2 * RAM allocation and memory access
4 * Copyright (c) 2003 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 #include "qemu/osdep.h"
21 #include "qemu-common.h"
22 #include "qapi/error.h"
24 #include "qemu/cutils.h"
25 #include "qemu/cacheflush.h"
29 #include "hw/core/tcg-cpu-ops.h"
30 #endif /* CONFIG_TCG */
32 #include "exec/exec-all.h"
33 #include "exec/target_page.h"
34 #include "hw/qdev-core.h"
35 #include "hw/qdev-properties.h"
36 #include "hw/boards.h"
37 #include "hw/xen/xen.h"
38 #include "sysemu/kvm.h"
39 #include "sysemu/sysemu.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"
46 #include "exec/memory.h"
47 #include "exec/ioport.h"
48 #include "sysemu/dma.h"
49 #include "sysemu/hostmem.h"
50 #include "sysemu/hw_accel.h"
51 #include "exec/address-spaces.h"
52 #include "sysemu/xen-mapcache.h"
53 #include "trace/trace-root.h"
55 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
56 #include <linux/falloc.h>
59 #include "qemu/rcu_queue.h"
60 #include "qemu/main-loop.h"
61 #include "exec/translate-all.h"
62 #include "sysemu/replay.h"
64 #include "exec/memory-internal.h"
65 #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 addr
,
674 hwaddr
*xlat
, hwaddr
*plen
,
675 MemTxAttrs attrs
, int *prot
)
677 MemoryRegionSection
*section
;
678 IOMMUMemoryRegion
*iommu_mr
;
679 IOMMUMemoryRegionClass
*imrc
;
682 AddressSpaceDispatch
*d
=
683 qatomic_rcu_read(&cpu
->cpu_ases
[asidx
].memory_dispatch
);
686 section
= address_space_translate_internal(d
, addr
, &addr
, plen
, false);
688 iommu_mr
= memory_region_get_iommu(section
->mr
);
693 imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
695 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
696 tcg_register_iommu_notifier(cpu
, iommu_mr
, iommu_idx
);
697 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
698 * doesn't short-cut its translation table walk.
700 iotlb
= imrc
->translate(iommu_mr
, addr
, IOMMU_NONE
, iommu_idx
);
701 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
702 | (addr
& iotlb
.addr_mask
));
703 /* Update the caller's prot bits to remove permissions the IOMMU
704 * is giving us a failure response for. If we get down to no
705 * permissions left at all we can give up now.
707 if (!(iotlb
.perm
& IOMMU_RO
)) {
708 *prot
&= ~(PAGE_READ
| PAGE_EXEC
);
710 if (!(iotlb
.perm
& IOMMU_WO
)) {
711 *prot
&= ~PAGE_WRITE
;
718 d
= flatview_to_dispatch(address_space_to_flatview(iotlb
.target_as
));
721 assert(!memory_region_is_iommu(section
->mr
));
726 return &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
];
729 void cpu_address_space_init(CPUState
*cpu
, int asidx
,
730 const char *prefix
, MemoryRegion
*mr
)
732 CPUAddressSpace
*newas
;
733 AddressSpace
*as
= g_new0(AddressSpace
, 1);
737 as_name
= g_strdup_printf("%s-%d", prefix
, cpu
->cpu_index
);
738 address_space_init(as
, mr
, as_name
);
741 /* Target code should have set num_ases before calling us */
742 assert(asidx
< cpu
->num_ases
);
745 /* address space 0 gets the convenience alias */
749 /* KVM cannot currently support multiple address spaces. */
750 assert(asidx
== 0 || !kvm_enabled());
752 if (!cpu
->cpu_ases
) {
753 cpu
->cpu_ases
= g_new0(CPUAddressSpace
, cpu
->num_ases
);
756 newas
= &cpu
->cpu_ases
[asidx
];
760 newas
->tcg_as_listener
.log_global_after_sync
= tcg_log_global_after_sync
;
761 newas
->tcg_as_listener
.commit
= tcg_commit
;
762 memory_listener_register(&newas
->tcg_as_listener
, as
);
766 AddressSpace
*cpu_get_address_space(CPUState
*cpu
, int asidx
)
768 /* Return the AddressSpace corresponding to the specified index */
769 return cpu
->cpu_ases
[asidx
].as
;
772 /* Add a watchpoint. */
773 int cpu_watchpoint_insert(CPUState
*cpu
, vaddr addr
, vaddr len
,
774 int flags
, CPUWatchpoint
**watchpoint
)
779 /* forbid ranges which are empty or run off the end of the address space */
780 if (len
== 0 || (addr
+ len
- 1) < addr
) {
781 error_report("tried to set invalid watchpoint at %"
782 VADDR_PRIx
", len=%" VADDR_PRIu
, addr
, len
);
785 wp
= g_malloc(sizeof(*wp
));
791 /* keep all GDB-injected watchpoints in front */
792 if (flags
& BP_GDB
) {
793 QTAILQ_INSERT_HEAD(&cpu
->watchpoints
, wp
, entry
);
795 QTAILQ_INSERT_TAIL(&cpu
->watchpoints
, wp
, entry
);
798 in_page
= -(addr
| TARGET_PAGE_MASK
);
799 if (len
<= in_page
) {
800 tlb_flush_page(cpu
, addr
);
810 /* Remove a specific watchpoint. */
811 int cpu_watchpoint_remove(CPUState
*cpu
, vaddr addr
, vaddr len
,
816 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
817 if (addr
== wp
->vaddr
&& len
== wp
->len
818 && flags
== (wp
->flags
& ~BP_WATCHPOINT_HIT
)) {
819 cpu_watchpoint_remove_by_ref(cpu
, wp
);
826 /* Remove a specific watchpoint by reference. */
827 void cpu_watchpoint_remove_by_ref(CPUState
*cpu
, CPUWatchpoint
*watchpoint
)
829 QTAILQ_REMOVE(&cpu
->watchpoints
, watchpoint
, entry
);
831 tlb_flush_page(cpu
, watchpoint
->vaddr
);
836 /* Remove all matching watchpoints. */
837 void cpu_watchpoint_remove_all(CPUState
*cpu
, int mask
)
839 CPUWatchpoint
*wp
, *next
;
841 QTAILQ_FOREACH_SAFE(wp
, &cpu
->watchpoints
, entry
, next
) {
842 if (wp
->flags
& mask
) {
843 cpu_watchpoint_remove_by_ref(cpu
, wp
);
849 /* Return true if this watchpoint address matches the specified
850 * access (ie the address range covered by the watchpoint overlaps
851 * partially or completely with the address range covered by the
854 static inline bool watchpoint_address_matches(CPUWatchpoint
*wp
,
855 vaddr addr
, vaddr len
)
857 /* We know the lengths are non-zero, but a little caution is
858 * required to avoid errors in the case where the range ends
859 * exactly at the top of the address space and so addr + len
860 * wraps round to zero.
862 vaddr wpend
= wp
->vaddr
+ wp
->len
- 1;
863 vaddr addrend
= addr
+ len
- 1;
865 return !(addr
> wpend
|| wp
->vaddr
> addrend
);
868 /* Return flags for watchpoints that match addr + prot. */
869 int cpu_watchpoint_address_matches(CPUState
*cpu
, vaddr addr
, vaddr len
)
874 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
875 if (watchpoint_address_matches(wp
, addr
, len
)) {
882 /* Generate a debug exception if a watchpoint has been hit. */
883 void cpu_check_watchpoint(CPUState
*cpu
, vaddr addr
, vaddr len
,
884 MemTxAttrs attrs
, int flags
, uintptr_t ra
)
886 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
889 assert(tcg_enabled());
890 if (cpu
->watchpoint_hit
) {
892 * We re-entered the check after replacing the TB.
893 * Now raise the debug interrupt so that it will
894 * trigger after the current instruction.
896 qemu_mutex_lock_iothread();
897 cpu_interrupt(cpu
, CPU_INTERRUPT_DEBUG
);
898 qemu_mutex_unlock_iothread();
902 if (cc
->tcg_ops
->adjust_watchpoint_address
) {
903 /* this is currently used only by ARM BE32 */
904 addr
= cc
->tcg_ops
->adjust_watchpoint_address(cpu
, addr
, len
);
906 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
907 if (watchpoint_address_matches(wp
, addr
, len
)
908 && (wp
->flags
& flags
)) {
909 if (replay_running_debug()) {
911 * Don't process the watchpoints when we are
912 * in a reverse debugging operation.
917 if (flags
== BP_MEM_READ
) {
918 wp
->flags
|= BP_WATCHPOINT_HIT_READ
;
920 wp
->flags
|= BP_WATCHPOINT_HIT_WRITE
;
922 wp
->hitaddr
= MAX(addr
, wp
->vaddr
);
923 wp
->hitattrs
= attrs
;
924 if (!cpu
->watchpoint_hit
) {
925 if (wp
->flags
& BP_CPU
&& cc
->tcg_ops
->debug_check_watchpoint
&&
926 !cc
->tcg_ops
->debug_check_watchpoint(cpu
, wp
)) {
927 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
930 cpu
->watchpoint_hit
= wp
;
933 tb_check_watchpoint(cpu
, ra
);
934 if (wp
->flags
& BP_STOP_BEFORE_ACCESS
) {
935 cpu
->exception_index
= EXCP_DEBUG
;
937 cpu_loop_exit_restore(cpu
, ra
);
939 /* Force execution of one insn next time. */
940 cpu
->cflags_next_tb
= 1 | curr_cflags();
943 cpu_restore_state(cpu
, ra
, true);
945 cpu_loop_exit_noexc(cpu
);
949 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
954 #endif /* CONFIG_TCG */
956 /* Called from RCU critical section */
957 static RAMBlock
*qemu_get_ram_block(ram_addr_t addr
)
961 block
= qatomic_rcu_read(&ram_list
.mru_block
);
962 if (block
&& addr
- block
->offset
< block
->max_length
) {
965 RAMBLOCK_FOREACH(block
) {
966 if (addr
- block
->offset
< block
->max_length
) {
971 fprintf(stderr
, "Bad ram offset %" PRIx64
"\n", (uint64_t)addr
);
975 /* It is safe to write mru_block outside the iothread lock. This
980 * xxx removed from list
984 * call_rcu(reclaim_ramblock, xxx);
987 * qatomic_rcu_set is not needed here. The block was already published
988 * when it was placed into the list. Here we're just making an extra
989 * copy of the pointer.
991 ram_list
.mru_block
= block
;
995 static void tlb_reset_dirty_range_all(ram_addr_t start
, ram_addr_t length
)
1002 assert(tcg_enabled());
1003 end
= TARGET_PAGE_ALIGN(start
+ length
);
1004 start
&= TARGET_PAGE_MASK
;
1006 RCU_READ_LOCK_GUARD();
1007 block
= qemu_get_ram_block(start
);
1008 assert(block
== qemu_get_ram_block(end
- 1));
1009 start1
= (uintptr_t)ramblock_ptr(block
, start
- block
->offset
);
1011 tlb_reset_dirty(cpu
, start1
, length
);
1015 /* Note: start and end must be within the same ram block. */
1016 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start
,
1020 DirtyMemoryBlocks
*blocks
;
1021 unsigned long end
, page
, start_page
;
1024 uint64_t mr_offset
, mr_size
;
1030 end
= TARGET_PAGE_ALIGN(start
+ length
) >> TARGET_PAGE_BITS
;
1031 start_page
= start
>> TARGET_PAGE_BITS
;
1034 WITH_RCU_READ_LOCK_GUARD() {
1035 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1036 ramblock
= qemu_get_ram_block(start
);
1037 /* Range sanity check on the ramblock */
1038 assert(start
>= ramblock
->offset
&&
1039 start
+ length
<= ramblock
->offset
+ ramblock
->used_length
);
1041 while (page
< end
) {
1042 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1043 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1044 unsigned long num
= MIN(end
- page
,
1045 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1047 dirty
|= bitmap_test_and_clear_atomic(blocks
->blocks
[idx
],
1052 mr_offset
= (ram_addr_t
)(start_page
<< TARGET_PAGE_BITS
) - ramblock
->offset
;
1053 mr_size
= (end
- start_page
) << TARGET_PAGE_BITS
;
1054 memory_region_clear_dirty_bitmap(ramblock
->mr
, mr_offset
, mr_size
);
1057 if (dirty
&& tcg_enabled()) {
1058 tlb_reset_dirty_range_all(start
, length
);
1064 DirtyBitmapSnapshot
*cpu_physical_memory_snapshot_and_clear_dirty
1065 (MemoryRegion
*mr
, hwaddr offset
, hwaddr length
, unsigned client
)
1067 DirtyMemoryBlocks
*blocks
;
1068 ram_addr_t start
= memory_region_get_ram_addr(mr
) + offset
;
1069 unsigned long align
= 1UL << (TARGET_PAGE_BITS
+ BITS_PER_LEVEL
);
1070 ram_addr_t first
= QEMU_ALIGN_DOWN(start
, align
);
1071 ram_addr_t last
= QEMU_ALIGN_UP(start
+ length
, align
);
1072 DirtyBitmapSnapshot
*snap
;
1073 unsigned long page
, end
, dest
;
1075 snap
= g_malloc0(sizeof(*snap
) +
1076 ((last
- first
) >> (TARGET_PAGE_BITS
+ 3)));
1077 snap
->start
= first
;
1080 page
= first
>> TARGET_PAGE_BITS
;
1081 end
= last
>> TARGET_PAGE_BITS
;
1084 WITH_RCU_READ_LOCK_GUARD() {
1085 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1087 while (page
< end
) {
1088 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1089 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1090 unsigned long num
= MIN(end
- page
,
1091 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1093 assert(QEMU_IS_ALIGNED(offset
, (1 << BITS_PER_LEVEL
)));
1094 assert(QEMU_IS_ALIGNED(num
, (1 << BITS_PER_LEVEL
)));
1095 offset
>>= BITS_PER_LEVEL
;
1097 bitmap_copy_and_clear_atomic(snap
->dirty
+ dest
,
1098 blocks
->blocks
[idx
] + offset
,
1101 dest
+= num
>> BITS_PER_LEVEL
;
1105 if (tcg_enabled()) {
1106 tlb_reset_dirty_range_all(start
, length
);
1109 memory_region_clear_dirty_bitmap(mr
, offset
, length
);
1114 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot
*snap
,
1118 unsigned long page
, end
;
1120 assert(start
>= snap
->start
);
1121 assert(start
+ length
<= snap
->end
);
1123 end
= TARGET_PAGE_ALIGN(start
+ length
- snap
->start
) >> TARGET_PAGE_BITS
;
1124 page
= (start
- snap
->start
) >> TARGET_PAGE_BITS
;
1126 while (page
< end
) {
1127 if (test_bit(page
, snap
->dirty
)) {
1135 /* Called from RCU critical section */
1136 hwaddr
memory_region_section_get_iotlb(CPUState
*cpu
,
1137 MemoryRegionSection
*section
)
1139 AddressSpaceDispatch
*d
= flatview_to_dispatch(section
->fv
);
1140 return section
- d
->map
.sections
;
1143 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
1145 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
);
1147 static void *(*phys_mem_alloc
)(size_t size
, uint64_t *align
, bool shared
) =
1148 qemu_anon_ram_alloc
;
1151 * Set a custom physical guest memory alloator.
1152 * Accelerators with unusual needs may need this. Hopefully, we can
1153 * get rid of it eventually.
1155 void phys_mem_set_alloc(void *(*alloc
)(size_t, uint64_t *align
, bool shared
))
1157 phys_mem_alloc
= alloc
;
1160 static uint16_t phys_section_add(PhysPageMap
*map
,
1161 MemoryRegionSection
*section
)
1163 /* The physical section number is ORed with a page-aligned
1164 * pointer to produce the iotlb entries. Thus it should
1165 * never overflow into the page-aligned value.
1167 assert(map
->sections_nb
< TARGET_PAGE_SIZE
);
1169 if (map
->sections_nb
== map
->sections_nb_alloc
) {
1170 map
->sections_nb_alloc
= MAX(map
->sections_nb_alloc
* 2, 16);
1171 map
->sections
= g_renew(MemoryRegionSection
, map
->sections
,
1172 map
->sections_nb_alloc
);
1174 map
->sections
[map
->sections_nb
] = *section
;
1175 memory_region_ref(section
->mr
);
1176 return map
->sections_nb
++;
1179 static void phys_section_destroy(MemoryRegion
*mr
)
1181 bool have_sub_page
= mr
->subpage
;
1183 memory_region_unref(mr
);
1185 if (have_sub_page
) {
1186 subpage_t
*subpage
= container_of(mr
, subpage_t
, iomem
);
1187 object_unref(OBJECT(&subpage
->iomem
));
1192 static void phys_sections_free(PhysPageMap
*map
)
1194 while (map
->sections_nb
> 0) {
1195 MemoryRegionSection
*section
= &map
->sections
[--map
->sections_nb
];
1196 phys_section_destroy(section
->mr
);
1198 g_free(map
->sections
);
1202 static void register_subpage(FlatView
*fv
, MemoryRegionSection
*section
)
1204 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1206 hwaddr base
= section
->offset_within_address_space
1208 MemoryRegionSection
*existing
= phys_page_find(d
, base
);
1209 MemoryRegionSection subsection
= {
1210 .offset_within_address_space
= base
,
1211 .size
= int128_make64(TARGET_PAGE_SIZE
),
1215 assert(existing
->mr
->subpage
|| existing
->mr
== &io_mem_unassigned
);
1217 if (!(existing
->mr
->subpage
)) {
1218 subpage
= subpage_init(fv
, base
);
1220 subsection
.mr
= &subpage
->iomem
;
1221 phys_page_set(d
, base
>> TARGET_PAGE_BITS
, 1,
1222 phys_section_add(&d
->map
, &subsection
));
1224 subpage
= container_of(existing
->mr
, subpage_t
, iomem
);
1226 start
= section
->offset_within_address_space
& ~TARGET_PAGE_MASK
;
1227 end
= start
+ int128_get64(section
->size
) - 1;
1228 subpage_register(subpage
, start
, end
,
1229 phys_section_add(&d
->map
, section
));
1233 static void register_multipage(FlatView
*fv
,
1234 MemoryRegionSection
*section
)
1236 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1237 hwaddr start_addr
= section
->offset_within_address_space
;
1238 uint16_t section_index
= phys_section_add(&d
->map
, section
);
1239 uint64_t num_pages
= int128_get64(int128_rshift(section
->size
,
1243 phys_page_set(d
, start_addr
>> TARGET_PAGE_BITS
, num_pages
, section_index
);
1247 * The range in *section* may look like this:
1251 * where s stands for subpage and P for page.
1253 void flatview_add_to_dispatch(FlatView
*fv
, MemoryRegionSection
*section
)
1255 MemoryRegionSection remain
= *section
;
1256 Int128 page_size
= int128_make64(TARGET_PAGE_SIZE
);
1258 /* register first subpage */
1259 if (remain
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1260 uint64_t left
= TARGET_PAGE_ALIGN(remain
.offset_within_address_space
)
1261 - remain
.offset_within_address_space
;
1263 MemoryRegionSection now
= remain
;
1264 now
.size
= int128_min(int128_make64(left
), now
.size
);
1265 register_subpage(fv
, &now
);
1266 if (int128_eq(remain
.size
, now
.size
)) {
1269 remain
.size
= int128_sub(remain
.size
, now
.size
);
1270 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1271 remain
.offset_within_region
+= int128_get64(now
.size
);
1274 /* register whole pages */
1275 if (int128_ge(remain
.size
, page_size
)) {
1276 MemoryRegionSection now
= remain
;
1277 now
.size
= int128_and(now
.size
, int128_neg(page_size
));
1278 register_multipage(fv
, &now
);
1279 if (int128_eq(remain
.size
, now
.size
)) {
1282 remain
.size
= int128_sub(remain
.size
, now
.size
);
1283 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1284 remain
.offset_within_region
+= int128_get64(now
.size
);
1287 /* register last subpage */
1288 register_subpage(fv
, &remain
);
1291 void qemu_flush_coalesced_mmio_buffer(void)
1294 kvm_flush_coalesced_mmio_buffer();
1297 void qemu_mutex_lock_ramlist(void)
1299 qemu_mutex_lock(&ram_list
.mutex
);
1302 void qemu_mutex_unlock_ramlist(void)
1304 qemu_mutex_unlock(&ram_list
.mutex
);
1307 void ram_block_dump(Monitor
*mon
)
1312 RCU_READ_LOCK_GUARD();
1313 monitor_printf(mon
, "%24s %8s %18s %18s %18s\n",
1314 "Block Name", "PSize", "Offset", "Used", "Total");
1315 RAMBLOCK_FOREACH(block
) {
1316 psize
= size_to_str(block
->page_size
);
1317 monitor_printf(mon
, "%24s %8s 0x%016" PRIx64
" 0x%016" PRIx64
1318 " 0x%016" PRIx64
"\n", block
->idstr
, psize
,
1319 (uint64_t)block
->offset
,
1320 (uint64_t)block
->used_length
,
1321 (uint64_t)block
->max_length
);
1328 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1329 * may or may not name the same files / on the same filesystem now as
1330 * when we actually open and map them. Iterate over the file
1331 * descriptors instead, and use qemu_fd_getpagesize().
1333 static int find_min_backend_pagesize(Object
*obj
, void *opaque
)
1335 long *hpsize_min
= opaque
;
1337 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1338 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1339 long hpsize
= host_memory_backend_pagesize(backend
);
1341 if (host_memory_backend_is_mapped(backend
) && (hpsize
< *hpsize_min
)) {
1342 *hpsize_min
= hpsize
;
1349 static int find_max_backend_pagesize(Object
*obj
, void *opaque
)
1351 long *hpsize_max
= opaque
;
1353 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1354 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1355 long hpsize
= host_memory_backend_pagesize(backend
);
1357 if (host_memory_backend_is_mapped(backend
) && (hpsize
> *hpsize_max
)) {
1358 *hpsize_max
= hpsize
;
1366 * TODO: We assume right now that all mapped host memory backends are
1367 * used as RAM, however some might be used for different purposes.
1369 long qemu_minrampagesize(void)
1371 long hpsize
= LONG_MAX
;
1372 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1374 object_child_foreach(memdev_root
, find_min_backend_pagesize
, &hpsize
);
1378 long qemu_maxrampagesize(void)
1381 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1383 object_child_foreach(memdev_root
, find_max_backend_pagesize
, &pagesize
);
1387 long qemu_minrampagesize(void)
1389 return qemu_real_host_page_size
;
1391 long qemu_maxrampagesize(void)
1393 return qemu_real_host_page_size
;
1398 static int64_t get_file_size(int fd
)
1401 #if defined(__linux__)
1404 if (fstat(fd
, &st
) < 0) {
1408 /* Special handling for devdax character devices */
1409 if (S_ISCHR(st
.st_mode
)) {
1410 g_autofree
char *subsystem_path
= NULL
;
1411 g_autofree
char *subsystem
= NULL
;
1413 subsystem_path
= g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1414 major(st
.st_rdev
), minor(st
.st_rdev
));
1415 subsystem
= g_file_read_link(subsystem_path
, NULL
);
1417 if (subsystem
&& g_str_has_suffix(subsystem
, "/dax")) {
1418 g_autofree
char *size_path
= NULL
;
1419 g_autofree
char *size_str
= NULL
;
1421 size_path
= g_strdup_printf("/sys/dev/char/%d:%d/size",
1422 major(st
.st_rdev
), minor(st
.st_rdev
));
1424 if (g_file_get_contents(size_path
, &size_str
, NULL
, NULL
)) {
1425 return g_ascii_strtoll(size_str
, NULL
, 0);
1429 #endif /* defined(__linux__) */
1431 /* st.st_size may be zero for special files yet lseek(2) works */
1432 size
= lseek(fd
, 0, SEEK_END
);
1439 static int64_t get_file_align(int fd
)
1442 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1445 if (fstat(fd
, &st
) < 0) {
1449 /* Special handling for devdax character devices */
1450 if (S_ISCHR(st
.st_mode
)) {
1451 g_autofree
char *path
= NULL
;
1452 g_autofree
char *rpath
= NULL
;
1453 struct daxctl_ctx
*ctx
;
1454 struct daxctl_region
*region
;
1457 path
= g_strdup_printf("/sys/dev/char/%d:%d",
1458 major(st
.st_rdev
), minor(st
.st_rdev
));
1459 rpath
= realpath(path
, NULL
);
1461 rc
= daxctl_new(&ctx
);
1466 daxctl_region_foreach(ctx
, region
) {
1467 if (strstr(rpath
, daxctl_region_get_path(region
))) {
1468 align
= daxctl_region_get_align(region
);
1474 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1479 static int file_ram_open(const char *path
,
1480 const char *region_name
,
1486 char *sanitized_name
;
1492 fd
= open(path
, readonly
? O_RDONLY
: O_RDWR
);
1494 /* @path names an existing file, use it */
1497 if (errno
== ENOENT
) {
1498 /* @path names a file that doesn't exist, create it */
1499 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0644);
1504 } else if (errno
== EISDIR
) {
1505 /* @path names a directory, create a file there */
1506 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1507 sanitized_name
= g_strdup(region_name
);
1508 for (c
= sanitized_name
; *c
!= '\0'; c
++) {
1514 filename
= g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path
,
1516 g_free(sanitized_name
);
1518 fd
= mkstemp(filename
);
1526 if (errno
!= EEXIST
&& errno
!= EINTR
) {
1527 error_setg_errno(errp
, errno
,
1528 "can't open backing store %s for guest RAM",
1533 * Try again on EINTR and EEXIST. The latter happens when
1534 * something else creates the file between our two open().
1541 static void *file_ram_alloc(RAMBlock
*block
,
1550 block
->page_size
= qemu_fd_getpagesize(fd
);
1551 if (block
->mr
->align
% block
->page_size
) {
1552 error_setg(errp
, "alignment 0x%" PRIx64
1553 " must be multiples of page size 0x%zx",
1554 block
->mr
->align
, block
->page_size
);
1556 } else if (block
->mr
->align
&& !is_power_of_2(block
->mr
->align
)) {
1557 error_setg(errp
, "alignment 0x%" PRIx64
1558 " must be a power of two", block
->mr
->align
);
1561 block
->mr
->align
= MAX(block
->page_size
, block
->mr
->align
);
1562 #if defined(__s390x__)
1563 if (kvm_enabled()) {
1564 block
->mr
->align
= MAX(block
->mr
->align
, QEMU_VMALLOC_ALIGN
);
1568 if (memory
< block
->page_size
) {
1569 error_setg(errp
, "memory size 0x" RAM_ADDR_FMT
" must be equal to "
1570 "or larger than page size 0x%zx",
1571 memory
, block
->page_size
);
1575 memory
= ROUND_UP(memory
, block
->page_size
);
1578 * ftruncate is not supported by hugetlbfs in older
1579 * hosts, so don't bother bailing out on errors.
1580 * If anything goes wrong with it under other filesystems,
1583 * Do not truncate the non-empty backend file to avoid corrupting
1584 * the existing data in the file. Disabling shrinking is not
1585 * enough. For example, the current vNVDIMM implementation stores
1586 * the guest NVDIMM labels at the end of the backend file. If the
1587 * backend file is later extended, QEMU will not be able to find
1588 * those labels. Therefore, extending the non-empty backend file
1589 * is disabled as well.
1591 if (truncate
&& ftruncate(fd
, memory
)) {
1592 perror("ftruncate");
1595 area
= qemu_ram_mmap(fd
, memory
, block
->mr
->align
, readonly
,
1596 block
->flags
& RAM_SHARED
, block
->flags
& RAM_PMEM
);
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 bool qemu_ram_is_shared(RAMBlock
*rb
)
1713 return rb
->flags
& RAM_SHARED
;
1716 /* Note: Only set at the start of postcopy */
1717 bool qemu_ram_is_uf_zeroable(RAMBlock
*rb
)
1719 return rb
->flags
& RAM_UF_ZEROPAGE
;
1722 void qemu_ram_set_uf_zeroable(RAMBlock
*rb
)
1724 rb
->flags
|= RAM_UF_ZEROPAGE
;
1727 bool qemu_ram_is_migratable(RAMBlock
*rb
)
1729 return rb
->flags
& RAM_MIGRATABLE
;
1732 void qemu_ram_set_migratable(RAMBlock
*rb
)
1734 rb
->flags
|= RAM_MIGRATABLE
;
1737 void qemu_ram_unset_migratable(RAMBlock
*rb
)
1739 rb
->flags
&= ~RAM_MIGRATABLE
;
1742 /* Called with iothread lock held. */
1743 void qemu_ram_set_idstr(RAMBlock
*new_block
, const char *name
, DeviceState
*dev
)
1748 assert(!new_block
->idstr
[0]);
1751 char *id
= qdev_get_dev_path(dev
);
1753 snprintf(new_block
->idstr
, sizeof(new_block
->idstr
), "%s/", id
);
1757 pstrcat(new_block
->idstr
, sizeof(new_block
->idstr
), name
);
1759 RCU_READ_LOCK_GUARD();
1760 RAMBLOCK_FOREACH(block
) {
1761 if (block
!= new_block
&&
1762 !strcmp(block
->idstr
, new_block
->idstr
)) {
1763 fprintf(stderr
, "RAMBlock \"%s\" already registered, abort!\n",
1770 /* Called with iothread lock held. */
1771 void qemu_ram_unset_idstr(RAMBlock
*block
)
1773 /* FIXME: arch_init.c assumes that this is not called throughout
1774 * migration. Ignore the problem since hot-unplug during migration
1775 * does not work anyway.
1778 memset(block
->idstr
, 0, sizeof(block
->idstr
));
1782 size_t qemu_ram_pagesize(RAMBlock
*rb
)
1784 return rb
->page_size
;
1787 /* Returns the largest size of page in use */
1788 size_t qemu_ram_pagesize_largest(void)
1793 RAMBLOCK_FOREACH(block
) {
1794 largest
= MAX(largest
, qemu_ram_pagesize(block
));
1800 static int memory_try_enable_merging(void *addr
, size_t len
)
1802 if (!machine_mem_merge(current_machine
)) {
1803 /* disabled by the user */
1807 return qemu_madvise(addr
, len
, QEMU_MADV_MERGEABLE
);
1810 /* Only legal before guest might have detected the memory size: e.g. on
1811 * incoming migration, or right after reset.
1813 * As memory core doesn't know how is memory accessed, it is up to
1814 * resize callback to update device state and/or add assertions to detect
1815 * misuse, if necessary.
1817 int qemu_ram_resize(RAMBlock
*block
, ram_addr_t newsize
, Error
**errp
)
1819 const ram_addr_t unaligned_size
= newsize
;
1823 newsize
= HOST_PAGE_ALIGN(newsize
);
1825 if (block
->used_length
== newsize
) {
1827 * We don't have to resize the ram block (which only knows aligned
1828 * sizes), however, we have to notify if the unaligned size changed.
1830 if (unaligned_size
!= memory_region_size(block
->mr
)) {
1831 memory_region_set_size(block
->mr
, unaligned_size
);
1832 if (block
->resized
) {
1833 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1839 if (!(block
->flags
& RAM_RESIZEABLE
)) {
1840 error_setg_errno(errp
, EINVAL
,
1841 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1842 " != 0x" RAM_ADDR_FMT
, block
->idstr
,
1843 newsize
, block
->used_length
);
1847 if (block
->max_length
< newsize
) {
1848 error_setg_errno(errp
, EINVAL
,
1849 "Size too large: %s: 0x" RAM_ADDR_FMT
1850 " > 0x" RAM_ADDR_FMT
, block
->idstr
,
1851 newsize
, block
->max_length
);
1855 cpu_physical_memory_clear_dirty_range(block
->offset
, block
->used_length
);
1856 block
->used_length
= newsize
;
1857 cpu_physical_memory_set_dirty_range(block
->offset
, block
->used_length
,
1859 memory_region_set_size(block
->mr
, unaligned_size
);
1860 if (block
->resized
) {
1861 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1867 * Trigger sync on the given ram block for range [start, start + length]
1868 * with the backing store if one is available.
1870 * @Note: this is supposed to be a synchronous op.
1872 void qemu_ram_msync(RAMBlock
*block
, ram_addr_t start
, ram_addr_t length
)
1874 /* The requested range should fit in within the block range */
1875 g_assert((start
+ length
) <= block
->used_length
);
1877 #ifdef CONFIG_LIBPMEM
1878 /* The lack of support for pmem should not block the sync */
1879 if (ramblock_is_pmem(block
)) {
1880 void *addr
= ramblock_ptr(block
, start
);
1881 pmem_persist(addr
, length
);
1885 if (block
->fd
>= 0) {
1887 * Case there is no support for PMEM or the memory has not been
1888 * specified as persistent (or is not one) - use the msync.
1889 * Less optimal but still achieves the same goal
1891 void *addr
= ramblock_ptr(block
, start
);
1892 if (qemu_msync(addr
, length
, block
->fd
)) {
1893 warn_report("%s: failed to sync memory range: start: "
1894 RAM_ADDR_FMT
" length: " RAM_ADDR_FMT
,
1895 __func__
, start
, length
);
1900 /* Called with ram_list.mutex held */
1901 static void dirty_memory_extend(ram_addr_t old_ram_size
,
1902 ram_addr_t new_ram_size
)
1904 ram_addr_t old_num_blocks
= DIV_ROUND_UP(old_ram_size
,
1905 DIRTY_MEMORY_BLOCK_SIZE
);
1906 ram_addr_t new_num_blocks
= DIV_ROUND_UP(new_ram_size
,
1907 DIRTY_MEMORY_BLOCK_SIZE
);
1910 /* Only need to extend if block count increased */
1911 if (new_num_blocks
<= old_num_blocks
) {
1915 for (i
= 0; i
< DIRTY_MEMORY_NUM
; i
++) {
1916 DirtyMemoryBlocks
*old_blocks
;
1917 DirtyMemoryBlocks
*new_blocks
;
1920 old_blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[i
]);
1921 new_blocks
= g_malloc(sizeof(*new_blocks
) +
1922 sizeof(new_blocks
->blocks
[0]) * new_num_blocks
);
1924 if (old_num_blocks
) {
1925 memcpy(new_blocks
->blocks
, old_blocks
->blocks
,
1926 old_num_blocks
* sizeof(old_blocks
->blocks
[0]));
1929 for (j
= old_num_blocks
; j
< new_num_blocks
; j
++) {
1930 new_blocks
->blocks
[j
] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE
);
1933 qatomic_rcu_set(&ram_list
.dirty_memory
[i
], new_blocks
);
1936 g_free_rcu(old_blocks
, rcu
);
1941 static void ram_block_add(RAMBlock
*new_block
, Error
**errp
, bool shared
)
1944 RAMBlock
*last_block
= NULL
;
1945 ram_addr_t old_ram_size
, new_ram_size
;
1948 old_ram_size
= last_ram_page();
1950 qemu_mutex_lock_ramlist();
1951 new_block
->offset
= find_ram_offset(new_block
->max_length
);
1953 if (!new_block
->host
) {
1954 if (xen_enabled()) {
1955 xen_ram_alloc(new_block
->offset
, new_block
->max_length
,
1956 new_block
->mr
, &err
);
1958 error_propagate(errp
, err
);
1959 qemu_mutex_unlock_ramlist();
1963 new_block
->host
= phys_mem_alloc(new_block
->max_length
,
1964 &new_block
->mr
->align
, shared
);
1965 if (!new_block
->host
) {
1966 error_setg_errno(errp
, errno
,
1967 "cannot set up guest memory '%s'",
1968 memory_region_name(new_block
->mr
));
1969 qemu_mutex_unlock_ramlist();
1972 memory_try_enable_merging(new_block
->host
, new_block
->max_length
);
1976 new_ram_size
= MAX(old_ram_size
,
1977 (new_block
->offset
+ new_block
->max_length
) >> TARGET_PAGE_BITS
);
1978 if (new_ram_size
> old_ram_size
) {
1979 dirty_memory_extend(old_ram_size
, new_ram_size
);
1981 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1982 * QLIST (which has an RCU-friendly variant) does not have insertion at
1983 * tail, so save the last element in last_block.
1985 RAMBLOCK_FOREACH(block
) {
1987 if (block
->max_length
< new_block
->max_length
) {
1992 QLIST_INSERT_BEFORE_RCU(block
, new_block
, next
);
1993 } else if (last_block
) {
1994 QLIST_INSERT_AFTER_RCU(last_block
, new_block
, next
);
1995 } else { /* list is empty */
1996 QLIST_INSERT_HEAD_RCU(&ram_list
.blocks
, new_block
, next
);
1998 ram_list
.mru_block
= NULL
;
2000 /* Write list before version */
2003 qemu_mutex_unlock_ramlist();
2005 cpu_physical_memory_set_dirty_range(new_block
->offset
,
2006 new_block
->used_length
,
2009 if (new_block
->host
) {
2010 qemu_ram_setup_dump(new_block
->host
, new_block
->max_length
);
2011 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_HUGEPAGE
);
2013 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
2014 * Configure it unless the machine is a qtest server, in which case
2015 * KVM is not used and it may be forked (eg for fuzzing purposes).
2017 if (!qtest_enabled()) {
2018 qemu_madvise(new_block
->host
, new_block
->max_length
,
2019 QEMU_MADV_DONTFORK
);
2021 ram_block_notify_add(new_block
->host
, new_block
->max_length
);
2026 RAMBlock
*qemu_ram_alloc_from_fd(ram_addr_t size
, MemoryRegion
*mr
,
2027 uint32_t ram_flags
, int fd
, bool readonly
,
2030 RAMBlock
*new_block
;
2031 Error
*local_err
= NULL
;
2032 int64_t file_size
, file_align
;
2034 /* Just support these ram flags by now. */
2035 assert((ram_flags
& ~(RAM_SHARED
| RAM_PMEM
)) == 0);
2037 if (xen_enabled()) {
2038 error_setg(errp
, "-mem-path not supported with Xen");
2042 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2044 "host lacks kvm mmu notifiers, -mem-path unsupported");
2048 if (phys_mem_alloc
!= qemu_anon_ram_alloc
) {
2050 * file_ram_alloc() needs to allocate just like
2051 * phys_mem_alloc, but we haven't bothered to provide
2055 "-mem-path not supported with this accelerator");
2059 size
= HOST_PAGE_ALIGN(size
);
2060 file_size
= get_file_size(fd
);
2061 if (file_size
> 0 && file_size
< size
) {
2062 error_setg(errp
, "backing store size 0x%" PRIx64
2063 " does not match 'size' option 0x" RAM_ADDR_FMT
,
2068 file_align
= get_file_align(fd
);
2069 if (file_align
> 0 && mr
&& file_align
> mr
->align
) {
2070 error_setg(errp
, "backing store align 0x%" PRIx64
2071 " is larger than 'align' option 0x%" PRIx64
,
2072 file_align
, mr
->align
);
2076 new_block
= g_malloc0(sizeof(*new_block
));
2078 new_block
->used_length
= size
;
2079 new_block
->max_length
= size
;
2080 new_block
->flags
= ram_flags
;
2081 new_block
->host
= file_ram_alloc(new_block
, size
, fd
, readonly
,
2083 if (!new_block
->host
) {
2088 ram_block_add(new_block
, &local_err
, ram_flags
& RAM_SHARED
);
2091 error_propagate(errp
, local_err
);
2099 RAMBlock
*qemu_ram_alloc_from_file(ram_addr_t size
, MemoryRegion
*mr
,
2100 uint32_t ram_flags
, const char *mem_path
,
2101 bool readonly
, Error
**errp
)
2107 fd
= file_ram_open(mem_path
, memory_region_name(mr
), readonly
, &created
,
2113 block
= qemu_ram_alloc_from_fd(size
, mr
, ram_flags
, fd
, readonly
, errp
);
2127 RAMBlock
*qemu_ram_alloc_internal(ram_addr_t size
, ram_addr_t max_size
,
2128 void (*resized
)(const char*,
2131 void *host
, bool resizeable
, bool share
,
2132 MemoryRegion
*mr
, Error
**errp
)
2134 RAMBlock
*new_block
;
2135 Error
*local_err
= NULL
;
2137 size
= HOST_PAGE_ALIGN(size
);
2138 max_size
= HOST_PAGE_ALIGN(max_size
);
2139 new_block
= g_malloc0(sizeof(*new_block
));
2141 new_block
->resized
= resized
;
2142 new_block
->used_length
= size
;
2143 new_block
->max_length
= max_size
;
2144 assert(max_size
>= size
);
2146 new_block
->page_size
= qemu_real_host_page_size
;
2147 new_block
->host
= host
;
2149 new_block
->flags
|= RAM_PREALLOC
;
2152 new_block
->flags
|= RAM_RESIZEABLE
;
2154 ram_block_add(new_block
, &local_err
, share
);
2157 error_propagate(errp
, local_err
);
2163 RAMBlock
*qemu_ram_alloc_from_ptr(ram_addr_t size
, void *host
,
2164 MemoryRegion
*mr
, Error
**errp
)
2166 return qemu_ram_alloc_internal(size
, size
, NULL
, host
, false,
2170 RAMBlock
*qemu_ram_alloc(ram_addr_t size
, bool share
,
2171 MemoryRegion
*mr
, Error
**errp
)
2173 return qemu_ram_alloc_internal(size
, size
, NULL
, NULL
, false,
2177 RAMBlock
*qemu_ram_alloc_resizeable(ram_addr_t size
, ram_addr_t maxsz
,
2178 void (*resized
)(const char*,
2181 MemoryRegion
*mr
, Error
**errp
)
2183 return qemu_ram_alloc_internal(size
, maxsz
, resized
, NULL
, true,
2187 static void reclaim_ramblock(RAMBlock
*block
)
2189 if (block
->flags
& RAM_PREALLOC
) {
2191 } else if (xen_enabled()) {
2192 xen_invalidate_map_cache_entry(block
->host
);
2194 } else if (block
->fd
>= 0) {
2195 qemu_ram_munmap(block
->fd
, block
->host
, block
->max_length
);
2199 qemu_anon_ram_free(block
->host
, block
->max_length
);
2204 void qemu_ram_free(RAMBlock
*block
)
2211 ram_block_notify_remove(block
->host
, block
->max_length
);
2214 qemu_mutex_lock_ramlist();
2215 QLIST_REMOVE_RCU(block
, next
);
2216 ram_list
.mru_block
= NULL
;
2217 /* Write list before version */
2220 call_rcu(block
, reclaim_ramblock
, rcu
);
2221 qemu_mutex_unlock_ramlist();
2225 void qemu_ram_remap(ram_addr_t addr
, ram_addr_t length
)
2232 RAMBLOCK_FOREACH(block
) {
2233 offset
= addr
- block
->offset
;
2234 if (offset
< block
->max_length
) {
2235 vaddr
= ramblock_ptr(block
, offset
);
2236 if (block
->flags
& RAM_PREALLOC
) {
2238 } else if (xen_enabled()) {
2242 if (block
->fd
>= 0) {
2243 flags
|= (block
->flags
& RAM_SHARED
?
2244 MAP_SHARED
: MAP_PRIVATE
);
2245 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2246 flags
, block
->fd
, offset
);
2249 * Remap needs to match alloc. Accelerators that
2250 * set phys_mem_alloc never remap. If they did,
2251 * we'd need a remap hook here.
2253 assert(phys_mem_alloc
== qemu_anon_ram_alloc
);
2255 flags
|= MAP_PRIVATE
| MAP_ANONYMOUS
;
2256 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2259 if (area
!= vaddr
) {
2260 error_report("Could not remap addr: "
2261 RAM_ADDR_FMT
"@" RAM_ADDR_FMT
"",
2265 memory_try_enable_merging(vaddr
, length
);
2266 qemu_ram_setup_dump(vaddr
, length
);
2271 #endif /* !_WIN32 */
2273 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2274 * This should not be used for general purpose DMA. Use address_space_map
2275 * or address_space_rw instead. For local memory (e.g. video ram) that the
2276 * device owns, use memory_region_get_ram_ptr.
2278 * Called within RCU critical section.
2280 void *qemu_map_ram_ptr(RAMBlock
*ram_block
, ram_addr_t addr
)
2282 RAMBlock
*block
= ram_block
;
2284 if (block
== NULL
) {
2285 block
= qemu_get_ram_block(addr
);
2286 addr
-= block
->offset
;
2289 if (xen_enabled() && block
->host
== NULL
) {
2290 /* We need to check if the requested address is in the RAM
2291 * because we don't want to map the entire memory in QEMU.
2292 * In that case just map until the end of the page.
2294 if (block
->offset
== 0) {
2295 return xen_map_cache(addr
, 0, 0, false);
2298 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, false);
2300 return ramblock_ptr(block
, addr
);
2303 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2304 * but takes a size argument.
2306 * Called within RCU critical section.
2308 static void *qemu_ram_ptr_length(RAMBlock
*ram_block
, ram_addr_t addr
,
2309 hwaddr
*size
, bool lock
)
2311 RAMBlock
*block
= ram_block
;
2316 if (block
== NULL
) {
2317 block
= qemu_get_ram_block(addr
);
2318 addr
-= block
->offset
;
2320 *size
= MIN(*size
, block
->max_length
- addr
);
2322 if (xen_enabled() && block
->host
== NULL
) {
2323 /* We need to check if the requested address is in the RAM
2324 * because we don't want to map the entire memory in QEMU.
2325 * In that case just map the requested area.
2327 if (block
->offset
== 0) {
2328 return xen_map_cache(addr
, *size
, lock
, lock
);
2331 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, lock
);
2334 return ramblock_ptr(block
, addr
);
2337 /* Return the offset of a hostpointer within a ramblock */
2338 ram_addr_t
qemu_ram_block_host_offset(RAMBlock
*rb
, void *host
)
2340 ram_addr_t res
= (uint8_t *)host
- (uint8_t *)rb
->host
;
2341 assert((uintptr_t)host
>= (uintptr_t)rb
->host
);
2342 assert(res
< rb
->max_length
);
2348 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2351 * ptr: Host pointer to look up
2352 * round_offset: If true round the result offset down to a page boundary
2353 * *ram_addr: set to result ram_addr
2354 * *offset: set to result offset within the RAMBlock
2356 * Returns: RAMBlock (or NULL if not found)
2358 * By the time this function returns, the returned pointer is not protected
2359 * by RCU anymore. If the caller is not within an RCU critical section and
2360 * does not hold the iothread lock, it must have other means of protecting the
2361 * pointer, such as a reference to the region that includes the incoming
2364 RAMBlock
*qemu_ram_block_from_host(void *ptr
, bool round_offset
,
2368 uint8_t *host
= ptr
;
2370 if (xen_enabled()) {
2371 ram_addr_t ram_addr
;
2372 RCU_READ_LOCK_GUARD();
2373 ram_addr
= xen_ram_addr_from_mapcache(ptr
);
2374 block
= qemu_get_ram_block(ram_addr
);
2376 *offset
= ram_addr
- block
->offset
;
2381 RCU_READ_LOCK_GUARD();
2382 block
= qatomic_rcu_read(&ram_list
.mru_block
);
2383 if (block
&& block
->host
&& host
- block
->host
< block
->max_length
) {
2387 RAMBLOCK_FOREACH(block
) {
2388 /* This case append when the block is not mapped. */
2389 if (block
->host
== NULL
) {
2392 if (host
- block
->host
< block
->max_length
) {
2400 *offset
= (host
- block
->host
);
2402 *offset
&= TARGET_PAGE_MASK
;
2408 * Finds the named RAMBlock
2410 * name: The name of RAMBlock to find
2412 * Returns: RAMBlock (or NULL if not found)
2414 RAMBlock
*qemu_ram_block_by_name(const char *name
)
2418 RAMBLOCK_FOREACH(block
) {
2419 if (!strcmp(name
, block
->idstr
)) {
2427 /* Some of the softmmu routines need to translate from a host pointer
2428 (typically a TLB entry) back to a ram offset. */
2429 ram_addr_t
qemu_ram_addr_from_host(void *ptr
)
2434 block
= qemu_ram_block_from_host(ptr
, false, &offset
);
2436 return RAM_ADDR_INVALID
;
2439 return block
->offset
+ offset
;
2442 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2443 MemTxAttrs attrs
, void *buf
, hwaddr len
);
2444 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2445 const void *buf
, hwaddr len
);
2446 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
2447 bool is_write
, MemTxAttrs attrs
);
2449 static MemTxResult
subpage_read(void *opaque
, hwaddr addr
, uint64_t *data
,
2450 unsigned len
, MemTxAttrs attrs
)
2452 subpage_t
*subpage
= opaque
;
2456 #if defined(DEBUG_SUBPAGE)
2457 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
"\n", __func__
,
2458 subpage
, len
, addr
);
2460 res
= flatview_read(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2464 *data
= ldn_p(buf
, len
);
2468 static MemTxResult
subpage_write(void *opaque
, hwaddr addr
,
2469 uint64_t value
, unsigned len
, MemTxAttrs attrs
)
2471 subpage_t
*subpage
= opaque
;
2474 #if defined(DEBUG_SUBPAGE)
2475 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2476 " value %"PRIx64
"\n",
2477 __func__
, subpage
, len
, addr
, value
);
2479 stn_p(buf
, len
, value
);
2480 return flatview_write(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2483 static bool subpage_accepts(void *opaque
, hwaddr addr
,
2484 unsigned len
, bool is_write
,
2487 subpage_t
*subpage
= opaque
;
2488 #if defined(DEBUG_SUBPAGE)
2489 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx
"\n",
2490 __func__
, subpage
, is_write
? 'w' : 'r', len
, addr
);
2493 return flatview_access_valid(subpage
->fv
, addr
+ subpage
->base
,
2494 len
, is_write
, attrs
);
2497 static const MemoryRegionOps subpage_ops
= {
2498 .read_with_attrs
= subpage_read
,
2499 .write_with_attrs
= subpage_write
,
2500 .impl
.min_access_size
= 1,
2501 .impl
.max_access_size
= 8,
2502 .valid
.min_access_size
= 1,
2503 .valid
.max_access_size
= 8,
2504 .valid
.accepts
= subpage_accepts
,
2505 .endianness
= DEVICE_NATIVE_ENDIAN
,
2508 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
2513 if (start
>= TARGET_PAGE_SIZE
|| end
>= TARGET_PAGE_SIZE
)
2515 idx
= SUBPAGE_IDX(start
);
2516 eidx
= SUBPAGE_IDX(end
);
2517 #if defined(DEBUG_SUBPAGE)
2518 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2519 __func__
, mmio
, start
, end
, idx
, eidx
, section
);
2521 for (; idx
<= eidx
; idx
++) {
2522 mmio
->sub_section
[idx
] = section
;
2528 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
)
2532 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2533 mmio
= g_malloc0(sizeof(subpage_t
) + TARGET_PAGE_SIZE
* sizeof(uint16_t));
2536 memory_region_init_io(&mmio
->iomem
, NULL
, &subpage_ops
, mmio
,
2537 NULL
, TARGET_PAGE_SIZE
);
2538 mmio
->iomem
.subpage
= true;
2539 #if defined(DEBUG_SUBPAGE)
2540 printf("%s: %p base " TARGET_FMT_plx
" len %08x\n", __func__
,
2541 mmio
, base
, TARGET_PAGE_SIZE
);
2547 static uint16_t dummy_section(PhysPageMap
*map
, FlatView
*fv
, MemoryRegion
*mr
)
2550 MemoryRegionSection section
= {
2553 .offset_within_address_space
= 0,
2554 .offset_within_region
= 0,
2555 .size
= int128_2_64(),
2558 return phys_section_add(map
, §ion
);
2561 MemoryRegionSection
*iotlb_to_section(CPUState
*cpu
,
2562 hwaddr index
, MemTxAttrs attrs
)
2564 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
2565 CPUAddressSpace
*cpuas
= &cpu
->cpu_ases
[asidx
];
2566 AddressSpaceDispatch
*d
= qatomic_rcu_read(&cpuas
->memory_dispatch
);
2567 MemoryRegionSection
*sections
= d
->map
.sections
;
2569 return §ions
[index
& ~TARGET_PAGE_MASK
];
2572 static void io_mem_init(void)
2574 memory_region_init_io(&io_mem_unassigned
, NULL
, &unassigned_mem_ops
, NULL
,
2578 AddressSpaceDispatch
*address_space_dispatch_new(FlatView
*fv
)
2580 AddressSpaceDispatch
*d
= g_new0(AddressSpaceDispatch
, 1);
2583 n
= dummy_section(&d
->map
, fv
, &io_mem_unassigned
);
2584 assert(n
== PHYS_SECTION_UNASSIGNED
);
2586 d
->phys_map
= (PhysPageEntry
) { .ptr
= PHYS_MAP_NODE_NIL
, .skip
= 1 };
2591 void address_space_dispatch_free(AddressSpaceDispatch
*d
)
2593 phys_sections_free(&d
->map
);
2597 static void do_nothing(CPUState
*cpu
, run_on_cpu_data d
)
2601 static void tcg_log_global_after_sync(MemoryListener
*listener
)
2603 CPUAddressSpace
*cpuas
;
2605 /* Wait for the CPU to end the current TB. This avoids the following
2609 * ---------------------- -------------------------
2610 * TLB check -> slow path
2611 * notdirty_mem_write
2615 * TLB check -> fast path
2619 * by pushing the migration thread's memory read after the vCPU thread has
2620 * written the memory.
2622 if (replay_mode
== REPLAY_MODE_NONE
) {
2624 * VGA can make calls to this function while updating the screen.
2625 * In record/replay mode this causes a deadlock, because
2626 * run_on_cpu waits for rr mutex. Therefore no races are possible
2627 * in this case and no need for making run_on_cpu when
2628 * record/replay is not enabled.
2630 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2631 run_on_cpu(cpuas
->cpu
, do_nothing
, RUN_ON_CPU_NULL
);
2635 static void tcg_commit(MemoryListener
*listener
)
2637 CPUAddressSpace
*cpuas
;
2638 AddressSpaceDispatch
*d
;
2640 assert(tcg_enabled());
2641 /* since each CPU stores ram addresses in its TLB cache, we must
2642 reset the modified entries */
2643 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2644 cpu_reloading_memory_map();
2645 /* The CPU and TLB are protected by the iothread lock.
2646 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2647 * may have split the RCU critical section.
2649 d
= address_space_to_dispatch(cpuas
->as
);
2650 qatomic_rcu_set(&cpuas
->memory_dispatch
, d
);
2651 tlb_flush(cpuas
->cpu
);
2654 static void memory_map_init(void)
2656 system_memory
= g_malloc(sizeof(*system_memory
));
2658 memory_region_init(system_memory
, NULL
, "system", UINT64_MAX
);
2659 address_space_init(&address_space_memory
, system_memory
, "memory");
2661 system_io
= g_malloc(sizeof(*system_io
));
2662 memory_region_init_io(system_io
, NULL
, &unassigned_io_ops
, NULL
, "io",
2664 address_space_init(&address_space_io
, system_io
, "I/O");
2667 MemoryRegion
*get_system_memory(void)
2669 return system_memory
;
2672 MemoryRegion
*get_system_io(void)
2677 static void invalidate_and_set_dirty(MemoryRegion
*mr
, hwaddr addr
,
2680 uint8_t dirty_log_mask
= memory_region_get_dirty_log_mask(mr
);
2681 addr
+= memory_region_get_ram_addr(mr
);
2683 /* No early return if dirty_log_mask is or becomes 0, because
2684 * cpu_physical_memory_set_dirty_range will still call
2685 * xen_modified_memory.
2687 if (dirty_log_mask
) {
2689 cpu_physical_memory_range_includes_clean(addr
, length
, dirty_log_mask
);
2691 if (dirty_log_mask
& (1 << DIRTY_MEMORY_CODE
)) {
2692 assert(tcg_enabled());
2693 tb_invalidate_phys_range(addr
, addr
+ length
);
2694 dirty_log_mask
&= ~(1 << DIRTY_MEMORY_CODE
);
2696 cpu_physical_memory_set_dirty_range(addr
, length
, dirty_log_mask
);
2699 void memory_region_flush_rom_device(MemoryRegion
*mr
, hwaddr addr
, hwaddr size
)
2702 * In principle this function would work on other memory region types too,
2703 * but the ROM device use case is the only one where this operation is
2704 * necessary. Other memory regions should use the
2705 * address_space_read/write() APIs.
2707 assert(memory_region_is_romd(mr
));
2709 invalidate_and_set_dirty(mr
, addr
, size
);
2712 static int memory_access_size(MemoryRegion
*mr
, unsigned l
, hwaddr addr
)
2714 unsigned access_size_max
= mr
->ops
->valid
.max_access_size
;
2716 /* Regions are assumed to support 1-4 byte accesses unless
2717 otherwise specified. */
2718 if (access_size_max
== 0) {
2719 access_size_max
= 4;
2722 /* Bound the maximum access by the alignment of the address. */
2723 if (!mr
->ops
->impl
.unaligned
) {
2724 unsigned align_size_max
= addr
& -addr
;
2725 if (align_size_max
!= 0 && align_size_max
< access_size_max
) {
2726 access_size_max
= align_size_max
;
2730 /* Don't attempt accesses larger than the maximum. */
2731 if (l
> access_size_max
) {
2732 l
= access_size_max
;
2739 static bool prepare_mmio_access(MemoryRegion
*mr
)
2741 bool release_lock
= false;
2743 if (!qemu_mutex_iothread_locked()) {
2744 qemu_mutex_lock_iothread();
2745 release_lock
= true;
2747 if (mr
->flush_coalesced_mmio
) {
2748 qemu_flush_coalesced_mmio_buffer();
2751 return release_lock
;
2754 /* Called within RCU critical section. */
2755 static MemTxResult
flatview_write_continue(FlatView
*fv
, hwaddr addr
,
2758 hwaddr len
, hwaddr addr1
,
2759 hwaddr l
, MemoryRegion
*mr
)
2763 MemTxResult result
= MEMTX_OK
;
2764 bool release_lock
= false;
2765 const uint8_t *buf
= ptr
;
2768 if (!memory_access_is_direct(mr
, true)) {
2769 release_lock
|= prepare_mmio_access(mr
);
2770 l
= memory_access_size(mr
, l
, addr1
);
2771 /* XXX: could force current_cpu to NULL to avoid
2773 val
= ldn_he_p(buf
, l
);
2774 result
|= memory_region_dispatch_write(mr
, addr1
, val
,
2775 size_memop(l
), attrs
);
2778 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2779 memcpy(ram_ptr
, buf
, l
);
2780 invalidate_and_set_dirty(mr
, addr1
, l
);
2784 qemu_mutex_unlock_iothread();
2785 release_lock
= false;
2797 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2803 /* Called from RCU critical section. */
2804 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2805 const void *buf
, hwaddr len
)
2810 MemTxResult result
= MEMTX_OK
;
2813 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2814 result
= flatview_write_continue(fv
, addr
, attrs
, buf
, len
,
2820 /* Called within RCU critical section. */
2821 MemTxResult
flatview_read_continue(FlatView
*fv
, hwaddr addr
,
2822 MemTxAttrs attrs
, void *ptr
,
2823 hwaddr len
, hwaddr addr1
, hwaddr l
,
2828 MemTxResult result
= MEMTX_OK
;
2829 bool release_lock
= false;
2833 if (!memory_access_is_direct(mr
, false)) {
2835 release_lock
|= prepare_mmio_access(mr
);
2836 l
= memory_access_size(mr
, l
, addr1
);
2837 result
|= memory_region_dispatch_read(mr
, addr1
, &val
,
2838 size_memop(l
), attrs
);
2839 stn_he_p(buf
, l
, val
);
2842 fuzz_dma_read_cb(addr
, len
, mr
, false);
2843 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2844 memcpy(buf
, ram_ptr
, l
);
2848 qemu_mutex_unlock_iothread();
2849 release_lock
= false;
2861 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2867 /* Called from RCU critical section. */
2868 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2869 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2876 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2877 return flatview_read_continue(fv
, addr
, attrs
, buf
, len
,
2881 MemTxResult
address_space_read_full(AddressSpace
*as
, hwaddr addr
,
2882 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2884 MemTxResult result
= MEMTX_OK
;
2888 RCU_READ_LOCK_GUARD();
2889 fv
= address_space_to_flatview(as
);
2890 result
= flatview_read(fv
, addr
, attrs
, buf
, len
);
2896 MemTxResult
address_space_write(AddressSpace
*as
, hwaddr addr
,
2898 const void *buf
, hwaddr len
)
2900 MemTxResult result
= MEMTX_OK
;
2904 RCU_READ_LOCK_GUARD();
2905 fv
= address_space_to_flatview(as
);
2906 result
= flatview_write(fv
, addr
, attrs
, buf
, len
);
2912 MemTxResult
address_space_rw(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
,
2913 void *buf
, hwaddr len
, bool is_write
)
2916 return address_space_write(as
, addr
, attrs
, buf
, len
);
2918 return address_space_read_full(as
, addr
, attrs
, buf
, len
);
2922 void cpu_physical_memory_rw(hwaddr addr
, void *buf
,
2923 hwaddr len
, bool is_write
)
2925 address_space_rw(&address_space_memory
, addr
, MEMTXATTRS_UNSPECIFIED
,
2926 buf
, len
, is_write
);
2929 enum write_rom_type
{
2934 static inline MemTxResult
address_space_write_rom_internal(AddressSpace
*as
,
2939 enum write_rom_type type
)
2945 const uint8_t *buf
= ptr
;
2947 RCU_READ_LOCK_GUARD();
2950 mr
= address_space_translate(as
, addr
, &addr1
, &l
, true, attrs
);
2952 if (!(memory_region_is_ram(mr
) ||
2953 memory_region_is_romd(mr
))) {
2954 l
= memory_access_size(mr
, l
, addr1
);
2957 ram_ptr
= qemu_map_ram_ptr(mr
->ram_block
, addr1
);
2960 memcpy(ram_ptr
, buf
, l
);
2961 invalidate_and_set_dirty(mr
, addr1
, l
);
2964 flush_idcache_range((uintptr_t)ram_ptr
, (uintptr_t)ram_ptr
, l
);
2975 /* used for ROM loading : can write in RAM and ROM */
2976 MemTxResult
address_space_write_rom(AddressSpace
*as
, hwaddr addr
,
2978 const void *buf
, hwaddr len
)
2980 return address_space_write_rom_internal(as
, addr
, attrs
,
2981 buf
, len
, WRITE_DATA
);
2984 void cpu_flush_icache_range(hwaddr start
, hwaddr len
)
2987 * This function should do the same thing as an icache flush that was
2988 * triggered from within the guest. For TCG we are always cache coherent,
2989 * so there is no need to flush anything. For KVM / Xen we need to flush
2990 * the host's instruction cache at least.
2992 if (tcg_enabled()) {
2996 address_space_write_rom_internal(&address_space_memory
,
2997 start
, MEMTXATTRS_UNSPECIFIED
,
2998 NULL
, len
, FLUSH_CACHE
);
3009 static BounceBuffer bounce
;
3011 typedef struct MapClient
{
3013 QLIST_ENTRY(MapClient
) link
;
3016 QemuMutex map_client_list_lock
;
3017 static QLIST_HEAD(, MapClient
) map_client_list
3018 = QLIST_HEAD_INITIALIZER(map_client_list
);
3020 static void cpu_unregister_map_client_do(MapClient
*client
)
3022 QLIST_REMOVE(client
, link
);
3026 static void cpu_notify_map_clients_locked(void)
3030 while (!QLIST_EMPTY(&map_client_list
)) {
3031 client
= QLIST_FIRST(&map_client_list
);
3032 qemu_bh_schedule(client
->bh
);
3033 cpu_unregister_map_client_do(client
);
3037 void cpu_register_map_client(QEMUBH
*bh
)
3039 MapClient
*client
= g_malloc(sizeof(*client
));
3041 qemu_mutex_lock(&map_client_list_lock
);
3043 QLIST_INSERT_HEAD(&map_client_list
, client
, link
);
3044 if (!qatomic_read(&bounce
.in_use
)) {
3045 cpu_notify_map_clients_locked();
3047 qemu_mutex_unlock(&map_client_list_lock
);
3050 void cpu_exec_init_all(void)
3052 qemu_mutex_init(&ram_list
.mutex
);
3053 /* The data structures we set up here depend on knowing the page size,
3054 * so no more changes can be made after this point.
3055 * In an ideal world, nothing we did before we had finished the
3056 * machine setup would care about the target page size, and we could
3057 * do this much later, rather than requiring board models to state
3058 * up front what their requirements are.
3060 finalize_target_page_bits();
3063 qemu_mutex_init(&map_client_list_lock
);
3066 void cpu_unregister_map_client(QEMUBH
*bh
)
3070 qemu_mutex_lock(&map_client_list_lock
);
3071 QLIST_FOREACH(client
, &map_client_list
, link
) {
3072 if (client
->bh
== bh
) {
3073 cpu_unregister_map_client_do(client
);
3077 qemu_mutex_unlock(&map_client_list_lock
);
3080 static void cpu_notify_map_clients(void)
3082 qemu_mutex_lock(&map_client_list_lock
);
3083 cpu_notify_map_clients_locked();
3084 qemu_mutex_unlock(&map_client_list_lock
);
3087 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
3088 bool is_write
, MemTxAttrs attrs
)
3095 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3096 if (!memory_access_is_direct(mr
, is_write
)) {
3097 l
= memory_access_size(mr
, l
, addr
);
3098 if (!memory_region_access_valid(mr
, xlat
, l
, is_write
, attrs
)) {
3109 bool address_space_access_valid(AddressSpace
*as
, hwaddr addr
,
3110 hwaddr len
, bool is_write
,
3116 RCU_READ_LOCK_GUARD();
3117 fv
= address_space_to_flatview(as
);
3118 result
= flatview_access_valid(fv
, addr
, len
, is_write
, attrs
);
3123 flatview_extend_translation(FlatView
*fv
, hwaddr addr
,
3125 MemoryRegion
*mr
, hwaddr base
, hwaddr len
,
3126 bool is_write
, MemTxAttrs attrs
)
3130 MemoryRegion
*this_mr
;
3136 if (target_len
== 0) {
3141 this_mr
= flatview_translate(fv
, addr
, &xlat
,
3142 &len
, is_write
, attrs
);
3143 if (this_mr
!= mr
|| xlat
!= base
+ done
) {
3149 /* Map a physical memory region into a host virtual address.
3150 * May map a subset of the requested range, given by and returned in *plen.
3151 * May return NULL if resources needed to perform the mapping are exhausted.
3152 * Use only for reads OR writes - not for read-modify-write operations.
3153 * Use cpu_register_map_client() to know when retrying the map operation is
3154 * likely to succeed.
3156 void *address_space_map(AddressSpace
*as
,
3173 RCU_READ_LOCK_GUARD();
3174 fv
= address_space_to_flatview(as
);
3175 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3177 if (!memory_access_is_direct(mr
, is_write
)) {
3178 if (qatomic_xchg(&bounce
.in_use
, true)) {
3182 /* Avoid unbounded allocations */
3183 l
= MIN(l
, TARGET_PAGE_SIZE
);
3184 bounce
.buffer
= qemu_memalign(TARGET_PAGE_SIZE
, l
);
3188 memory_region_ref(mr
);
3191 flatview_read(fv
, addr
, MEMTXATTRS_UNSPECIFIED
,
3196 return bounce
.buffer
;
3200 memory_region_ref(mr
);
3201 *plen
= flatview_extend_translation(fv
, addr
, len
, mr
, xlat
,
3202 l
, is_write
, attrs
);
3203 fuzz_dma_read_cb(addr
, *plen
, mr
, is_write
);
3204 ptr
= qemu_ram_ptr_length(mr
->ram_block
, xlat
, plen
, true);
3209 /* Unmaps a memory region previously mapped by address_space_map().
3210 * Will also mark the memory as dirty if is_write is true. access_len gives
3211 * the amount of memory that was actually read or written by the caller.
3213 void address_space_unmap(AddressSpace
*as
, void *buffer
, hwaddr len
,
3214 bool is_write
, hwaddr access_len
)
3216 if (buffer
!= bounce
.buffer
) {
3220 mr
= memory_region_from_host(buffer
, &addr1
);
3223 invalidate_and_set_dirty(mr
, addr1
, access_len
);
3225 if (xen_enabled()) {
3226 xen_invalidate_map_cache_entry(buffer
);
3228 memory_region_unref(mr
);
3232 address_space_write(as
, bounce
.addr
, MEMTXATTRS_UNSPECIFIED
,
3233 bounce
.buffer
, access_len
);
3235 qemu_vfree(bounce
.buffer
);
3236 bounce
.buffer
= NULL
;
3237 memory_region_unref(bounce
.mr
);
3238 qatomic_mb_set(&bounce
.in_use
, false);
3239 cpu_notify_map_clients();
3242 void *cpu_physical_memory_map(hwaddr addr
,
3246 return address_space_map(&address_space_memory
, addr
, plen
, is_write
,
3247 MEMTXATTRS_UNSPECIFIED
);
3250 void cpu_physical_memory_unmap(void *buffer
, hwaddr len
,
3251 bool is_write
, hwaddr access_len
)
3253 return address_space_unmap(&address_space_memory
, buffer
, len
, is_write
, access_len
);
3256 #define ARG1_DECL AddressSpace *as
3259 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3260 #define RCU_READ_LOCK(...) rcu_read_lock()
3261 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3262 #include "memory_ldst.c.inc"
3264 int64_t address_space_cache_init(MemoryRegionCache
*cache
,
3270 AddressSpaceDispatch
*d
;
3278 cache
->fv
= address_space_get_flatview(as
);
3279 d
= flatview_to_dispatch(cache
->fv
);
3280 cache
->mrs
= *address_space_translate_internal(d
, addr
, &cache
->xlat
, &l
, true);
3283 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3284 * Take that into account to compute how many bytes are there between
3285 * cache->xlat and the end of the section.
3287 diff
= int128_sub(cache
->mrs
.size
,
3288 int128_make64(cache
->xlat
- cache
->mrs
.offset_within_region
));
3289 l
= int128_get64(int128_min(diff
, int128_make64(l
)));
3292 memory_region_ref(mr
);
3293 if (memory_access_is_direct(mr
, is_write
)) {
3294 /* We don't care about the memory attributes here as we're only
3295 * doing this if we found actual RAM, which behaves the same
3296 * regardless of attributes; so UNSPECIFIED is fine.
3298 l
= flatview_extend_translation(cache
->fv
, addr
, len
, mr
,
3299 cache
->xlat
, l
, is_write
,
3300 MEMTXATTRS_UNSPECIFIED
);
3301 cache
->ptr
= qemu_ram_ptr_length(mr
->ram_block
, cache
->xlat
, &l
, true);
3307 cache
->is_write
= is_write
;
3311 void address_space_cache_invalidate(MemoryRegionCache
*cache
,
3315 assert(cache
->is_write
);
3316 if (likely(cache
->ptr
)) {
3317 invalidate_and_set_dirty(cache
->mrs
.mr
, addr
+ cache
->xlat
, access_len
);
3321 void address_space_cache_destroy(MemoryRegionCache
*cache
)
3323 if (!cache
->mrs
.mr
) {
3327 if (xen_enabled()) {
3328 xen_invalidate_map_cache_entry(cache
->ptr
);
3330 memory_region_unref(cache
->mrs
.mr
);
3331 flatview_unref(cache
->fv
);
3332 cache
->mrs
.mr
= NULL
;
3336 /* Called from RCU critical section. This function has the same
3337 * semantics as address_space_translate, but it only works on a
3338 * predefined range of a MemoryRegion that was mapped with
3339 * address_space_cache_init.
3341 static inline MemoryRegion
*address_space_translate_cached(
3342 MemoryRegionCache
*cache
, hwaddr addr
, hwaddr
*xlat
,
3343 hwaddr
*plen
, bool is_write
, MemTxAttrs attrs
)
3345 MemoryRegionSection section
;
3347 IOMMUMemoryRegion
*iommu_mr
;
3348 AddressSpace
*target_as
;
3350 assert(!cache
->ptr
);
3351 *xlat
= addr
+ cache
->xlat
;
3354 iommu_mr
= memory_region_get_iommu(mr
);
3360 section
= address_space_translate_iommu(iommu_mr
, xlat
, plen
,
3361 NULL
, is_write
, true,
3366 /* Called from RCU critical section. address_space_read_cached uses this
3367 * out of line function when the target is an MMIO or IOMMU region.
3370 address_space_read_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3371 void *buf
, hwaddr len
)
3377 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, false,
3378 MEMTXATTRS_UNSPECIFIED
);
3379 return flatview_read_continue(cache
->fv
,
3380 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3384 /* Called from RCU critical section. address_space_write_cached uses this
3385 * out of line function when the target is an MMIO or IOMMU region.
3388 address_space_write_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3389 const void *buf
, hwaddr len
)
3395 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, true,
3396 MEMTXATTRS_UNSPECIFIED
);
3397 return flatview_write_continue(cache
->fv
,
3398 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3402 #define ARG1_DECL MemoryRegionCache *cache
3404 #define SUFFIX _cached_slow
3405 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3406 #define RCU_READ_LOCK() ((void)0)
3407 #define RCU_READ_UNLOCK() ((void)0)
3408 #include "memory_ldst.c.inc"
3410 /* virtual memory access for debug (includes writing to ROM) */
3411 int cpu_memory_rw_debug(CPUState
*cpu
, target_ulong addr
,
3412 void *ptr
, target_ulong len
, bool is_write
)
3415 target_ulong l
, page
;
3418 cpu_synchronize_state(cpu
);
3424 page
= addr
& TARGET_PAGE_MASK
;
3425 phys_addr
= cpu_get_phys_page_attrs_debug(cpu
, page
, &attrs
);
3426 asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
3427 /* if no physical page mapped, return an error */
3428 if (phys_addr
== -1)
3430 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3433 phys_addr
+= (addr
& ~TARGET_PAGE_MASK
);
3435 res
= address_space_write_rom(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3438 res
= address_space_read(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3441 if (res
!= MEMTX_OK
) {
3452 * Allows code that needs to deal with migration bitmaps etc to still be built
3453 * target independent.
3455 size_t qemu_target_page_size(void)
3457 return TARGET_PAGE_SIZE
;
3460 int qemu_target_page_bits(void)
3462 return TARGET_PAGE_BITS
;
3465 int qemu_target_page_bits_min(void)
3467 return TARGET_PAGE_BITS_MIN
;
3470 bool cpu_physical_memory_is_io(hwaddr phys_addr
)
3476 RCU_READ_LOCK_GUARD();
3477 mr
= address_space_translate(&address_space_memory
,
3478 phys_addr
, &phys_addr
, &l
, false,
3479 MEMTXATTRS_UNSPECIFIED
);
3481 res
= !(memory_region_is_ram(mr
) || memory_region_is_romd(mr
));
3485 int qemu_ram_foreach_block(RAMBlockIterFunc func
, void *opaque
)
3490 RCU_READ_LOCK_GUARD();
3491 RAMBLOCK_FOREACH(block
) {
3492 ret
= func(block
, opaque
);
3501 * Unmap pages of memory from start to start+length such that
3502 * they a) read as 0, b) Trigger whatever fault mechanism
3503 * the OS provides for postcopy.
3504 * The pages must be unmapped by the end of the function.
3505 * Returns: 0 on success, none-0 on failure
3508 int ram_block_discard_range(RAMBlock
*rb
, uint64_t start
, size_t length
)
3512 uint8_t *host_startaddr
= rb
->host
+ start
;
3514 if (!QEMU_PTR_IS_ALIGNED(host_startaddr
, rb
->page_size
)) {
3515 error_report("ram_block_discard_range: Unaligned start address: %p",
3520 if ((start
+ length
) <= rb
->used_length
) {
3521 bool need_madvise
, need_fallocate
;
3522 if (!QEMU_IS_ALIGNED(length
, rb
->page_size
)) {
3523 error_report("ram_block_discard_range: Unaligned length: %zx",
3528 errno
= ENOTSUP
; /* If we are missing MADVISE etc */
3530 /* The logic here is messy;
3531 * madvise DONTNEED fails for hugepages
3532 * fallocate works on hugepages and shmem
3534 need_madvise
= (rb
->page_size
== qemu_host_page_size
);
3535 need_fallocate
= rb
->fd
!= -1;
3536 if (need_fallocate
) {
3537 /* For a file, this causes the area of the file to be zero'd
3538 * if read, and for hugetlbfs also causes it to be unmapped
3539 * so a userfault will trigger.
3541 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3542 ret
= fallocate(rb
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3546 error_report("ram_block_discard_range: Failed to fallocate "
3547 "%s:%" PRIx64
" +%zx (%d)",
3548 rb
->idstr
, start
, length
, ret
);
3553 error_report("ram_block_discard_range: fallocate not available/file"
3554 "%s:%" PRIx64
" +%zx (%d)",
3555 rb
->idstr
, start
, length
, ret
);
3560 /* For normal RAM this causes it to be unmapped,
3561 * for shared memory it causes the local mapping to disappear
3562 * and to fall back on the file contents (which we just
3563 * fallocate'd away).
3565 #if defined(CONFIG_MADVISE)
3566 ret
= madvise(host_startaddr
, length
, MADV_DONTNEED
);
3569 error_report("ram_block_discard_range: Failed to discard range "
3570 "%s:%" PRIx64
" +%zx (%d)",
3571 rb
->idstr
, start
, length
, ret
);
3576 error_report("ram_block_discard_range: MADVISE not available"
3577 "%s:%" PRIx64
" +%zx (%d)",
3578 rb
->idstr
, start
, length
, ret
);
3582 trace_ram_block_discard_range(rb
->idstr
, host_startaddr
, length
,
3583 need_madvise
, need_fallocate
, ret
);
3585 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3586 "/%zx/" RAM_ADDR_FMT
")",
3587 rb
->idstr
, start
, length
, rb
->used_length
);
3594 bool ramblock_is_pmem(RAMBlock
*rb
)
3596 return rb
->flags
& RAM_PMEM
;
3599 static void mtree_print_phys_entries(int start
, int end
, int skip
, int ptr
)
3601 if (start
== end
- 1) {
3602 qemu_printf("\t%3d ", start
);
3604 qemu_printf("\t%3d..%-3d ", start
, end
- 1);
3606 qemu_printf(" skip=%d ", skip
);
3607 if (ptr
== PHYS_MAP_NODE_NIL
) {
3608 qemu_printf(" ptr=NIL");
3610 qemu_printf(" ptr=#%d", ptr
);
3612 qemu_printf(" ptr=[%d]", ptr
);
3617 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3618 int128_sub((size), int128_one())) : 0)
3620 void mtree_print_dispatch(AddressSpaceDispatch
*d
, MemoryRegion
*root
)
3624 qemu_printf(" Dispatch\n");
3625 qemu_printf(" Physical sections\n");
3627 for (i
= 0; i
< d
->map
.sections_nb
; ++i
) {
3628 MemoryRegionSection
*s
= d
->map
.sections
+ i
;
3629 const char *names
[] = { " [unassigned]", " [not dirty]",
3630 " [ROM]", " [watch]" };
3632 qemu_printf(" #%d @" TARGET_FMT_plx
".." TARGET_FMT_plx
3635 s
->offset_within_address_space
,
3636 s
->offset_within_address_space
+ MR_SIZE(s
->mr
->size
),
3637 s
->mr
->name
? s
->mr
->name
: "(noname)",
3638 i
< ARRAY_SIZE(names
) ? names
[i
] : "",
3639 s
->mr
== root
? " [ROOT]" : "",
3640 s
== d
->mru_section
? " [MRU]" : "",
3641 s
->mr
->is_iommu
? " [iommu]" : "");
3644 qemu_printf(" alias=%s", s
->mr
->alias
->name
?
3645 s
->mr
->alias
->name
: "noname");
3650 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3651 P_L2_BITS
, P_L2_LEVELS
, d
->phys_map
.ptr
, d
->phys_map
.skip
);
3652 for (i
= 0; i
< d
->map
.nodes_nb
; ++i
) {
3655 Node
*n
= d
->map
.nodes
+ i
;
3657 qemu_printf(" [%d]\n", i
);
3659 for (j
= 0, jprev
= 0, prev
= *n
[0]; j
< ARRAY_SIZE(*n
); ++j
) {
3660 PhysPageEntry
*pe
= *n
+ j
;
3662 if (pe
->ptr
== prev
.ptr
&& pe
->skip
== prev
.skip
) {
3666 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3672 if (jprev
!= ARRAY_SIZE(*n
)) {
3673 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3679 * If positive, discarding RAM is disabled. If negative, discarding RAM is
3680 * required to work and cannot be disabled.
3682 static int ram_block_discard_disabled
;
3684 int ram_block_discard_disable(bool state
)
3689 qatomic_dec(&ram_block_discard_disabled
);
3694 old
= qatomic_read(&ram_block_discard_disabled
);
3698 } while (qatomic_cmpxchg(&ram_block_discard_disabled
,
3699 old
, old
+ 1) != old
);
3703 int ram_block_discard_require(bool state
)
3708 qatomic_inc(&ram_block_discard_disabled
);
3713 old
= qatomic_read(&ram_block_discard_disabled
);
3717 } while (qatomic_cmpxchg(&ram_block_discard_disabled
,
3718 old
, old
- 1) != old
);
3722 bool ram_block_discard_is_disabled(void)
3724 return qatomic_read(&ram_block_discard_disabled
) > 0;
3727 bool ram_block_discard_is_required(void)
3729 return qatomic_read(&ram_block_discard_disabled
) < 0;