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 /* Add a watchpoint. */
785 int cpu_watchpoint_insert(CPUState
*cpu
, vaddr addr
, vaddr len
,
786 int flags
, CPUWatchpoint
**watchpoint
)
791 /* forbid ranges which are empty or run off the end of the address space */
792 if (len
== 0 || (addr
+ len
- 1) < addr
) {
793 error_report("tried to set invalid watchpoint at %"
794 VADDR_PRIx
", len=%" VADDR_PRIu
, addr
, len
);
797 wp
= g_malloc(sizeof(*wp
));
803 /* keep all GDB-injected watchpoints in front */
804 if (flags
& BP_GDB
) {
805 QTAILQ_INSERT_HEAD(&cpu
->watchpoints
, wp
, entry
);
807 QTAILQ_INSERT_TAIL(&cpu
->watchpoints
, wp
, entry
);
810 in_page
= -(addr
| TARGET_PAGE_MASK
);
811 if (len
<= in_page
) {
812 tlb_flush_page(cpu
, addr
);
822 /* Remove a specific watchpoint. */
823 int cpu_watchpoint_remove(CPUState
*cpu
, vaddr addr
, vaddr len
,
828 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
829 if (addr
== wp
->vaddr
&& len
== wp
->len
830 && flags
== (wp
->flags
& ~BP_WATCHPOINT_HIT
)) {
831 cpu_watchpoint_remove_by_ref(cpu
, wp
);
838 /* Remove a specific watchpoint by reference. */
839 void cpu_watchpoint_remove_by_ref(CPUState
*cpu
, CPUWatchpoint
*watchpoint
)
841 QTAILQ_REMOVE(&cpu
->watchpoints
, watchpoint
, entry
);
843 tlb_flush_page(cpu
, watchpoint
->vaddr
);
848 /* Remove all matching watchpoints. */
849 void cpu_watchpoint_remove_all(CPUState
*cpu
, int mask
)
851 CPUWatchpoint
*wp
, *next
;
853 QTAILQ_FOREACH_SAFE(wp
, &cpu
->watchpoints
, entry
, next
) {
854 if (wp
->flags
& mask
) {
855 cpu_watchpoint_remove_by_ref(cpu
, wp
);
861 /* Return true if this watchpoint address matches the specified
862 * access (ie the address range covered by the watchpoint overlaps
863 * partially or completely with the address range covered by the
866 static inline bool watchpoint_address_matches(CPUWatchpoint
*wp
,
867 vaddr addr
, vaddr len
)
869 /* We know the lengths are non-zero, but a little caution is
870 * required to avoid errors in the case where the range ends
871 * exactly at the top of the address space and so addr + len
872 * wraps round to zero.
874 vaddr wpend
= wp
->vaddr
+ wp
->len
- 1;
875 vaddr addrend
= addr
+ len
- 1;
877 return !(addr
> wpend
|| wp
->vaddr
> addrend
);
880 /* Return flags for watchpoints that match addr + prot. */
881 int cpu_watchpoint_address_matches(CPUState
*cpu
, vaddr addr
, vaddr len
)
886 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
887 if (watchpoint_address_matches(wp
, addr
, len
)) {
894 /* Generate a debug exception if a watchpoint has been hit. */
895 void cpu_check_watchpoint(CPUState
*cpu
, vaddr addr
, vaddr len
,
896 MemTxAttrs attrs
, int flags
, uintptr_t ra
)
898 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
901 assert(tcg_enabled());
902 if (cpu
->watchpoint_hit
) {
904 * We re-entered the check after replacing the TB.
905 * Now raise the debug interrupt so that it will
906 * trigger after the current instruction.
908 qemu_mutex_lock_iothread();
909 cpu_interrupt(cpu
, CPU_INTERRUPT_DEBUG
);
910 qemu_mutex_unlock_iothread();
914 if (cc
->tcg_ops
->adjust_watchpoint_address
) {
915 /* this is currently used only by ARM BE32 */
916 addr
= cc
->tcg_ops
->adjust_watchpoint_address(cpu
, addr
, len
);
918 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
919 if (watchpoint_address_matches(wp
, addr
, len
)
920 && (wp
->flags
& flags
)) {
921 if (replay_running_debug()) {
923 * replay_breakpoint reads icount.
924 * Force recompile to succeed, because icount may
925 * be read only at the end of the block.
927 if (!cpu
->can_do_io
) {
928 /* Force execution of one insn next time. */
929 cpu
->cflags_next_tb
= 1 | CF_LAST_IO
| CF_NOIRQ
| curr_cflags(cpu
);
930 cpu_loop_exit_restore(cpu
, ra
);
933 * Don't process the watchpoints when we are
934 * in a reverse debugging operation.
939 if (flags
== BP_MEM_READ
) {
940 wp
->flags
|= BP_WATCHPOINT_HIT_READ
;
942 wp
->flags
|= BP_WATCHPOINT_HIT_WRITE
;
944 wp
->hitaddr
= MAX(addr
, wp
->vaddr
);
945 wp
->hitattrs
= attrs
;
947 if (wp
->flags
& BP_CPU
&& cc
->tcg_ops
->debug_check_watchpoint
&&
948 !cc
->tcg_ops
->debug_check_watchpoint(cpu
, wp
)) {
949 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
952 cpu
->watchpoint_hit
= wp
;
955 /* This call also restores vCPU state */
956 tb_check_watchpoint(cpu
, ra
);
957 if (wp
->flags
& BP_STOP_BEFORE_ACCESS
) {
958 cpu
->exception_index
= EXCP_DEBUG
;
962 /* Force execution of one insn next time. */
963 cpu
->cflags_next_tb
= 1 | CF_LAST_IO
| CF_NOIRQ
| curr_cflags(cpu
);
965 cpu_loop_exit_noexc(cpu
);
968 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
973 #endif /* CONFIG_TCG */
975 /* Called from RCU critical section */
976 static RAMBlock
*qemu_get_ram_block(ram_addr_t addr
)
980 block
= qatomic_rcu_read(&ram_list
.mru_block
);
981 if (block
&& addr
- block
->offset
< block
->max_length
) {
984 RAMBLOCK_FOREACH(block
) {
985 if (addr
- block
->offset
< block
->max_length
) {
990 fprintf(stderr
, "Bad ram offset %" PRIx64
"\n", (uint64_t)addr
);
994 /* It is safe to write mru_block outside the iothread lock. This
999 * xxx removed from list
1003 * call_rcu(reclaim_ramblock, xxx);
1006 * qatomic_rcu_set is not needed here. The block was already published
1007 * when it was placed into the list. Here we're just making an extra
1008 * copy of the pointer.
1010 ram_list
.mru_block
= block
;
1014 static void tlb_reset_dirty_range_all(ram_addr_t start
, ram_addr_t length
)
1021 assert(tcg_enabled());
1022 end
= TARGET_PAGE_ALIGN(start
+ length
);
1023 start
&= TARGET_PAGE_MASK
;
1025 RCU_READ_LOCK_GUARD();
1026 block
= qemu_get_ram_block(start
);
1027 assert(block
== qemu_get_ram_block(end
- 1));
1028 start1
= (uintptr_t)ramblock_ptr(block
, start
- block
->offset
);
1030 tlb_reset_dirty(cpu
, start1
, length
);
1034 /* Note: start and end must be within the same ram block. */
1035 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start
,
1039 DirtyMemoryBlocks
*blocks
;
1040 unsigned long end
, page
, start_page
;
1043 uint64_t mr_offset
, mr_size
;
1049 end
= TARGET_PAGE_ALIGN(start
+ length
) >> TARGET_PAGE_BITS
;
1050 start_page
= start
>> TARGET_PAGE_BITS
;
1053 WITH_RCU_READ_LOCK_GUARD() {
1054 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1055 ramblock
= qemu_get_ram_block(start
);
1056 /* Range sanity check on the ramblock */
1057 assert(start
>= ramblock
->offset
&&
1058 start
+ length
<= ramblock
->offset
+ ramblock
->used_length
);
1060 while (page
< end
) {
1061 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1062 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1063 unsigned long num
= MIN(end
- page
,
1064 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1066 dirty
|= bitmap_test_and_clear_atomic(blocks
->blocks
[idx
],
1071 mr_offset
= (ram_addr_t
)(start_page
<< TARGET_PAGE_BITS
) - ramblock
->offset
;
1072 mr_size
= (end
- start_page
) << TARGET_PAGE_BITS
;
1073 memory_region_clear_dirty_bitmap(ramblock
->mr
, mr_offset
, mr_size
);
1076 if (dirty
&& tcg_enabled()) {
1077 tlb_reset_dirty_range_all(start
, length
);
1083 DirtyBitmapSnapshot
*cpu_physical_memory_snapshot_and_clear_dirty
1084 (MemoryRegion
*mr
, hwaddr offset
, hwaddr length
, unsigned client
)
1086 DirtyMemoryBlocks
*blocks
;
1087 ram_addr_t start
= memory_region_get_ram_addr(mr
) + offset
;
1088 unsigned long align
= 1UL << (TARGET_PAGE_BITS
+ BITS_PER_LEVEL
);
1089 ram_addr_t first
= QEMU_ALIGN_DOWN(start
, align
);
1090 ram_addr_t last
= QEMU_ALIGN_UP(start
+ length
, align
);
1091 DirtyBitmapSnapshot
*snap
;
1092 unsigned long page
, end
, dest
;
1094 snap
= g_malloc0(sizeof(*snap
) +
1095 ((last
- first
) >> (TARGET_PAGE_BITS
+ 3)));
1096 snap
->start
= first
;
1099 page
= first
>> TARGET_PAGE_BITS
;
1100 end
= last
>> TARGET_PAGE_BITS
;
1103 WITH_RCU_READ_LOCK_GUARD() {
1104 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1106 while (page
< end
) {
1107 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1108 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1109 unsigned long num
= MIN(end
- page
,
1110 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1112 assert(QEMU_IS_ALIGNED(offset
, (1 << BITS_PER_LEVEL
)));
1113 assert(QEMU_IS_ALIGNED(num
, (1 << BITS_PER_LEVEL
)));
1114 offset
>>= BITS_PER_LEVEL
;
1116 bitmap_copy_and_clear_atomic(snap
->dirty
+ dest
,
1117 blocks
->blocks
[idx
] + offset
,
1120 dest
+= num
>> BITS_PER_LEVEL
;
1124 if (tcg_enabled()) {
1125 tlb_reset_dirty_range_all(start
, length
);
1128 memory_region_clear_dirty_bitmap(mr
, offset
, length
);
1133 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot
*snap
,
1137 unsigned long page
, end
;
1139 assert(start
>= snap
->start
);
1140 assert(start
+ length
<= snap
->end
);
1142 end
= TARGET_PAGE_ALIGN(start
+ length
- snap
->start
) >> TARGET_PAGE_BITS
;
1143 page
= (start
- snap
->start
) >> TARGET_PAGE_BITS
;
1145 while (page
< end
) {
1146 if (test_bit(page
, snap
->dirty
)) {
1154 /* Called from RCU critical section */
1155 hwaddr
memory_region_section_get_iotlb(CPUState
*cpu
,
1156 MemoryRegionSection
*section
)
1158 AddressSpaceDispatch
*d
= flatview_to_dispatch(section
->fv
);
1159 return section
- d
->map
.sections
;
1162 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
1164 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
);
1166 static uint16_t phys_section_add(PhysPageMap
*map
,
1167 MemoryRegionSection
*section
)
1169 /* The physical section number is ORed with a page-aligned
1170 * pointer to produce the iotlb entries. Thus it should
1171 * never overflow into the page-aligned value.
1173 assert(map
->sections_nb
< TARGET_PAGE_SIZE
);
1175 if (map
->sections_nb
== map
->sections_nb_alloc
) {
1176 map
->sections_nb_alloc
= MAX(map
->sections_nb_alloc
* 2, 16);
1177 map
->sections
= g_renew(MemoryRegionSection
, map
->sections
,
1178 map
->sections_nb_alloc
);
1180 map
->sections
[map
->sections_nb
] = *section
;
1181 memory_region_ref(section
->mr
);
1182 return map
->sections_nb
++;
1185 static void phys_section_destroy(MemoryRegion
*mr
)
1187 bool have_sub_page
= mr
->subpage
;
1189 memory_region_unref(mr
);
1191 if (have_sub_page
) {
1192 subpage_t
*subpage
= container_of(mr
, subpage_t
, iomem
);
1193 object_unref(OBJECT(&subpage
->iomem
));
1198 static void phys_sections_free(PhysPageMap
*map
)
1200 while (map
->sections_nb
> 0) {
1201 MemoryRegionSection
*section
= &map
->sections
[--map
->sections_nb
];
1202 phys_section_destroy(section
->mr
);
1204 g_free(map
->sections
);
1208 static void register_subpage(FlatView
*fv
, MemoryRegionSection
*section
)
1210 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1212 hwaddr base
= section
->offset_within_address_space
1214 MemoryRegionSection
*existing
= phys_page_find(d
, base
);
1215 MemoryRegionSection subsection
= {
1216 .offset_within_address_space
= base
,
1217 .size
= int128_make64(TARGET_PAGE_SIZE
),
1221 assert(existing
->mr
->subpage
|| existing
->mr
== &io_mem_unassigned
);
1223 if (!(existing
->mr
->subpage
)) {
1224 subpage
= subpage_init(fv
, base
);
1226 subsection
.mr
= &subpage
->iomem
;
1227 phys_page_set(d
, base
>> TARGET_PAGE_BITS
, 1,
1228 phys_section_add(&d
->map
, &subsection
));
1230 subpage
= container_of(existing
->mr
, subpage_t
, iomem
);
1232 start
= section
->offset_within_address_space
& ~TARGET_PAGE_MASK
;
1233 end
= start
+ int128_get64(section
->size
) - 1;
1234 subpage_register(subpage
, start
, end
,
1235 phys_section_add(&d
->map
, section
));
1239 static void register_multipage(FlatView
*fv
,
1240 MemoryRegionSection
*section
)
1242 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1243 hwaddr start_addr
= section
->offset_within_address_space
;
1244 uint16_t section_index
= phys_section_add(&d
->map
, section
);
1245 uint64_t num_pages
= int128_get64(int128_rshift(section
->size
,
1249 phys_page_set(d
, start_addr
>> TARGET_PAGE_BITS
, num_pages
, section_index
);
1253 * The range in *section* may look like this:
1257 * where s stands for subpage and P for page.
1259 void flatview_add_to_dispatch(FlatView
*fv
, MemoryRegionSection
*section
)
1261 MemoryRegionSection remain
= *section
;
1262 Int128 page_size
= int128_make64(TARGET_PAGE_SIZE
);
1264 /* register first subpage */
1265 if (remain
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1266 uint64_t left
= TARGET_PAGE_ALIGN(remain
.offset_within_address_space
)
1267 - remain
.offset_within_address_space
;
1269 MemoryRegionSection now
= remain
;
1270 now
.size
= int128_min(int128_make64(left
), now
.size
);
1271 register_subpage(fv
, &now
);
1272 if (int128_eq(remain
.size
, now
.size
)) {
1275 remain
.size
= int128_sub(remain
.size
, now
.size
);
1276 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1277 remain
.offset_within_region
+= int128_get64(now
.size
);
1280 /* register whole pages */
1281 if (int128_ge(remain
.size
, page_size
)) {
1282 MemoryRegionSection now
= remain
;
1283 now
.size
= int128_and(now
.size
, int128_neg(page_size
));
1284 register_multipage(fv
, &now
);
1285 if (int128_eq(remain
.size
, now
.size
)) {
1288 remain
.size
= int128_sub(remain
.size
, now
.size
);
1289 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1290 remain
.offset_within_region
+= int128_get64(now
.size
);
1293 /* register last subpage */
1294 register_subpage(fv
, &remain
);
1297 void qemu_flush_coalesced_mmio_buffer(void)
1300 kvm_flush_coalesced_mmio_buffer();
1303 void qemu_mutex_lock_ramlist(void)
1305 qemu_mutex_lock(&ram_list
.mutex
);
1308 void qemu_mutex_unlock_ramlist(void)
1310 qemu_mutex_unlock(&ram_list
.mutex
);
1313 GString
*ram_block_format(void)
1317 GString
*buf
= g_string_new("");
1319 RCU_READ_LOCK_GUARD();
1320 g_string_append_printf(buf
, "%24s %8s %18s %18s %18s\n",
1321 "Block Name", "PSize", "Offset", "Used", "Total");
1322 RAMBLOCK_FOREACH(block
) {
1323 psize
= size_to_str(block
->page_size
);
1324 g_string_append_printf(buf
, "%24s %8s 0x%016" PRIx64
" 0x%016" PRIx64
1325 " 0x%016" PRIx64
"\n", block
->idstr
, psize
,
1326 (uint64_t)block
->offset
,
1327 (uint64_t)block
->used_length
,
1328 (uint64_t)block
->max_length
);
1335 static int find_min_backend_pagesize(Object
*obj
, void *opaque
)
1337 long *hpsize_min
= opaque
;
1339 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1340 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1341 long hpsize
= host_memory_backend_pagesize(backend
);
1343 if (host_memory_backend_is_mapped(backend
) && (hpsize
< *hpsize_min
)) {
1344 *hpsize_min
= hpsize
;
1351 static int find_max_backend_pagesize(Object
*obj
, void *opaque
)
1353 long *hpsize_max
= opaque
;
1355 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1356 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1357 long hpsize
= host_memory_backend_pagesize(backend
);
1359 if (host_memory_backend_is_mapped(backend
) && (hpsize
> *hpsize_max
)) {
1360 *hpsize_max
= hpsize
;
1368 * TODO: We assume right now that all mapped host memory backends are
1369 * used as RAM, however some might be used for different purposes.
1371 long qemu_minrampagesize(void)
1373 long hpsize
= LONG_MAX
;
1374 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1376 object_child_foreach(memdev_root
, find_min_backend_pagesize
, &hpsize
);
1380 long qemu_maxrampagesize(void)
1383 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1385 object_child_foreach(memdev_root
, find_max_backend_pagesize
, &pagesize
);
1390 static int64_t get_file_size(int fd
)
1393 #if defined(__linux__)
1396 if (fstat(fd
, &st
) < 0) {
1400 /* Special handling for devdax character devices */
1401 if (S_ISCHR(st
.st_mode
)) {
1402 g_autofree
char *subsystem_path
= NULL
;
1403 g_autofree
char *subsystem
= NULL
;
1405 subsystem_path
= g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1406 major(st
.st_rdev
), minor(st
.st_rdev
));
1407 subsystem
= g_file_read_link(subsystem_path
, NULL
);
1409 if (subsystem
&& g_str_has_suffix(subsystem
, "/dax")) {
1410 g_autofree
char *size_path
= NULL
;
1411 g_autofree
char *size_str
= NULL
;
1413 size_path
= g_strdup_printf("/sys/dev/char/%d:%d/size",
1414 major(st
.st_rdev
), minor(st
.st_rdev
));
1416 if (g_file_get_contents(size_path
, &size_str
, NULL
, NULL
)) {
1417 return g_ascii_strtoll(size_str
, NULL
, 0);
1421 #endif /* defined(__linux__) */
1423 /* st.st_size may be zero for special files yet lseek(2) works */
1424 size
= lseek(fd
, 0, SEEK_END
);
1431 static int64_t get_file_align(int fd
)
1434 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1437 if (fstat(fd
, &st
) < 0) {
1441 /* Special handling for devdax character devices */
1442 if (S_ISCHR(st
.st_mode
)) {
1443 g_autofree
char *path
= NULL
;
1444 g_autofree
char *rpath
= NULL
;
1445 struct daxctl_ctx
*ctx
;
1446 struct daxctl_region
*region
;
1449 path
= g_strdup_printf("/sys/dev/char/%d:%d",
1450 major(st
.st_rdev
), minor(st
.st_rdev
));
1451 rpath
= realpath(path
, NULL
);
1456 rc
= daxctl_new(&ctx
);
1461 daxctl_region_foreach(ctx
, region
) {
1462 if (strstr(rpath
, daxctl_region_get_path(region
))) {
1463 align
= daxctl_region_get_align(region
);
1469 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1474 static int file_ram_open(const char *path
,
1475 const char *region_name
,
1481 char *sanitized_name
;
1487 fd
= open(path
, readonly
? O_RDONLY
: O_RDWR
);
1489 /* @path names an existing file, use it */
1492 if (errno
== ENOENT
) {
1493 /* @path names a file that doesn't exist, create it */
1494 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0644);
1499 } else if (errno
== EISDIR
) {
1500 /* @path names a directory, create a file there */
1501 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1502 sanitized_name
= g_strdup(region_name
);
1503 for (c
= sanitized_name
; *c
!= '\0'; c
++) {
1509 filename
= g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path
,
1511 g_free(sanitized_name
);
1513 fd
= mkstemp(filename
);
1521 if (errno
!= EEXIST
&& errno
!= EINTR
) {
1522 error_setg_errno(errp
, errno
,
1523 "can't open backing store %s for guest RAM",
1528 * Try again on EINTR and EEXIST. The latter happens when
1529 * something else creates the file between our two open().
1536 static void *file_ram_alloc(RAMBlock
*block
,
1544 uint32_t qemu_map_flags
;
1547 block
->page_size
= qemu_fd_getpagesize(fd
);
1548 if (block
->mr
->align
% block
->page_size
) {
1549 error_setg(errp
, "alignment 0x%" PRIx64
1550 " must be multiples of page size 0x%zx",
1551 block
->mr
->align
, block
->page_size
);
1553 } else if (block
->mr
->align
&& !is_power_of_2(block
->mr
->align
)) {
1554 error_setg(errp
, "alignment 0x%" PRIx64
1555 " must be a power of two", block
->mr
->align
);
1558 block
->mr
->align
= MAX(block
->page_size
, block
->mr
->align
);
1559 #if defined(__s390x__)
1560 if (kvm_enabled()) {
1561 block
->mr
->align
= MAX(block
->mr
->align
, QEMU_VMALLOC_ALIGN
);
1565 if (memory
< block
->page_size
) {
1566 error_setg(errp
, "memory size 0x" RAM_ADDR_FMT
" must be equal to "
1567 "or larger than page size 0x%zx",
1568 memory
, block
->page_size
);
1572 memory
= ROUND_UP(memory
, block
->page_size
);
1575 * ftruncate is not supported by hugetlbfs in older
1576 * hosts, so don't bother bailing out on errors.
1577 * If anything goes wrong with it under other filesystems,
1580 * Do not truncate the non-empty backend file to avoid corrupting
1581 * the existing data in the file. Disabling shrinking is not
1582 * enough. For example, the current vNVDIMM implementation stores
1583 * the guest NVDIMM labels at the end of the backend file. If the
1584 * backend file is later extended, QEMU will not be able to find
1585 * those labels. Therefore, extending the non-empty backend file
1586 * is disabled as well.
1588 if (truncate
&& ftruncate(fd
, memory
)) {
1589 perror("ftruncate");
1592 qemu_map_flags
= readonly
? QEMU_MAP_READONLY
: 0;
1593 qemu_map_flags
|= (block
->flags
& RAM_SHARED
) ? QEMU_MAP_SHARED
: 0;
1594 qemu_map_flags
|= (block
->flags
& RAM_PMEM
) ? QEMU_MAP_SYNC
: 0;
1595 qemu_map_flags
|= (block
->flags
& RAM_NORESERVE
) ? QEMU_MAP_NORESERVE
: 0;
1596 area
= qemu_ram_mmap(fd
, memory
, block
->mr
->align
, qemu_map_flags
, offset
);
1597 if (area
== MAP_FAILED
) {
1598 error_setg_errno(errp
, errno
,
1599 "unable to map backing store for guest RAM");
1608 /* Allocate space within the ram_addr_t space that governs the
1610 * Called with the ramlist lock held.
1612 static ram_addr_t
find_ram_offset(ram_addr_t size
)
1614 RAMBlock
*block
, *next_block
;
1615 ram_addr_t offset
= RAM_ADDR_MAX
, mingap
= RAM_ADDR_MAX
;
1617 assert(size
!= 0); /* it would hand out same offset multiple times */
1619 if (QLIST_EMPTY_RCU(&ram_list
.blocks
)) {
1623 RAMBLOCK_FOREACH(block
) {
1624 ram_addr_t candidate
, next
= RAM_ADDR_MAX
;
1626 /* Align blocks to start on a 'long' in the bitmap
1627 * which makes the bitmap sync'ing take the fast path.
1629 candidate
= block
->offset
+ block
->max_length
;
1630 candidate
= ROUND_UP(candidate
, BITS_PER_LONG
<< TARGET_PAGE_BITS
);
1632 /* Search for the closest following block
1635 RAMBLOCK_FOREACH(next_block
) {
1636 if (next_block
->offset
>= candidate
) {
1637 next
= MIN(next
, next_block
->offset
);
1641 /* If it fits remember our place and remember the size
1642 * of gap, but keep going so that we might find a smaller
1643 * gap to fill so avoiding fragmentation.
1645 if (next
- candidate
>= size
&& next
- candidate
< mingap
) {
1647 mingap
= next
- candidate
;
1650 trace_find_ram_offset_loop(size
, candidate
, offset
, next
, mingap
);
1653 if (offset
== RAM_ADDR_MAX
) {
1654 fprintf(stderr
, "Failed to find gap of requested size: %" PRIu64
"\n",
1659 trace_find_ram_offset(size
, offset
);
1664 static unsigned long last_ram_page(void)
1667 ram_addr_t last
= 0;
1669 RCU_READ_LOCK_GUARD();
1670 RAMBLOCK_FOREACH(block
) {
1671 last
= MAX(last
, block
->offset
+ block
->max_length
);
1673 return last
>> TARGET_PAGE_BITS
;
1676 static void qemu_ram_setup_dump(void *addr
, ram_addr_t size
)
1680 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1681 if (!machine_dump_guest_core(current_machine
)) {
1682 ret
= qemu_madvise(addr
, size
, QEMU_MADV_DONTDUMP
);
1684 perror("qemu_madvise");
1685 fprintf(stderr
, "madvise doesn't support MADV_DONTDUMP, "
1686 "but dump_guest_core=off specified\n");
1691 const char *qemu_ram_get_idstr(RAMBlock
*rb
)
1696 void *qemu_ram_get_host_addr(RAMBlock
*rb
)
1701 ram_addr_t
qemu_ram_get_offset(RAMBlock
*rb
)
1706 ram_addr_t
qemu_ram_get_used_length(RAMBlock
*rb
)
1708 return rb
->used_length
;
1711 ram_addr_t
qemu_ram_get_max_length(RAMBlock
*rb
)
1713 return rb
->max_length
;
1716 bool qemu_ram_is_shared(RAMBlock
*rb
)
1718 return rb
->flags
& RAM_SHARED
;
1721 bool qemu_ram_is_noreserve(RAMBlock
*rb
)
1723 return rb
->flags
& RAM_NORESERVE
;
1726 /* Note: Only set at the start of postcopy */
1727 bool qemu_ram_is_uf_zeroable(RAMBlock
*rb
)
1729 return rb
->flags
& RAM_UF_ZEROPAGE
;
1732 void qemu_ram_set_uf_zeroable(RAMBlock
*rb
)
1734 rb
->flags
|= RAM_UF_ZEROPAGE
;
1737 bool qemu_ram_is_migratable(RAMBlock
*rb
)
1739 return rb
->flags
& RAM_MIGRATABLE
;
1742 void qemu_ram_set_migratable(RAMBlock
*rb
)
1744 rb
->flags
|= RAM_MIGRATABLE
;
1747 void qemu_ram_unset_migratable(RAMBlock
*rb
)
1749 rb
->flags
&= ~RAM_MIGRATABLE
;
1752 int qemu_ram_get_fd(RAMBlock
*rb
)
1757 /* Called with iothread lock held. */
1758 void qemu_ram_set_idstr(RAMBlock
*new_block
, const char *name
, DeviceState
*dev
)
1763 assert(!new_block
->idstr
[0]);
1766 char *id
= qdev_get_dev_path(dev
);
1768 snprintf(new_block
->idstr
, sizeof(new_block
->idstr
), "%s/", id
);
1772 pstrcat(new_block
->idstr
, sizeof(new_block
->idstr
), name
);
1774 RCU_READ_LOCK_GUARD();
1775 RAMBLOCK_FOREACH(block
) {
1776 if (block
!= new_block
&&
1777 !strcmp(block
->idstr
, new_block
->idstr
)) {
1778 fprintf(stderr
, "RAMBlock \"%s\" already registered, abort!\n",
1785 /* Called with iothread lock held. */
1786 void qemu_ram_unset_idstr(RAMBlock
*block
)
1788 /* FIXME: arch_init.c assumes that this is not called throughout
1789 * migration. Ignore the problem since hot-unplug during migration
1790 * does not work anyway.
1793 memset(block
->idstr
, 0, sizeof(block
->idstr
));
1797 size_t qemu_ram_pagesize(RAMBlock
*rb
)
1799 return rb
->page_size
;
1802 /* Returns the largest size of page in use */
1803 size_t qemu_ram_pagesize_largest(void)
1808 RAMBLOCK_FOREACH(block
) {
1809 largest
= MAX(largest
, qemu_ram_pagesize(block
));
1815 static int memory_try_enable_merging(void *addr
, size_t len
)
1817 if (!machine_mem_merge(current_machine
)) {
1818 /* disabled by the user */
1822 return qemu_madvise(addr
, len
, QEMU_MADV_MERGEABLE
);
1826 * Resizing RAM while migrating can result in the migration being canceled.
1827 * Care has to be taken if the guest might have already detected the memory.
1829 * As memory core doesn't know how is memory accessed, it is up to
1830 * resize callback to update device state and/or add assertions to detect
1831 * misuse, if necessary.
1833 int qemu_ram_resize(RAMBlock
*block
, ram_addr_t newsize
, Error
**errp
)
1835 const ram_addr_t oldsize
= block
->used_length
;
1836 const ram_addr_t unaligned_size
= newsize
;
1840 newsize
= HOST_PAGE_ALIGN(newsize
);
1842 if (block
->used_length
== newsize
) {
1844 * We don't have to resize the ram block (which only knows aligned
1845 * sizes), however, we have to notify if the unaligned size changed.
1847 if (unaligned_size
!= memory_region_size(block
->mr
)) {
1848 memory_region_set_size(block
->mr
, unaligned_size
);
1849 if (block
->resized
) {
1850 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1856 if (!(block
->flags
& RAM_RESIZEABLE
)) {
1857 error_setg_errno(errp
, EINVAL
,
1858 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1859 " != 0x" RAM_ADDR_FMT
, block
->idstr
,
1860 newsize
, block
->used_length
);
1864 if (block
->max_length
< newsize
) {
1865 error_setg_errno(errp
, EINVAL
,
1866 "Size too large: %s: 0x" RAM_ADDR_FMT
1867 " > 0x" RAM_ADDR_FMT
, block
->idstr
,
1868 newsize
, block
->max_length
);
1872 /* Notify before modifying the ram block and touching the bitmaps. */
1874 ram_block_notify_resize(block
->host
, oldsize
, newsize
);
1877 cpu_physical_memory_clear_dirty_range(block
->offset
, block
->used_length
);
1878 block
->used_length
= newsize
;
1879 cpu_physical_memory_set_dirty_range(block
->offset
, block
->used_length
,
1881 memory_region_set_size(block
->mr
, unaligned_size
);
1882 if (block
->resized
) {
1883 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1889 * Trigger sync on the given ram block for range [start, start + length]
1890 * with the backing store if one is available.
1892 * @Note: this is supposed to be a synchronous op.
1894 void qemu_ram_msync(RAMBlock
*block
, ram_addr_t start
, ram_addr_t length
)
1896 /* The requested range should fit in within the block range */
1897 g_assert((start
+ length
) <= block
->used_length
);
1899 #ifdef CONFIG_LIBPMEM
1900 /* The lack of support for pmem should not block the sync */
1901 if (ramblock_is_pmem(block
)) {
1902 void *addr
= ramblock_ptr(block
, start
);
1903 pmem_persist(addr
, length
);
1907 if (block
->fd
>= 0) {
1909 * Case there is no support for PMEM or the memory has not been
1910 * specified as persistent (or is not one) - use the msync.
1911 * Less optimal but still achieves the same goal
1913 void *addr
= ramblock_ptr(block
, start
);
1914 if (qemu_msync(addr
, length
, block
->fd
)) {
1915 warn_report("%s: failed to sync memory range: start: "
1916 RAM_ADDR_FMT
" length: " RAM_ADDR_FMT
,
1917 __func__
, start
, length
);
1922 /* Called with ram_list.mutex held */
1923 static void dirty_memory_extend(ram_addr_t old_ram_size
,
1924 ram_addr_t new_ram_size
)
1926 ram_addr_t old_num_blocks
= DIV_ROUND_UP(old_ram_size
,
1927 DIRTY_MEMORY_BLOCK_SIZE
);
1928 ram_addr_t new_num_blocks
= DIV_ROUND_UP(new_ram_size
,
1929 DIRTY_MEMORY_BLOCK_SIZE
);
1932 /* Only need to extend if block count increased */
1933 if (new_num_blocks
<= old_num_blocks
) {
1937 for (i
= 0; i
< DIRTY_MEMORY_NUM
; i
++) {
1938 DirtyMemoryBlocks
*old_blocks
;
1939 DirtyMemoryBlocks
*new_blocks
;
1942 old_blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[i
]);
1943 new_blocks
= g_malloc(sizeof(*new_blocks
) +
1944 sizeof(new_blocks
->blocks
[0]) * new_num_blocks
);
1946 if (old_num_blocks
) {
1947 memcpy(new_blocks
->blocks
, old_blocks
->blocks
,
1948 old_num_blocks
* sizeof(old_blocks
->blocks
[0]));
1951 for (j
= old_num_blocks
; j
< new_num_blocks
; j
++) {
1952 new_blocks
->blocks
[j
] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE
);
1955 qatomic_rcu_set(&ram_list
.dirty_memory
[i
], new_blocks
);
1958 g_free_rcu(old_blocks
, rcu
);
1963 static void ram_block_add(RAMBlock
*new_block
, Error
**errp
)
1965 const bool noreserve
= qemu_ram_is_noreserve(new_block
);
1966 const bool shared
= qemu_ram_is_shared(new_block
);
1968 RAMBlock
*last_block
= NULL
;
1969 ram_addr_t old_ram_size
, new_ram_size
;
1972 old_ram_size
= last_ram_page();
1974 qemu_mutex_lock_ramlist();
1975 new_block
->offset
= find_ram_offset(new_block
->max_length
);
1977 if (!new_block
->host
) {
1978 if (xen_enabled()) {
1979 xen_ram_alloc(new_block
->offset
, new_block
->max_length
,
1980 new_block
->mr
, &err
);
1982 error_propagate(errp
, err
);
1983 qemu_mutex_unlock_ramlist();
1987 new_block
->host
= qemu_anon_ram_alloc(new_block
->max_length
,
1988 &new_block
->mr
->align
,
1990 if (!new_block
->host
) {
1991 error_setg_errno(errp
, errno
,
1992 "cannot set up guest memory '%s'",
1993 memory_region_name(new_block
->mr
));
1994 qemu_mutex_unlock_ramlist();
1997 memory_try_enable_merging(new_block
->host
, new_block
->max_length
);
2001 new_ram_size
= MAX(old_ram_size
,
2002 (new_block
->offset
+ new_block
->max_length
) >> TARGET_PAGE_BITS
);
2003 if (new_ram_size
> old_ram_size
) {
2004 dirty_memory_extend(old_ram_size
, new_ram_size
);
2006 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2007 * QLIST (which has an RCU-friendly variant) does not have insertion at
2008 * tail, so save the last element in last_block.
2010 RAMBLOCK_FOREACH(block
) {
2012 if (block
->max_length
< new_block
->max_length
) {
2017 QLIST_INSERT_BEFORE_RCU(block
, new_block
, next
);
2018 } else if (last_block
) {
2019 QLIST_INSERT_AFTER_RCU(last_block
, new_block
, next
);
2020 } else { /* list is empty */
2021 QLIST_INSERT_HEAD_RCU(&ram_list
.blocks
, new_block
, next
);
2023 ram_list
.mru_block
= NULL
;
2025 /* Write list before version */
2028 qemu_mutex_unlock_ramlist();
2030 cpu_physical_memory_set_dirty_range(new_block
->offset
,
2031 new_block
->used_length
,
2034 if (new_block
->host
) {
2035 qemu_ram_setup_dump(new_block
->host
, new_block
->max_length
);
2036 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_HUGEPAGE
);
2038 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
2039 * Configure it unless the machine is a qtest server, in which case
2040 * KVM is not used and it may be forked (eg for fuzzing purposes).
2042 if (!qtest_enabled()) {
2043 qemu_madvise(new_block
->host
, new_block
->max_length
,
2044 QEMU_MADV_DONTFORK
);
2046 ram_block_notify_add(new_block
->host
, new_block
->used_length
,
2047 new_block
->max_length
);
2052 RAMBlock
*qemu_ram_alloc_from_fd(ram_addr_t size
, MemoryRegion
*mr
,
2053 uint32_t ram_flags
, int fd
, off_t offset
,
2054 bool readonly
, Error
**errp
)
2056 RAMBlock
*new_block
;
2057 Error
*local_err
= NULL
;
2058 int64_t file_size
, file_align
;
2060 /* Just support these ram flags by now. */
2061 assert((ram_flags
& ~(RAM_SHARED
| RAM_PMEM
| RAM_NORESERVE
|
2062 RAM_PROTECTED
)) == 0);
2064 if (xen_enabled()) {
2065 error_setg(errp
, "-mem-path not supported with Xen");
2069 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2071 "host lacks kvm mmu notifiers, -mem-path unsupported");
2075 size
= HOST_PAGE_ALIGN(size
);
2076 file_size
= get_file_size(fd
);
2077 if (file_size
> 0 && file_size
< size
) {
2078 error_setg(errp
, "backing store size 0x%" PRIx64
2079 " does not match 'size' option 0x" RAM_ADDR_FMT
,
2084 file_align
= get_file_align(fd
);
2085 if (file_align
> 0 && file_align
> mr
->align
) {
2086 error_setg(errp
, "backing store align 0x%" PRIx64
2087 " is larger than 'align' option 0x%" PRIx64
,
2088 file_align
, mr
->align
);
2092 new_block
= g_malloc0(sizeof(*new_block
));
2094 new_block
->used_length
= size
;
2095 new_block
->max_length
= size
;
2096 new_block
->flags
= ram_flags
;
2097 new_block
->host
= file_ram_alloc(new_block
, size
, fd
, readonly
,
2098 !file_size
, offset
, errp
);
2099 if (!new_block
->host
) {
2104 ram_block_add(new_block
, &local_err
);
2107 error_propagate(errp
, local_err
);
2115 RAMBlock
*qemu_ram_alloc_from_file(ram_addr_t size
, MemoryRegion
*mr
,
2116 uint32_t ram_flags
, const char *mem_path
,
2117 bool readonly
, Error
**errp
)
2123 fd
= file_ram_open(mem_path
, memory_region_name(mr
), readonly
, &created
,
2129 block
= qemu_ram_alloc_from_fd(size
, mr
, ram_flags
, fd
, 0, readonly
, errp
);
2143 RAMBlock
*qemu_ram_alloc_internal(ram_addr_t size
, ram_addr_t max_size
,
2144 void (*resized
)(const char*,
2147 void *host
, uint32_t ram_flags
,
2148 MemoryRegion
*mr
, Error
**errp
)
2150 RAMBlock
*new_block
;
2151 Error
*local_err
= NULL
;
2153 assert((ram_flags
& ~(RAM_SHARED
| RAM_RESIZEABLE
| RAM_PREALLOC
|
2154 RAM_NORESERVE
)) == 0);
2155 assert(!host
^ (ram_flags
& RAM_PREALLOC
));
2157 size
= HOST_PAGE_ALIGN(size
);
2158 max_size
= HOST_PAGE_ALIGN(max_size
);
2159 new_block
= g_malloc0(sizeof(*new_block
));
2161 new_block
->resized
= resized
;
2162 new_block
->used_length
= size
;
2163 new_block
->max_length
= max_size
;
2164 assert(max_size
>= size
);
2166 new_block
->page_size
= qemu_real_host_page_size();
2167 new_block
->host
= host
;
2168 new_block
->flags
= ram_flags
;
2169 ram_block_add(new_block
, &local_err
);
2172 error_propagate(errp
, local_err
);
2178 RAMBlock
*qemu_ram_alloc_from_ptr(ram_addr_t size
, void *host
,
2179 MemoryRegion
*mr
, Error
**errp
)
2181 return qemu_ram_alloc_internal(size
, size
, NULL
, host
, RAM_PREALLOC
, mr
,
2185 RAMBlock
*qemu_ram_alloc(ram_addr_t size
, uint32_t ram_flags
,
2186 MemoryRegion
*mr
, Error
**errp
)
2188 assert((ram_flags
& ~(RAM_SHARED
| RAM_NORESERVE
)) == 0);
2189 return qemu_ram_alloc_internal(size
, size
, NULL
, NULL
, ram_flags
, mr
, errp
);
2192 RAMBlock
*qemu_ram_alloc_resizeable(ram_addr_t size
, ram_addr_t maxsz
,
2193 void (*resized
)(const char*,
2196 MemoryRegion
*mr
, Error
**errp
)
2198 return qemu_ram_alloc_internal(size
, maxsz
, resized
, NULL
,
2199 RAM_RESIZEABLE
, mr
, errp
);
2202 static void reclaim_ramblock(RAMBlock
*block
)
2204 if (block
->flags
& RAM_PREALLOC
) {
2206 } else if (xen_enabled()) {
2207 xen_invalidate_map_cache_entry(block
->host
);
2209 } else if (block
->fd
>= 0) {
2210 qemu_ram_munmap(block
->fd
, block
->host
, block
->max_length
);
2214 qemu_anon_ram_free(block
->host
, block
->max_length
);
2219 void qemu_ram_free(RAMBlock
*block
)
2226 ram_block_notify_remove(block
->host
, block
->used_length
,
2230 qemu_mutex_lock_ramlist();
2231 QLIST_REMOVE_RCU(block
, next
);
2232 ram_list
.mru_block
= NULL
;
2233 /* Write list before version */
2236 call_rcu(block
, reclaim_ramblock
, rcu
);
2237 qemu_mutex_unlock_ramlist();
2241 void qemu_ram_remap(ram_addr_t addr
, ram_addr_t length
)
2248 RAMBLOCK_FOREACH(block
) {
2249 offset
= addr
- block
->offset
;
2250 if (offset
< block
->max_length
) {
2251 vaddr
= ramblock_ptr(block
, offset
);
2252 if (block
->flags
& RAM_PREALLOC
) {
2254 } else if (xen_enabled()) {
2258 flags
|= block
->flags
& RAM_SHARED
?
2259 MAP_SHARED
: MAP_PRIVATE
;
2260 flags
|= block
->flags
& RAM_NORESERVE
? MAP_NORESERVE
: 0;
2261 if (block
->fd
>= 0) {
2262 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2263 flags
, block
->fd
, offset
);
2265 flags
|= MAP_ANONYMOUS
;
2266 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2269 if (area
!= vaddr
) {
2270 error_report("Could not remap addr: "
2271 RAM_ADDR_FMT
"@" RAM_ADDR_FMT
"",
2275 memory_try_enable_merging(vaddr
, length
);
2276 qemu_ram_setup_dump(vaddr
, length
);
2281 #endif /* !_WIN32 */
2283 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2284 * This should not be used for general purpose DMA. Use address_space_map
2285 * or address_space_rw instead. For local memory (e.g. video ram) that the
2286 * device owns, use memory_region_get_ram_ptr.
2288 * Called within RCU critical section.
2290 void *qemu_map_ram_ptr(RAMBlock
*ram_block
, ram_addr_t addr
)
2292 RAMBlock
*block
= ram_block
;
2294 if (block
== NULL
) {
2295 block
= qemu_get_ram_block(addr
);
2296 addr
-= block
->offset
;
2299 if (xen_enabled() && block
->host
== NULL
) {
2300 /* We need to check if the requested address is in the RAM
2301 * because we don't want to map the entire memory in QEMU.
2302 * In that case just map until the end of the page.
2304 if (block
->offset
== 0) {
2305 return xen_map_cache(addr
, 0, 0, false);
2308 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, false);
2310 return ramblock_ptr(block
, addr
);
2313 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2314 * but takes a size argument.
2316 * Called within RCU critical section.
2318 static void *qemu_ram_ptr_length(RAMBlock
*ram_block
, ram_addr_t addr
,
2319 hwaddr
*size
, bool lock
)
2321 RAMBlock
*block
= ram_block
;
2326 if (block
== NULL
) {
2327 block
= qemu_get_ram_block(addr
);
2328 addr
-= block
->offset
;
2330 *size
= MIN(*size
, block
->max_length
- addr
);
2332 if (xen_enabled() && block
->host
== NULL
) {
2333 /* We need to check if the requested address is in the RAM
2334 * because we don't want to map the entire memory in QEMU.
2335 * In that case just map the requested area.
2337 if (block
->offset
== 0) {
2338 return xen_map_cache(addr
, *size
, lock
, lock
);
2341 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, lock
);
2344 return ramblock_ptr(block
, addr
);
2347 /* Return the offset of a hostpointer within a ramblock */
2348 ram_addr_t
qemu_ram_block_host_offset(RAMBlock
*rb
, void *host
)
2350 ram_addr_t res
= (uint8_t *)host
- (uint8_t *)rb
->host
;
2351 assert((uintptr_t)host
>= (uintptr_t)rb
->host
);
2352 assert(res
< rb
->max_length
);
2358 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2361 * ptr: Host pointer to look up
2362 * round_offset: If true round the result offset down to a page boundary
2363 * *ram_addr: set to result ram_addr
2364 * *offset: set to result offset within the RAMBlock
2366 * Returns: RAMBlock (or NULL if not found)
2368 * By the time this function returns, the returned pointer is not protected
2369 * by RCU anymore. If the caller is not within an RCU critical section and
2370 * does not hold the iothread lock, it must have other means of protecting the
2371 * pointer, such as a reference to the region that includes the incoming
2374 RAMBlock
*qemu_ram_block_from_host(void *ptr
, bool round_offset
,
2378 uint8_t *host
= ptr
;
2380 if (xen_enabled()) {
2381 ram_addr_t ram_addr
;
2382 RCU_READ_LOCK_GUARD();
2383 ram_addr
= xen_ram_addr_from_mapcache(ptr
);
2384 block
= qemu_get_ram_block(ram_addr
);
2386 *offset
= ram_addr
- block
->offset
;
2391 RCU_READ_LOCK_GUARD();
2392 block
= qatomic_rcu_read(&ram_list
.mru_block
);
2393 if (block
&& block
->host
&& host
- block
->host
< block
->max_length
) {
2397 RAMBLOCK_FOREACH(block
) {
2398 /* This case append when the block is not mapped. */
2399 if (block
->host
== NULL
) {
2402 if (host
- block
->host
< block
->max_length
) {
2410 *offset
= (host
- block
->host
);
2412 *offset
&= TARGET_PAGE_MASK
;
2418 * Finds the named RAMBlock
2420 * name: The name of RAMBlock to find
2422 * Returns: RAMBlock (or NULL if not found)
2424 RAMBlock
*qemu_ram_block_by_name(const char *name
)
2428 RAMBLOCK_FOREACH(block
) {
2429 if (!strcmp(name
, block
->idstr
)) {
2437 /* Some of the softmmu routines need to translate from a host pointer
2438 (typically a TLB entry) back to a ram offset. */
2439 ram_addr_t
qemu_ram_addr_from_host(void *ptr
)
2444 block
= qemu_ram_block_from_host(ptr
, false, &offset
);
2446 return RAM_ADDR_INVALID
;
2449 return block
->offset
+ offset
;
2452 ram_addr_t
qemu_ram_addr_from_host_nofail(void *ptr
)
2454 ram_addr_t ram_addr
;
2456 ram_addr
= qemu_ram_addr_from_host(ptr
);
2457 if (ram_addr
== RAM_ADDR_INVALID
) {
2458 error_report("Bad ram pointer %p", ptr
);
2464 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2465 MemTxAttrs attrs
, void *buf
, hwaddr len
);
2466 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2467 const void *buf
, hwaddr len
);
2468 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
2469 bool is_write
, MemTxAttrs attrs
);
2471 static MemTxResult
subpage_read(void *opaque
, hwaddr addr
, uint64_t *data
,
2472 unsigned len
, MemTxAttrs attrs
)
2474 subpage_t
*subpage
= opaque
;
2478 #if defined(DEBUG_SUBPAGE)
2479 printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
"\n", __func__
,
2480 subpage
, len
, addr
);
2482 res
= flatview_read(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2486 *data
= ldn_p(buf
, len
);
2490 static MemTxResult
subpage_write(void *opaque
, hwaddr addr
,
2491 uint64_t value
, unsigned len
, MemTxAttrs attrs
)
2493 subpage_t
*subpage
= opaque
;
2496 #if defined(DEBUG_SUBPAGE)
2497 printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
2498 " value %"PRIx64
"\n",
2499 __func__
, subpage
, len
, addr
, value
);
2501 stn_p(buf
, len
, value
);
2502 return flatview_write(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2505 static bool subpage_accepts(void *opaque
, hwaddr addr
,
2506 unsigned len
, bool is_write
,
2509 subpage_t
*subpage
= opaque
;
2510 #if defined(DEBUG_SUBPAGE)
2511 printf("%s: subpage %p %c len %u addr " HWADDR_FMT_plx
"\n",
2512 __func__
, subpage
, is_write
? 'w' : 'r', len
, addr
);
2515 return flatview_access_valid(subpage
->fv
, addr
+ subpage
->base
,
2516 len
, is_write
, attrs
);
2519 static const MemoryRegionOps subpage_ops
= {
2520 .read_with_attrs
= subpage_read
,
2521 .write_with_attrs
= subpage_write
,
2522 .impl
.min_access_size
= 1,
2523 .impl
.max_access_size
= 8,
2524 .valid
.min_access_size
= 1,
2525 .valid
.max_access_size
= 8,
2526 .valid
.accepts
= subpage_accepts
,
2527 .endianness
= DEVICE_NATIVE_ENDIAN
,
2530 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
2535 if (start
>= TARGET_PAGE_SIZE
|| end
>= TARGET_PAGE_SIZE
)
2537 idx
= SUBPAGE_IDX(start
);
2538 eidx
= SUBPAGE_IDX(end
);
2539 #if defined(DEBUG_SUBPAGE)
2540 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2541 __func__
, mmio
, start
, end
, idx
, eidx
, section
);
2543 for (; idx
<= eidx
; idx
++) {
2544 mmio
->sub_section
[idx
] = section
;
2550 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
)
2554 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2555 mmio
= g_malloc0(sizeof(subpage_t
) + TARGET_PAGE_SIZE
* sizeof(uint16_t));
2558 memory_region_init_io(&mmio
->iomem
, NULL
, &subpage_ops
, mmio
,
2559 NULL
, TARGET_PAGE_SIZE
);
2560 mmio
->iomem
.subpage
= true;
2561 #if defined(DEBUG_SUBPAGE)
2562 printf("%s: %p base " HWADDR_FMT_plx
" len %08x\n", __func__
,
2563 mmio
, base
, TARGET_PAGE_SIZE
);
2569 static uint16_t dummy_section(PhysPageMap
*map
, FlatView
*fv
, MemoryRegion
*mr
)
2572 MemoryRegionSection section
= {
2575 .offset_within_address_space
= 0,
2576 .offset_within_region
= 0,
2577 .size
= int128_2_64(),
2580 return phys_section_add(map
, §ion
);
2583 MemoryRegionSection
*iotlb_to_section(CPUState
*cpu
,
2584 hwaddr index
, MemTxAttrs attrs
)
2586 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
2587 CPUAddressSpace
*cpuas
= &cpu
->cpu_ases
[asidx
];
2588 AddressSpaceDispatch
*d
= qatomic_rcu_read(&cpuas
->memory_dispatch
);
2589 MemoryRegionSection
*sections
= d
->map
.sections
;
2591 return §ions
[index
& ~TARGET_PAGE_MASK
];
2594 static void io_mem_init(void)
2596 memory_region_init_io(&io_mem_unassigned
, NULL
, &unassigned_mem_ops
, NULL
,
2600 AddressSpaceDispatch
*address_space_dispatch_new(FlatView
*fv
)
2602 AddressSpaceDispatch
*d
= g_new0(AddressSpaceDispatch
, 1);
2605 n
= dummy_section(&d
->map
, fv
, &io_mem_unassigned
);
2606 assert(n
== PHYS_SECTION_UNASSIGNED
);
2608 d
->phys_map
= (PhysPageEntry
) { .ptr
= PHYS_MAP_NODE_NIL
, .skip
= 1 };
2613 void address_space_dispatch_free(AddressSpaceDispatch
*d
)
2615 phys_sections_free(&d
->map
);
2619 static void do_nothing(CPUState
*cpu
, run_on_cpu_data d
)
2623 static void tcg_log_global_after_sync(MemoryListener
*listener
)
2625 CPUAddressSpace
*cpuas
;
2627 /* Wait for the CPU to end the current TB. This avoids the following
2631 * ---------------------- -------------------------
2632 * TLB check -> slow path
2633 * notdirty_mem_write
2637 * TLB check -> fast path
2641 * by pushing the migration thread's memory read after the vCPU thread has
2642 * written the memory.
2644 if (replay_mode
== REPLAY_MODE_NONE
) {
2646 * VGA can make calls to this function while updating the screen.
2647 * In record/replay mode this causes a deadlock, because
2648 * run_on_cpu waits for rr mutex. Therefore no races are possible
2649 * in this case and no need for making run_on_cpu when
2650 * record/replay is enabled.
2652 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2653 run_on_cpu(cpuas
->cpu
, do_nothing
, RUN_ON_CPU_NULL
);
2657 static void tcg_commit(MemoryListener
*listener
)
2659 CPUAddressSpace
*cpuas
;
2660 AddressSpaceDispatch
*d
;
2662 assert(tcg_enabled());
2663 /* since each CPU stores ram addresses in its TLB cache, we must
2664 reset the modified entries */
2665 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2666 cpu_reloading_memory_map();
2667 /* The CPU and TLB are protected by the iothread lock.
2668 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2669 * may have split the RCU critical section.
2671 d
= address_space_to_dispatch(cpuas
->as
);
2672 qatomic_rcu_set(&cpuas
->memory_dispatch
, d
);
2673 tlb_flush(cpuas
->cpu
);
2676 static void memory_map_init(void)
2678 system_memory
= g_malloc(sizeof(*system_memory
));
2680 memory_region_init(system_memory
, NULL
, "system", UINT64_MAX
);
2681 address_space_init(&address_space_memory
, system_memory
, "memory");
2683 system_io
= g_malloc(sizeof(*system_io
));
2684 memory_region_init_io(system_io
, NULL
, &unassigned_io_ops
, NULL
, "io",
2686 address_space_init(&address_space_io
, system_io
, "I/O");
2689 MemoryRegion
*get_system_memory(void)
2691 return system_memory
;
2694 MemoryRegion
*get_system_io(void)
2699 static void invalidate_and_set_dirty(MemoryRegion
*mr
, hwaddr addr
,
2702 uint8_t dirty_log_mask
= memory_region_get_dirty_log_mask(mr
);
2703 addr
+= memory_region_get_ram_addr(mr
);
2705 /* No early return if dirty_log_mask is or becomes 0, because
2706 * cpu_physical_memory_set_dirty_range will still call
2707 * xen_modified_memory.
2709 if (dirty_log_mask
) {
2711 cpu_physical_memory_range_includes_clean(addr
, length
, dirty_log_mask
);
2713 if (dirty_log_mask
& (1 << DIRTY_MEMORY_CODE
)) {
2714 assert(tcg_enabled());
2715 tb_invalidate_phys_range(addr
, addr
+ length
);
2716 dirty_log_mask
&= ~(1 << DIRTY_MEMORY_CODE
);
2718 cpu_physical_memory_set_dirty_range(addr
, length
, dirty_log_mask
);
2721 void memory_region_flush_rom_device(MemoryRegion
*mr
, hwaddr addr
, hwaddr size
)
2724 * In principle this function would work on other memory region types too,
2725 * but the ROM device use case is the only one where this operation is
2726 * necessary. Other memory regions should use the
2727 * address_space_read/write() APIs.
2729 assert(memory_region_is_romd(mr
));
2731 invalidate_and_set_dirty(mr
, addr
, size
);
2734 int memory_access_size(MemoryRegion
*mr
, unsigned l
, hwaddr addr
)
2736 unsigned access_size_max
= mr
->ops
->valid
.max_access_size
;
2738 /* Regions are assumed to support 1-4 byte accesses unless
2739 otherwise specified. */
2740 if (access_size_max
== 0) {
2741 access_size_max
= 4;
2744 /* Bound the maximum access by the alignment of the address. */
2745 if (!mr
->ops
->impl
.unaligned
) {
2746 unsigned align_size_max
= addr
& -addr
;
2747 if (align_size_max
!= 0 && align_size_max
< access_size_max
) {
2748 access_size_max
= align_size_max
;
2752 /* Don't attempt accesses larger than the maximum. */
2753 if (l
> access_size_max
) {
2754 l
= access_size_max
;
2761 bool prepare_mmio_access(MemoryRegion
*mr
)
2763 bool release_lock
= false;
2765 if (!qemu_mutex_iothread_locked()) {
2766 qemu_mutex_lock_iothread();
2767 release_lock
= true;
2769 if (mr
->flush_coalesced_mmio
) {
2770 qemu_flush_coalesced_mmio_buffer();
2773 return release_lock
;
2777 * flatview_access_allowed
2778 * @mr: #MemoryRegion to be accessed
2779 * @attrs: memory transaction attributes
2780 * @addr: address within that memory region
2781 * @len: the number of bytes to access
2783 * Check if a memory transaction is allowed.
2785 * Returns: true if transaction is allowed, false if denied.
2787 static bool flatview_access_allowed(MemoryRegion
*mr
, MemTxAttrs attrs
,
2788 hwaddr addr
, hwaddr len
)
2790 if (likely(!attrs
.memory
)) {
2793 if (memory_region_is_ram(mr
)) {
2796 qemu_log_mask(LOG_GUEST_ERROR
,
2797 "Invalid access to non-RAM device at "
2798 "addr 0x%" HWADDR_PRIX
", size %" HWADDR_PRIu
", "
2799 "region '%s'\n", addr
, len
, memory_region_name(mr
));
2803 /* Called within RCU critical section. */
2804 static MemTxResult
flatview_write_continue(FlatView
*fv
, hwaddr addr
,
2807 hwaddr len
, hwaddr addr1
,
2808 hwaddr l
, MemoryRegion
*mr
)
2812 MemTxResult result
= MEMTX_OK
;
2813 bool release_lock
= false;
2814 const uint8_t *buf
= ptr
;
2817 if (!flatview_access_allowed(mr
, attrs
, addr1
, l
)) {
2818 result
|= MEMTX_ACCESS_ERROR
;
2820 } else if (!memory_access_is_direct(mr
, true)) {
2821 release_lock
|= prepare_mmio_access(mr
);
2822 l
= memory_access_size(mr
, l
, addr1
);
2823 /* XXX: could force current_cpu to NULL to avoid
2825 val
= ldn_he_p(buf
, l
);
2826 result
|= memory_region_dispatch_write(mr
, addr1
, val
,
2827 size_memop(l
), attrs
);
2830 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2831 memcpy(ram_ptr
, buf
, l
);
2832 invalidate_and_set_dirty(mr
, addr1
, l
);
2836 qemu_mutex_unlock_iothread();
2837 release_lock
= false;
2849 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2855 /* Called from RCU critical section. */
2856 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2857 const void *buf
, hwaddr len
)
2864 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2865 if (!flatview_access_allowed(mr
, attrs
, addr
, len
)) {
2866 return MEMTX_ACCESS_ERROR
;
2868 return flatview_write_continue(fv
, addr
, attrs
, buf
, len
,
2872 /* Called within RCU critical section. */
2873 MemTxResult
flatview_read_continue(FlatView
*fv
, hwaddr addr
,
2874 MemTxAttrs attrs
, void *ptr
,
2875 hwaddr len
, hwaddr addr1
, hwaddr l
,
2880 MemTxResult result
= MEMTX_OK
;
2881 bool release_lock
= false;
2884 fuzz_dma_read_cb(addr
, len
, mr
);
2886 if (!flatview_access_allowed(mr
, attrs
, addr1
, l
)) {
2887 result
|= MEMTX_ACCESS_ERROR
;
2889 } else if (!memory_access_is_direct(mr
, false)) {
2891 release_lock
|= prepare_mmio_access(mr
);
2892 l
= memory_access_size(mr
, l
, addr1
);
2893 result
|= memory_region_dispatch_read(mr
, addr1
, &val
,
2894 size_memop(l
), attrs
);
2895 stn_he_p(buf
, l
, val
);
2898 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2899 memcpy(buf
, ram_ptr
, l
);
2903 qemu_mutex_unlock_iothread();
2904 release_lock
= false;
2916 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2922 /* Called from RCU critical section. */
2923 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2924 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2931 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2932 if (!flatview_access_allowed(mr
, attrs
, addr
, len
)) {
2933 return MEMTX_ACCESS_ERROR
;
2935 return flatview_read_continue(fv
, addr
, attrs
, buf
, len
,
2939 MemTxResult
address_space_read_full(AddressSpace
*as
, hwaddr addr
,
2940 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2942 MemTxResult result
= MEMTX_OK
;
2946 RCU_READ_LOCK_GUARD();
2947 fv
= address_space_to_flatview(as
);
2948 result
= flatview_read(fv
, addr
, attrs
, buf
, len
);
2954 MemTxResult
address_space_write(AddressSpace
*as
, hwaddr addr
,
2956 const void *buf
, hwaddr len
)
2958 MemTxResult result
= MEMTX_OK
;
2962 RCU_READ_LOCK_GUARD();
2963 fv
= address_space_to_flatview(as
);
2964 result
= flatview_write(fv
, addr
, attrs
, buf
, len
);
2970 MemTxResult
address_space_rw(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
,
2971 void *buf
, hwaddr len
, bool is_write
)
2974 return address_space_write(as
, addr
, attrs
, buf
, len
);
2976 return address_space_read_full(as
, addr
, attrs
, buf
, len
);
2980 MemTxResult
address_space_set(AddressSpace
*as
, hwaddr addr
,
2981 uint8_t c
, hwaddr len
, MemTxAttrs attrs
)
2983 #define FILLBUF_SIZE 512
2984 uint8_t fillbuf
[FILLBUF_SIZE
];
2986 MemTxResult error
= MEMTX_OK
;
2988 memset(fillbuf
, c
, FILLBUF_SIZE
);
2990 l
= len
< FILLBUF_SIZE
? len
: FILLBUF_SIZE
;
2991 error
|= address_space_write(as
, addr
, attrs
, fillbuf
, l
);
2999 void cpu_physical_memory_rw(hwaddr addr
, void *buf
,
3000 hwaddr len
, bool is_write
)
3002 address_space_rw(&address_space_memory
, addr
, MEMTXATTRS_UNSPECIFIED
,
3003 buf
, len
, is_write
);
3006 enum write_rom_type
{
3011 static inline MemTxResult
address_space_write_rom_internal(AddressSpace
*as
,
3016 enum write_rom_type type
)
3022 const uint8_t *buf
= ptr
;
3024 RCU_READ_LOCK_GUARD();
3027 mr
= address_space_translate(as
, addr
, &addr1
, &l
, true, attrs
);
3029 if (!(memory_region_is_ram(mr
) ||
3030 memory_region_is_romd(mr
))) {
3031 l
= memory_access_size(mr
, l
, addr1
);
3034 ram_ptr
= qemu_map_ram_ptr(mr
->ram_block
, addr1
);
3037 memcpy(ram_ptr
, buf
, l
);
3038 invalidate_and_set_dirty(mr
, addr1
, l
);
3041 flush_idcache_range((uintptr_t)ram_ptr
, (uintptr_t)ram_ptr
, l
);
3052 /* used for ROM loading : can write in RAM and ROM */
3053 MemTxResult
address_space_write_rom(AddressSpace
*as
, hwaddr addr
,
3055 const void *buf
, hwaddr len
)
3057 return address_space_write_rom_internal(as
, addr
, attrs
,
3058 buf
, len
, WRITE_DATA
);
3061 void cpu_flush_icache_range(hwaddr start
, hwaddr len
)
3064 * This function should do the same thing as an icache flush that was
3065 * triggered from within the guest. For TCG we are always cache coherent,
3066 * so there is no need to flush anything. For KVM / Xen we need to flush
3067 * the host's instruction cache at least.
3069 if (tcg_enabled()) {
3073 address_space_write_rom_internal(&address_space_memory
,
3074 start
, MEMTXATTRS_UNSPECIFIED
,
3075 NULL
, len
, FLUSH_CACHE
);
3086 static BounceBuffer bounce
;
3088 typedef struct MapClient
{
3090 QLIST_ENTRY(MapClient
) link
;
3093 QemuMutex map_client_list_lock
;
3094 static QLIST_HEAD(, MapClient
) map_client_list
3095 = QLIST_HEAD_INITIALIZER(map_client_list
);
3097 static void cpu_unregister_map_client_do(MapClient
*client
)
3099 QLIST_REMOVE(client
, link
);
3103 static void cpu_notify_map_clients_locked(void)
3107 while (!QLIST_EMPTY(&map_client_list
)) {
3108 client
= QLIST_FIRST(&map_client_list
);
3109 qemu_bh_schedule(client
->bh
);
3110 cpu_unregister_map_client_do(client
);
3114 void cpu_register_map_client(QEMUBH
*bh
)
3116 MapClient
*client
= g_malloc(sizeof(*client
));
3118 qemu_mutex_lock(&map_client_list_lock
);
3120 QLIST_INSERT_HEAD(&map_client_list
, client
, link
);
3121 if (!qatomic_read(&bounce
.in_use
)) {
3122 cpu_notify_map_clients_locked();
3124 qemu_mutex_unlock(&map_client_list_lock
);
3127 void cpu_exec_init_all(void)
3129 qemu_mutex_init(&ram_list
.mutex
);
3130 /* The data structures we set up here depend on knowing the page size,
3131 * so no more changes can be made after this point.
3132 * In an ideal world, nothing we did before we had finished the
3133 * machine setup would care about the target page size, and we could
3134 * do this much later, rather than requiring board models to state
3135 * up front what their requirements are.
3137 finalize_target_page_bits();
3140 qemu_mutex_init(&map_client_list_lock
);
3143 void cpu_unregister_map_client(QEMUBH
*bh
)
3147 qemu_mutex_lock(&map_client_list_lock
);
3148 QLIST_FOREACH(client
, &map_client_list
, link
) {
3149 if (client
->bh
== bh
) {
3150 cpu_unregister_map_client_do(client
);
3154 qemu_mutex_unlock(&map_client_list_lock
);
3157 static void cpu_notify_map_clients(void)
3159 qemu_mutex_lock(&map_client_list_lock
);
3160 cpu_notify_map_clients_locked();
3161 qemu_mutex_unlock(&map_client_list_lock
);
3164 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
3165 bool is_write
, MemTxAttrs attrs
)
3172 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3173 if (!memory_access_is_direct(mr
, is_write
)) {
3174 l
= memory_access_size(mr
, l
, addr
);
3175 if (!memory_region_access_valid(mr
, xlat
, l
, is_write
, attrs
)) {
3186 bool address_space_access_valid(AddressSpace
*as
, hwaddr addr
,
3187 hwaddr len
, bool is_write
,
3192 RCU_READ_LOCK_GUARD();
3193 fv
= address_space_to_flatview(as
);
3194 return flatview_access_valid(fv
, addr
, len
, is_write
, attrs
);
3198 flatview_extend_translation(FlatView
*fv
, hwaddr addr
,
3200 MemoryRegion
*mr
, hwaddr base
, hwaddr len
,
3201 bool is_write
, MemTxAttrs attrs
)
3205 MemoryRegion
*this_mr
;
3211 if (target_len
== 0) {
3216 this_mr
= flatview_translate(fv
, addr
, &xlat
,
3217 &len
, is_write
, attrs
);
3218 if (this_mr
!= mr
|| xlat
!= base
+ done
) {
3224 /* Map a physical memory region into a host virtual address.
3225 * May map a subset of the requested range, given by and returned in *plen.
3226 * May return NULL if resources needed to perform the mapping are exhausted.
3227 * Use only for reads OR writes - not for read-modify-write operations.
3228 * Use cpu_register_map_client() to know when retrying the map operation is
3229 * likely to succeed.
3231 void *address_space_map(AddressSpace
*as
,
3247 RCU_READ_LOCK_GUARD();
3248 fv
= address_space_to_flatview(as
);
3249 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3251 if (!memory_access_is_direct(mr
, is_write
)) {
3252 if (qatomic_xchg(&bounce
.in_use
, true)) {
3256 /* Avoid unbounded allocations */
3257 l
= MIN(l
, TARGET_PAGE_SIZE
);
3258 bounce
.buffer
= qemu_memalign(TARGET_PAGE_SIZE
, l
);
3262 memory_region_ref(mr
);
3265 flatview_read(fv
, addr
, MEMTXATTRS_UNSPECIFIED
,
3270 return bounce
.buffer
;
3274 memory_region_ref(mr
);
3275 *plen
= flatview_extend_translation(fv
, addr
, len
, mr
, xlat
,
3276 l
, is_write
, attrs
);
3277 fuzz_dma_read_cb(addr
, *plen
, mr
);
3278 return qemu_ram_ptr_length(mr
->ram_block
, xlat
, plen
, true);
3281 /* Unmaps a memory region previously mapped by address_space_map().
3282 * Will also mark the memory as dirty if is_write is true. access_len gives
3283 * the amount of memory that was actually read or written by the caller.
3285 void address_space_unmap(AddressSpace
*as
, void *buffer
, hwaddr len
,
3286 bool is_write
, hwaddr access_len
)
3288 if (buffer
!= bounce
.buffer
) {
3292 mr
= memory_region_from_host(buffer
, &addr1
);
3295 invalidate_and_set_dirty(mr
, addr1
, access_len
);
3297 if (xen_enabled()) {
3298 xen_invalidate_map_cache_entry(buffer
);
3300 memory_region_unref(mr
);
3304 address_space_write(as
, bounce
.addr
, MEMTXATTRS_UNSPECIFIED
,
3305 bounce
.buffer
, access_len
);
3307 qemu_vfree(bounce
.buffer
);
3308 bounce
.buffer
= NULL
;
3309 memory_region_unref(bounce
.mr
);
3310 qatomic_mb_set(&bounce
.in_use
, false);
3311 cpu_notify_map_clients();
3314 void *cpu_physical_memory_map(hwaddr addr
,
3318 return address_space_map(&address_space_memory
, addr
, plen
, is_write
,
3319 MEMTXATTRS_UNSPECIFIED
);
3322 void cpu_physical_memory_unmap(void *buffer
, hwaddr len
,
3323 bool is_write
, hwaddr access_len
)
3325 return address_space_unmap(&address_space_memory
, buffer
, len
, is_write
, access_len
);
3328 #define ARG1_DECL AddressSpace *as
3331 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3332 #define RCU_READ_LOCK(...) rcu_read_lock()
3333 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3334 #include "memory_ldst.c.inc"
3336 int64_t address_space_cache_init(MemoryRegionCache
*cache
,
3342 AddressSpaceDispatch
*d
;
3350 cache
->fv
= address_space_get_flatview(as
);
3351 d
= flatview_to_dispatch(cache
->fv
);
3352 cache
->mrs
= *address_space_translate_internal(d
, addr
, &cache
->xlat
, &l
, true);
3355 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3356 * Take that into account to compute how many bytes are there between
3357 * cache->xlat and the end of the section.
3359 diff
= int128_sub(cache
->mrs
.size
,
3360 int128_make64(cache
->xlat
- cache
->mrs
.offset_within_region
));
3361 l
= int128_get64(int128_min(diff
, int128_make64(l
)));
3364 memory_region_ref(mr
);
3365 if (memory_access_is_direct(mr
, is_write
)) {
3366 /* We don't care about the memory attributes here as we're only
3367 * doing this if we found actual RAM, which behaves the same
3368 * regardless of attributes; so UNSPECIFIED is fine.
3370 l
= flatview_extend_translation(cache
->fv
, addr
, len
, mr
,
3371 cache
->xlat
, l
, is_write
,
3372 MEMTXATTRS_UNSPECIFIED
);
3373 cache
->ptr
= qemu_ram_ptr_length(mr
->ram_block
, cache
->xlat
, &l
, true);
3379 cache
->is_write
= is_write
;
3383 void address_space_cache_invalidate(MemoryRegionCache
*cache
,
3387 assert(cache
->is_write
);
3388 if (likely(cache
->ptr
)) {
3389 invalidate_and_set_dirty(cache
->mrs
.mr
, addr
+ cache
->xlat
, access_len
);
3393 void address_space_cache_destroy(MemoryRegionCache
*cache
)
3395 if (!cache
->mrs
.mr
) {
3399 if (xen_enabled()) {
3400 xen_invalidate_map_cache_entry(cache
->ptr
);
3402 memory_region_unref(cache
->mrs
.mr
);
3403 flatview_unref(cache
->fv
);
3404 cache
->mrs
.mr
= NULL
;
3408 /* Called from RCU critical section. This function has the same
3409 * semantics as address_space_translate, but it only works on a
3410 * predefined range of a MemoryRegion that was mapped with
3411 * address_space_cache_init.
3413 static inline MemoryRegion
*address_space_translate_cached(
3414 MemoryRegionCache
*cache
, hwaddr addr
, hwaddr
*xlat
,
3415 hwaddr
*plen
, bool is_write
, MemTxAttrs attrs
)
3417 MemoryRegionSection section
;
3419 IOMMUMemoryRegion
*iommu_mr
;
3420 AddressSpace
*target_as
;
3422 assert(!cache
->ptr
);
3423 *xlat
= addr
+ cache
->xlat
;
3426 iommu_mr
= memory_region_get_iommu(mr
);
3432 section
= address_space_translate_iommu(iommu_mr
, xlat
, plen
,
3433 NULL
, is_write
, true,
3438 /* Called from RCU critical section. address_space_read_cached uses this
3439 * out of line function when the target is an MMIO or IOMMU region.
3442 address_space_read_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3443 void *buf
, hwaddr len
)
3449 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, false,
3450 MEMTXATTRS_UNSPECIFIED
);
3451 return flatview_read_continue(cache
->fv
,
3452 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3456 /* Called from RCU critical section. address_space_write_cached uses this
3457 * out of line function when the target is an MMIO or IOMMU region.
3460 address_space_write_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3461 const void *buf
, hwaddr len
)
3467 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, true,
3468 MEMTXATTRS_UNSPECIFIED
);
3469 return flatview_write_continue(cache
->fv
,
3470 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3474 #define ARG1_DECL MemoryRegionCache *cache
3476 #define SUFFIX _cached_slow
3477 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3478 #define RCU_READ_LOCK() ((void)0)
3479 #define RCU_READ_UNLOCK() ((void)0)
3480 #include "memory_ldst.c.inc"
3482 /* virtual memory access for debug (includes writing to ROM) */
3483 int cpu_memory_rw_debug(CPUState
*cpu
, vaddr addr
,
3484 void *ptr
, size_t len
, bool is_write
)
3490 cpu_synchronize_state(cpu
);
3496 page
= addr
& TARGET_PAGE_MASK
;
3497 phys_addr
= cpu_get_phys_page_attrs_debug(cpu
, page
, &attrs
);
3498 asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
3499 /* if no physical page mapped, return an error */
3500 if (phys_addr
== -1)
3502 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3505 phys_addr
+= (addr
& ~TARGET_PAGE_MASK
);
3507 res
= address_space_write_rom(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3510 res
= address_space_read(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3513 if (res
!= MEMTX_OK
) {
3524 * Allows code that needs to deal with migration bitmaps etc to still be built
3525 * target independent.
3527 size_t qemu_target_page_size(void)
3529 return TARGET_PAGE_SIZE
;
3532 int qemu_target_page_bits(void)
3534 return TARGET_PAGE_BITS
;
3537 int qemu_target_page_bits_min(void)
3539 return TARGET_PAGE_BITS_MIN
;
3542 bool cpu_physical_memory_is_io(hwaddr phys_addr
)
3547 RCU_READ_LOCK_GUARD();
3548 mr
= address_space_translate(&address_space_memory
,
3549 phys_addr
, &phys_addr
, &l
, false,
3550 MEMTXATTRS_UNSPECIFIED
);
3552 return !(memory_region_is_ram(mr
) || memory_region_is_romd(mr
));
3555 int qemu_ram_foreach_block(RAMBlockIterFunc func
, void *opaque
)
3560 RCU_READ_LOCK_GUARD();
3561 RAMBLOCK_FOREACH(block
) {
3562 ret
= func(block
, opaque
);
3571 * Unmap pages of memory from start to start+length such that
3572 * they a) read as 0, b) Trigger whatever fault mechanism
3573 * the OS provides for postcopy.
3574 * The pages must be unmapped by the end of the function.
3575 * Returns: 0 on success, none-0 on failure
3578 int ram_block_discard_range(RAMBlock
*rb
, uint64_t start
, size_t length
)
3582 uint8_t *host_startaddr
= rb
->host
+ start
;
3584 if (!QEMU_PTR_IS_ALIGNED(host_startaddr
, rb
->page_size
)) {
3585 error_report("ram_block_discard_range: Unaligned start address: %p",
3590 if ((start
+ length
) <= rb
->max_length
) {
3591 bool need_madvise
, need_fallocate
;
3592 if (!QEMU_IS_ALIGNED(length
, rb
->page_size
)) {
3593 error_report("ram_block_discard_range: Unaligned length: %zx",
3598 errno
= ENOTSUP
; /* If we are missing MADVISE etc */
3600 /* The logic here is messy;
3601 * madvise DONTNEED fails for hugepages
3602 * fallocate works on hugepages and shmem
3603 * shared anonymous memory requires madvise REMOVE
3605 need_madvise
= (rb
->page_size
== qemu_host_page_size
);
3606 need_fallocate
= rb
->fd
!= -1;
3607 if (need_fallocate
) {
3608 /* For a file, this causes the area of the file to be zero'd
3609 * if read, and for hugetlbfs also causes it to be unmapped
3610 * so a userfault will trigger.
3612 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3613 ret
= fallocate(rb
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3617 error_report("ram_block_discard_range: Failed to fallocate "
3618 "%s:%" PRIx64
" +%zx (%d)",
3619 rb
->idstr
, start
, length
, ret
);
3624 error_report("ram_block_discard_range: fallocate not available/file"
3625 "%s:%" PRIx64
" +%zx (%d)",
3626 rb
->idstr
, start
, length
, ret
);
3631 /* For normal RAM this causes it to be unmapped,
3632 * for shared memory it causes the local mapping to disappear
3633 * and to fall back on the file contents (which we just
3634 * fallocate'd away).
3636 #if defined(CONFIG_MADVISE)
3637 if (qemu_ram_is_shared(rb
) && rb
->fd
< 0) {
3638 ret
= madvise(host_startaddr
, length
, QEMU_MADV_REMOVE
);
3640 ret
= madvise(host_startaddr
, length
, QEMU_MADV_DONTNEED
);
3644 error_report("ram_block_discard_range: Failed to discard range "
3645 "%s:%" PRIx64
" +%zx (%d)",
3646 rb
->idstr
, start
, length
, ret
);
3651 error_report("ram_block_discard_range: MADVISE not available"
3652 "%s:%" PRIx64
" +%zx (%d)",
3653 rb
->idstr
, start
, length
, ret
);
3657 trace_ram_block_discard_range(rb
->idstr
, host_startaddr
, length
,
3658 need_madvise
, need_fallocate
, ret
);
3660 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3661 "/%zx/" RAM_ADDR_FMT
")",
3662 rb
->idstr
, start
, length
, rb
->max_length
);
3669 bool ramblock_is_pmem(RAMBlock
*rb
)
3671 return rb
->flags
& RAM_PMEM
;
3674 static void mtree_print_phys_entries(int start
, int end
, int skip
, int ptr
)
3676 if (start
== end
- 1) {
3677 qemu_printf("\t%3d ", start
);
3679 qemu_printf("\t%3d..%-3d ", start
, end
- 1);
3681 qemu_printf(" skip=%d ", skip
);
3682 if (ptr
== PHYS_MAP_NODE_NIL
) {
3683 qemu_printf(" ptr=NIL");
3685 qemu_printf(" ptr=#%d", ptr
);
3687 qemu_printf(" ptr=[%d]", ptr
);
3692 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3693 int128_sub((size), int128_one())) : 0)
3695 void mtree_print_dispatch(AddressSpaceDispatch
*d
, MemoryRegion
*root
)
3699 qemu_printf(" Dispatch\n");
3700 qemu_printf(" Physical sections\n");
3702 for (i
= 0; i
< d
->map
.sections_nb
; ++i
) {
3703 MemoryRegionSection
*s
= d
->map
.sections
+ i
;
3704 const char *names
[] = { " [unassigned]", " [not dirty]",
3705 " [ROM]", " [watch]" };
3707 qemu_printf(" #%d @" HWADDR_FMT_plx
".." HWADDR_FMT_plx
3710 s
->offset_within_address_space
,
3711 s
->offset_within_address_space
+ MR_SIZE(s
->size
),
3712 s
->mr
->name
? s
->mr
->name
: "(noname)",
3713 i
< ARRAY_SIZE(names
) ? names
[i
] : "",
3714 s
->mr
== root
? " [ROOT]" : "",
3715 s
== d
->mru_section
? " [MRU]" : "",
3716 s
->mr
->is_iommu
? " [iommu]" : "");
3719 qemu_printf(" alias=%s", s
->mr
->alias
->name
?
3720 s
->mr
->alias
->name
: "noname");
3725 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3726 P_L2_BITS
, P_L2_LEVELS
, d
->phys_map
.ptr
, d
->phys_map
.skip
);
3727 for (i
= 0; i
< d
->map
.nodes_nb
; ++i
) {
3730 Node
*n
= d
->map
.nodes
+ i
;
3732 qemu_printf(" [%d]\n", i
);
3734 for (j
= 0, jprev
= 0, prev
= *n
[0]; j
< ARRAY_SIZE(*n
); ++j
) {
3735 PhysPageEntry
*pe
= *n
+ j
;
3737 if (pe
->ptr
== prev
.ptr
&& pe
->skip
== prev
.skip
) {
3741 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3747 if (jprev
!= ARRAY_SIZE(*n
)) {
3748 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3753 /* Require any discards to work. */
3754 static unsigned int ram_block_discard_required_cnt
;
3755 /* Require only coordinated discards to work. */
3756 static unsigned int ram_block_coordinated_discard_required_cnt
;
3757 /* Disable any discards. */
3758 static unsigned int ram_block_discard_disabled_cnt
;
3759 /* Disable only uncoordinated discards. */
3760 static unsigned int ram_block_uncoordinated_discard_disabled_cnt
;
3761 static QemuMutex ram_block_discard_disable_mutex
;
3763 static void ram_block_discard_disable_mutex_lock(void)
3765 static gsize initialized
;
3767 if (g_once_init_enter(&initialized
)) {
3768 qemu_mutex_init(&ram_block_discard_disable_mutex
);
3769 g_once_init_leave(&initialized
, 1);
3771 qemu_mutex_lock(&ram_block_discard_disable_mutex
);
3774 static void ram_block_discard_disable_mutex_unlock(void)
3776 qemu_mutex_unlock(&ram_block_discard_disable_mutex
);
3779 int ram_block_discard_disable(bool state
)
3783 ram_block_discard_disable_mutex_lock();
3785 ram_block_discard_disabled_cnt
--;
3786 } else if (ram_block_discard_required_cnt
||
3787 ram_block_coordinated_discard_required_cnt
) {
3790 ram_block_discard_disabled_cnt
++;
3792 ram_block_discard_disable_mutex_unlock();
3796 int ram_block_uncoordinated_discard_disable(bool state
)
3800 ram_block_discard_disable_mutex_lock();
3802 ram_block_uncoordinated_discard_disabled_cnt
--;
3803 } else if (ram_block_discard_required_cnt
) {
3806 ram_block_uncoordinated_discard_disabled_cnt
++;
3808 ram_block_discard_disable_mutex_unlock();
3812 int ram_block_discard_require(bool state
)
3816 ram_block_discard_disable_mutex_lock();
3818 ram_block_discard_required_cnt
--;
3819 } else if (ram_block_discard_disabled_cnt
||
3820 ram_block_uncoordinated_discard_disabled_cnt
) {
3823 ram_block_discard_required_cnt
++;
3825 ram_block_discard_disable_mutex_unlock();
3829 int ram_block_coordinated_discard_require(bool state
)
3833 ram_block_discard_disable_mutex_lock();
3835 ram_block_coordinated_discard_required_cnt
--;
3836 } else if (ram_block_discard_disabled_cnt
) {
3839 ram_block_coordinated_discard_required_cnt
++;
3841 ram_block_discard_disable_mutex_unlock();
3845 bool ram_block_discard_is_disabled(void)
3847 return qatomic_read(&ram_block_discard_disabled_cnt
) ||
3848 qatomic_read(&ram_block_uncoordinated_discard_disabled_cnt
);
3851 bool ram_block_discard_is_required(void)
3853 return qatomic_read(&ram_block_discard_required_cnt
) ||
3854 qatomic_read(&ram_block_coordinated_discard_required_cnt
);