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 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"
26 #include "exec/exec-all.h"
27 #include "exec/target_page.h"
29 #include "hw/qdev-core.h"
30 #include "hw/qdev-properties.h"
31 #include "hw/boards.h"
32 #include "hw/xen/xen.h"
33 #include "sysemu/kvm.h"
34 #include "sysemu/sysemu.h"
35 #include "sysemu/tcg.h"
36 #include "sysemu/qtest.h"
37 #include "qemu/timer.h"
38 #include "qemu/config-file.h"
39 #include "qemu/error-report.h"
40 #include "qemu/qemu-print.h"
41 #include "exec/memory.h"
42 #include "exec/ioport.h"
43 #include "sysemu/dma.h"
44 #include "sysemu/hostmem.h"
45 #include "sysemu/hw_accel.h"
46 #include "exec/address-spaces.h"
47 #include "sysemu/xen-mapcache.h"
48 #include "trace/trace-root.h"
50 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
51 #include <linux/falloc.h>
54 #include "qemu/rcu_queue.h"
55 #include "qemu/main-loop.h"
56 #include "translate-all.h"
57 #include "sysemu/replay.h"
59 #include "exec/memory-internal.h"
60 #include "exec/ram_addr.h"
63 #include "qemu/pmem.h"
65 #include "migration/vmstate.h"
67 #include "qemu/range.h"
69 #include "qemu/mmap-alloc.h"
72 #include "monitor/monitor.h"
74 #ifdef CONFIG_LIBDAXCTL
75 #include <daxctl/libdaxctl.h>
78 //#define DEBUG_SUBPAGE
80 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
81 * are protected by the ramlist lock.
83 RAMList ram_list
= { .blocks
= QLIST_HEAD_INITIALIZER(ram_list
.blocks
) };
85 static MemoryRegion
*system_memory
;
86 static MemoryRegion
*system_io
;
88 AddressSpace address_space_io
;
89 AddressSpace address_space_memory
;
91 static MemoryRegion io_mem_unassigned
;
93 typedef struct PhysPageEntry PhysPageEntry
;
95 struct PhysPageEntry
{
96 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
98 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
102 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
104 /* Size of the L2 (and L3, etc) page tables. */
105 #define ADDR_SPACE_BITS 64
108 #define P_L2_SIZE (1 << P_L2_BITS)
110 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
112 typedef PhysPageEntry Node
[P_L2_SIZE
];
114 typedef struct PhysPageMap
{
117 unsigned sections_nb
;
118 unsigned sections_nb_alloc
;
120 unsigned nodes_nb_alloc
;
122 MemoryRegionSection
*sections
;
125 struct AddressSpaceDispatch
{
126 MemoryRegionSection
*mru_section
;
127 /* This is a multi-level map on the physical address space.
128 * The bottom level has pointers to MemoryRegionSections.
130 PhysPageEntry phys_map
;
134 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
135 typedef struct subpage_t
{
139 uint16_t sub_section
[];
142 #define PHYS_SECTION_UNASSIGNED 0
144 static void io_mem_init(void);
145 static void memory_map_init(void);
146 static void tcg_log_global_after_sync(MemoryListener
*listener
);
147 static void tcg_commit(MemoryListener
*listener
);
150 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
151 * @cpu: the CPU whose AddressSpace this is
152 * @as: the AddressSpace itself
153 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
154 * @tcg_as_listener: listener for tracking changes to the AddressSpace
156 struct CPUAddressSpace
{
159 struct AddressSpaceDispatch
*memory_dispatch
;
160 MemoryListener tcg_as_listener
;
163 struct DirtyBitmapSnapshot
{
166 unsigned long dirty
[];
169 static void phys_map_node_reserve(PhysPageMap
*map
, unsigned nodes
)
171 static unsigned alloc_hint
= 16;
172 if (map
->nodes_nb
+ nodes
> map
->nodes_nb_alloc
) {
173 map
->nodes_nb_alloc
= MAX(alloc_hint
, map
->nodes_nb
+ nodes
);
174 map
->nodes
= g_renew(Node
, map
->nodes
, map
->nodes_nb_alloc
);
175 alloc_hint
= map
->nodes_nb_alloc
;
179 static uint32_t phys_map_node_alloc(PhysPageMap
*map
, bool leaf
)
186 ret
= map
->nodes_nb
++;
188 assert(ret
!= PHYS_MAP_NODE_NIL
);
189 assert(ret
!= map
->nodes_nb_alloc
);
191 e
.skip
= leaf
? 0 : 1;
192 e
.ptr
= leaf
? PHYS_SECTION_UNASSIGNED
: PHYS_MAP_NODE_NIL
;
193 for (i
= 0; i
< P_L2_SIZE
; ++i
) {
194 memcpy(&p
[i
], &e
, sizeof(e
));
199 static void phys_page_set_level(PhysPageMap
*map
, PhysPageEntry
*lp
,
200 hwaddr
*index
, uint64_t *nb
, uint16_t leaf
,
204 hwaddr step
= (hwaddr
)1 << (level
* P_L2_BITS
);
206 if (lp
->skip
&& lp
->ptr
== PHYS_MAP_NODE_NIL
) {
207 lp
->ptr
= phys_map_node_alloc(map
, level
== 0);
209 p
= map
->nodes
[lp
->ptr
];
210 lp
= &p
[(*index
>> (level
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
212 while (*nb
&& lp
< &p
[P_L2_SIZE
]) {
213 if ((*index
& (step
- 1)) == 0 && *nb
>= step
) {
219 phys_page_set_level(map
, lp
, index
, nb
, leaf
, level
- 1);
225 static void phys_page_set(AddressSpaceDispatch
*d
,
226 hwaddr index
, uint64_t nb
,
229 /* Wildly overreserve - it doesn't matter much. */
230 phys_map_node_reserve(&d
->map
, 3 * P_L2_LEVELS
);
232 phys_page_set_level(&d
->map
, &d
->phys_map
, &index
, &nb
, leaf
, P_L2_LEVELS
- 1);
235 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
236 * and update our entry so we can skip it and go directly to the destination.
238 static void phys_page_compact(PhysPageEntry
*lp
, Node
*nodes
)
240 unsigned valid_ptr
= P_L2_SIZE
;
245 if (lp
->ptr
== PHYS_MAP_NODE_NIL
) {
250 for (i
= 0; i
< P_L2_SIZE
; i
++) {
251 if (p
[i
].ptr
== PHYS_MAP_NODE_NIL
) {
258 phys_page_compact(&p
[i
], nodes
);
262 /* We can only compress if there's only one child. */
267 assert(valid_ptr
< P_L2_SIZE
);
269 /* Don't compress if it won't fit in the # of bits we have. */
270 if (P_L2_LEVELS
>= (1 << 6) &&
271 lp
->skip
+ p
[valid_ptr
].skip
>= (1 << 6)) {
275 lp
->ptr
= p
[valid_ptr
].ptr
;
276 if (!p
[valid_ptr
].skip
) {
277 /* If our only child is a leaf, make this a leaf. */
278 /* By design, we should have made this node a leaf to begin with so we
279 * should never reach here.
280 * But since it's so simple to handle this, let's do it just in case we
285 lp
->skip
+= p
[valid_ptr
].skip
;
289 void address_space_dispatch_compact(AddressSpaceDispatch
*d
)
291 if (d
->phys_map
.skip
) {
292 phys_page_compact(&d
->phys_map
, d
->map
.nodes
);
296 static inline bool section_covers_addr(const MemoryRegionSection
*section
,
299 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
300 * the section must cover the entire address space.
302 return int128_gethi(section
->size
) ||
303 range_covers_byte(section
->offset_within_address_space
,
304 int128_getlo(section
->size
), addr
);
307 static MemoryRegionSection
*phys_page_find(AddressSpaceDispatch
*d
, hwaddr addr
)
309 PhysPageEntry lp
= d
->phys_map
, *p
;
310 Node
*nodes
= d
->map
.nodes
;
311 MemoryRegionSection
*sections
= d
->map
.sections
;
312 hwaddr index
= addr
>> TARGET_PAGE_BITS
;
315 for (i
= P_L2_LEVELS
; lp
.skip
&& (i
-= lp
.skip
) >= 0;) {
316 if (lp
.ptr
== PHYS_MAP_NODE_NIL
) {
317 return §ions
[PHYS_SECTION_UNASSIGNED
];
320 lp
= p
[(index
>> (i
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
323 if (section_covers_addr(§ions
[lp
.ptr
], addr
)) {
324 return §ions
[lp
.ptr
];
326 return §ions
[PHYS_SECTION_UNASSIGNED
];
330 /* Called from RCU critical section */
331 static MemoryRegionSection
*address_space_lookup_region(AddressSpaceDispatch
*d
,
333 bool resolve_subpage
)
335 MemoryRegionSection
*section
= qatomic_read(&d
->mru_section
);
338 if (!section
|| section
== &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
] ||
339 !section_covers_addr(section
, addr
)) {
340 section
= phys_page_find(d
, addr
);
341 qatomic_set(&d
->mru_section
, section
);
343 if (resolve_subpage
&& section
->mr
->subpage
) {
344 subpage
= container_of(section
->mr
, subpage_t
, iomem
);
345 section
= &d
->map
.sections
[subpage
->sub_section
[SUBPAGE_IDX(addr
)]];
350 /* Called from RCU critical section */
351 static MemoryRegionSection
*
352 address_space_translate_internal(AddressSpaceDispatch
*d
, hwaddr addr
, hwaddr
*xlat
,
353 hwaddr
*plen
, bool resolve_subpage
)
355 MemoryRegionSection
*section
;
359 section
= address_space_lookup_region(d
, addr
, resolve_subpage
);
360 /* Compute offset within MemoryRegionSection */
361 addr
-= section
->offset_within_address_space
;
363 /* Compute offset within MemoryRegion */
364 *xlat
= addr
+ section
->offset_within_region
;
368 /* MMIO registers can be expected to perform full-width accesses based only
369 * on their address, without considering adjacent registers that could
370 * decode to completely different MemoryRegions. When such registers
371 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
372 * regions overlap wildly. For this reason we cannot clamp the accesses
375 * If the length is small (as is the case for address_space_ldl/stl),
376 * everything works fine. If the incoming length is large, however,
377 * the caller really has to do the clamping through memory_access_size.
379 if (memory_region_is_ram(mr
)) {
380 diff
= int128_sub(section
->size
, int128_make64(addr
));
381 *plen
= int128_get64(int128_min(diff
, int128_make64(*plen
)));
387 * address_space_translate_iommu - translate an address through an IOMMU
388 * memory region and then through the target address space.
390 * @iommu_mr: the IOMMU memory region that we start the translation from
391 * @addr: the address to be translated through the MMU
392 * @xlat: the translated address offset within the destination memory region.
393 * It cannot be %NULL.
394 * @plen_out: valid read/write length of the translated address. It
396 * @page_mask_out: page mask for the translated address. This
397 * should only be meaningful for IOMMU translated
398 * addresses, since there may be huge pages that this bit
399 * would tell. It can be %NULL if we don't care about it.
400 * @is_write: whether the translation operation is for write
401 * @is_mmio: whether this can be MMIO, set true if it can
402 * @target_as: the address space targeted by the IOMMU
403 * @attrs: transaction attributes
405 * This function is called from RCU critical section. It is the common
406 * part of flatview_do_translate and address_space_translate_cached.
408 static MemoryRegionSection
address_space_translate_iommu(IOMMUMemoryRegion
*iommu_mr
,
411 hwaddr
*page_mask_out
,
414 AddressSpace
**target_as
,
417 MemoryRegionSection
*section
;
418 hwaddr page_mask
= (hwaddr
)-1;
422 IOMMUMemoryRegionClass
*imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
426 if (imrc
->attrs_to_index
) {
427 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
430 iotlb
= imrc
->translate(iommu_mr
, addr
, is_write
?
431 IOMMU_WO
: IOMMU_RO
, iommu_idx
);
433 if (!(iotlb
.perm
& (1 << is_write
))) {
437 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
438 | (addr
& iotlb
.addr_mask
));
439 page_mask
&= iotlb
.addr_mask
;
440 *plen_out
= MIN(*plen_out
, (addr
| iotlb
.addr_mask
) - addr
+ 1);
441 *target_as
= iotlb
.target_as
;
443 section
= address_space_translate_internal(
444 address_space_to_dispatch(iotlb
.target_as
), addr
, xlat
,
447 iommu_mr
= memory_region_get_iommu(section
->mr
);
448 } while (unlikely(iommu_mr
));
451 *page_mask_out
= page_mask
;
456 return (MemoryRegionSection
) { .mr
= &io_mem_unassigned
};
460 * flatview_do_translate - translate an address in FlatView
462 * @fv: the flat view that we want to translate on
463 * @addr: the address to be translated in above address space
464 * @xlat: the translated address offset within memory region. It
466 * @plen_out: valid read/write length of the translated address. It
467 * can be @NULL when we don't care about it.
468 * @page_mask_out: page mask for the translated address. This
469 * should only be meaningful for IOMMU translated
470 * addresses, since there may be huge pages that this bit
471 * would tell. It can be @NULL if we don't care about it.
472 * @is_write: whether the translation operation is for write
473 * @is_mmio: whether this can be MMIO, set true if it can
474 * @target_as: the address space targeted by the IOMMU
475 * @attrs: memory transaction attributes
477 * This function is called from RCU critical section
479 static MemoryRegionSection
flatview_do_translate(FlatView
*fv
,
483 hwaddr
*page_mask_out
,
486 AddressSpace
**target_as
,
489 MemoryRegionSection
*section
;
490 IOMMUMemoryRegion
*iommu_mr
;
491 hwaddr plen
= (hwaddr
)(-1);
497 section
= address_space_translate_internal(
498 flatview_to_dispatch(fv
), addr
, xlat
,
501 iommu_mr
= memory_region_get_iommu(section
->mr
);
502 if (unlikely(iommu_mr
)) {
503 return address_space_translate_iommu(iommu_mr
, xlat
,
504 plen_out
, page_mask_out
,
509 /* Not behind an IOMMU, use default page size. */
510 *page_mask_out
= ~TARGET_PAGE_MASK
;
516 /* Called from RCU critical section */
517 IOMMUTLBEntry
address_space_get_iotlb_entry(AddressSpace
*as
, hwaddr addr
,
518 bool is_write
, MemTxAttrs attrs
)
520 MemoryRegionSection section
;
521 hwaddr xlat
, page_mask
;
524 * This can never be MMIO, and we don't really care about plen,
527 section
= flatview_do_translate(address_space_to_flatview(as
), addr
, &xlat
,
528 NULL
, &page_mask
, is_write
, false, &as
,
531 /* Illegal translation */
532 if (section
.mr
== &io_mem_unassigned
) {
536 /* Convert memory region offset into address space offset */
537 xlat
+= section
.offset_within_address_space
-
538 section
.offset_within_region
;
540 return (IOMMUTLBEntry
) {
542 .iova
= addr
& ~page_mask
,
543 .translated_addr
= xlat
& ~page_mask
,
544 .addr_mask
= page_mask
,
545 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
550 return (IOMMUTLBEntry
) {0};
553 /* Called from RCU critical section */
554 MemoryRegion
*flatview_translate(FlatView
*fv
, hwaddr addr
, hwaddr
*xlat
,
555 hwaddr
*plen
, bool is_write
,
559 MemoryRegionSection section
;
560 AddressSpace
*as
= NULL
;
562 /* This can be MMIO, so setup MMIO bit. */
563 section
= flatview_do_translate(fv
, addr
, xlat
, plen
, NULL
,
564 is_write
, true, &as
, attrs
);
567 if (xen_enabled() && memory_access_is_direct(mr
, is_write
)) {
568 hwaddr page
= ((addr
& TARGET_PAGE_MASK
) + TARGET_PAGE_SIZE
) - addr
;
569 *plen
= MIN(page
, *plen
);
575 typedef struct TCGIOMMUNotifier
{
583 static void tcg_iommu_unmap_notify(IOMMUNotifier
*n
, IOMMUTLBEntry
*iotlb
)
585 TCGIOMMUNotifier
*notifier
= container_of(n
, TCGIOMMUNotifier
, n
);
587 if (!notifier
->active
) {
590 tlb_flush(notifier
->cpu
);
591 notifier
->active
= false;
592 /* We leave the notifier struct on the list to avoid reallocating it later.
593 * Generally the number of IOMMUs a CPU deals with will be small.
594 * In any case we can't unregister the iommu notifier from a notify
599 static void tcg_register_iommu_notifier(CPUState
*cpu
,
600 IOMMUMemoryRegion
*iommu_mr
,
603 /* Make sure this CPU has an IOMMU notifier registered for this
604 * IOMMU/IOMMU index combination, so that we can flush its TLB
605 * when the IOMMU tells us the mappings we've cached have changed.
607 MemoryRegion
*mr
= MEMORY_REGION(iommu_mr
);
608 TCGIOMMUNotifier
*notifier
;
611 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
612 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
613 if (notifier
->mr
== mr
&& notifier
->iommu_idx
== iommu_idx
) {
617 if (i
== cpu
->iommu_notifiers
->len
) {
618 /* Not found, add a new entry at the end of the array */
619 cpu
->iommu_notifiers
= g_array_set_size(cpu
->iommu_notifiers
, i
+ 1);
620 notifier
= g_new0(TCGIOMMUNotifier
, 1);
621 g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
) = notifier
;
624 notifier
->iommu_idx
= iommu_idx
;
626 /* Rather than trying to register interest in the specific part
627 * of the iommu's address space that we've accessed and then
628 * expand it later as subsequent accesses touch more of it, we
629 * just register interest in the whole thing, on the assumption
630 * that iommu reconfiguration will be rare.
632 iommu_notifier_init(¬ifier
->n
,
633 tcg_iommu_unmap_notify
,
634 IOMMU_NOTIFIER_UNMAP
,
638 memory_region_register_iommu_notifier(notifier
->mr
, ¬ifier
->n
,
642 if (!notifier
->active
) {
643 notifier
->active
= true;
647 void tcg_iommu_free_notifier_list(CPUState
*cpu
)
649 /* Destroy the CPU's notifier list */
651 TCGIOMMUNotifier
*notifier
;
653 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
654 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
655 memory_region_unregister_iommu_notifier(notifier
->mr
, ¬ifier
->n
);
658 g_array_free(cpu
->iommu_notifiers
, true);
661 void tcg_iommu_init_notifier_list(CPUState
*cpu
)
663 cpu
->iommu_notifiers
= g_array_new(false, true, sizeof(TCGIOMMUNotifier
*));
666 /* Called from RCU critical section */
667 MemoryRegionSection
*
668 address_space_translate_for_iotlb(CPUState
*cpu
, int asidx
, hwaddr addr
,
669 hwaddr
*xlat
, hwaddr
*plen
,
670 MemTxAttrs attrs
, int *prot
)
672 MemoryRegionSection
*section
;
673 IOMMUMemoryRegion
*iommu_mr
;
674 IOMMUMemoryRegionClass
*imrc
;
677 AddressSpaceDispatch
*d
=
678 qatomic_rcu_read(&cpu
->cpu_ases
[asidx
].memory_dispatch
);
681 section
= address_space_translate_internal(d
, addr
, &addr
, plen
, false);
683 iommu_mr
= memory_region_get_iommu(section
->mr
);
688 imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
690 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
691 tcg_register_iommu_notifier(cpu
, iommu_mr
, iommu_idx
);
692 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
693 * doesn't short-cut its translation table walk.
695 iotlb
= imrc
->translate(iommu_mr
, addr
, IOMMU_NONE
, iommu_idx
);
696 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
697 | (addr
& iotlb
.addr_mask
));
698 /* Update the caller's prot bits to remove permissions the IOMMU
699 * is giving us a failure response for. If we get down to no
700 * permissions left at all we can give up now.
702 if (!(iotlb
.perm
& IOMMU_RO
)) {
703 *prot
&= ~(PAGE_READ
| PAGE_EXEC
);
705 if (!(iotlb
.perm
& IOMMU_WO
)) {
706 *prot
&= ~PAGE_WRITE
;
713 d
= flatview_to_dispatch(address_space_to_flatview(iotlb
.target_as
));
716 assert(!memory_region_is_iommu(section
->mr
));
721 return &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
];
724 void cpu_address_space_init(CPUState
*cpu
, int asidx
,
725 const char *prefix
, MemoryRegion
*mr
)
727 CPUAddressSpace
*newas
;
728 AddressSpace
*as
= g_new0(AddressSpace
, 1);
732 as_name
= g_strdup_printf("%s-%d", prefix
, cpu
->cpu_index
);
733 address_space_init(as
, mr
, as_name
);
736 /* Target code should have set num_ases before calling us */
737 assert(asidx
< cpu
->num_ases
);
740 /* address space 0 gets the convenience alias */
744 /* KVM cannot currently support multiple address spaces. */
745 assert(asidx
== 0 || !kvm_enabled());
747 if (!cpu
->cpu_ases
) {
748 cpu
->cpu_ases
= g_new0(CPUAddressSpace
, cpu
->num_ases
);
751 newas
= &cpu
->cpu_ases
[asidx
];
755 newas
->tcg_as_listener
.log_global_after_sync
= tcg_log_global_after_sync
;
756 newas
->tcg_as_listener
.commit
= tcg_commit
;
757 memory_listener_register(&newas
->tcg_as_listener
, as
);
761 AddressSpace
*cpu_get_address_space(CPUState
*cpu
, int asidx
)
763 /* Return the AddressSpace corresponding to the specified index */
764 return cpu
->cpu_ases
[asidx
].as
;
767 /* Add a watchpoint. */
768 int cpu_watchpoint_insert(CPUState
*cpu
, vaddr addr
, vaddr len
,
769 int flags
, CPUWatchpoint
**watchpoint
)
774 /* forbid ranges which are empty or run off the end of the address space */
775 if (len
== 0 || (addr
+ len
- 1) < addr
) {
776 error_report("tried to set invalid watchpoint at %"
777 VADDR_PRIx
", len=%" VADDR_PRIu
, addr
, len
);
780 wp
= g_malloc(sizeof(*wp
));
786 /* keep all GDB-injected watchpoints in front */
787 if (flags
& BP_GDB
) {
788 QTAILQ_INSERT_HEAD(&cpu
->watchpoints
, wp
, entry
);
790 QTAILQ_INSERT_TAIL(&cpu
->watchpoints
, wp
, entry
);
793 in_page
= -(addr
| TARGET_PAGE_MASK
);
794 if (len
<= in_page
) {
795 tlb_flush_page(cpu
, addr
);
805 /* Remove a specific watchpoint. */
806 int cpu_watchpoint_remove(CPUState
*cpu
, vaddr addr
, vaddr len
,
811 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
812 if (addr
== wp
->vaddr
&& len
== wp
->len
813 && flags
== (wp
->flags
& ~BP_WATCHPOINT_HIT
)) {
814 cpu_watchpoint_remove_by_ref(cpu
, wp
);
821 /* Remove a specific watchpoint by reference. */
822 void cpu_watchpoint_remove_by_ref(CPUState
*cpu
, CPUWatchpoint
*watchpoint
)
824 QTAILQ_REMOVE(&cpu
->watchpoints
, watchpoint
, entry
);
826 tlb_flush_page(cpu
, watchpoint
->vaddr
);
831 /* Remove all matching watchpoints. */
832 void cpu_watchpoint_remove_all(CPUState
*cpu
, int mask
)
834 CPUWatchpoint
*wp
, *next
;
836 QTAILQ_FOREACH_SAFE(wp
, &cpu
->watchpoints
, entry
, next
) {
837 if (wp
->flags
& mask
) {
838 cpu_watchpoint_remove_by_ref(cpu
, wp
);
843 /* Return true if this watchpoint address matches the specified
844 * access (ie the address range covered by the watchpoint overlaps
845 * partially or completely with the address range covered by the
848 static inline bool watchpoint_address_matches(CPUWatchpoint
*wp
,
849 vaddr addr
, vaddr len
)
851 /* We know the lengths are non-zero, but a little caution is
852 * required to avoid errors in the case where the range ends
853 * exactly at the top of the address space and so addr + len
854 * wraps round to zero.
856 vaddr wpend
= wp
->vaddr
+ wp
->len
- 1;
857 vaddr addrend
= addr
+ len
- 1;
859 return !(addr
> wpend
|| wp
->vaddr
> addrend
);
862 /* Return flags for watchpoints that match addr + prot. */
863 int cpu_watchpoint_address_matches(CPUState
*cpu
, vaddr addr
, vaddr len
)
868 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
869 if (watchpoint_address_matches(wp
, addr
, len
)) {
876 /* Called from RCU critical section */
877 static RAMBlock
*qemu_get_ram_block(ram_addr_t addr
)
881 block
= qatomic_rcu_read(&ram_list
.mru_block
);
882 if (block
&& addr
- block
->offset
< block
->max_length
) {
885 RAMBLOCK_FOREACH(block
) {
886 if (addr
- block
->offset
< block
->max_length
) {
891 fprintf(stderr
, "Bad ram offset %" PRIx64
"\n", (uint64_t)addr
);
895 /* It is safe to write mru_block outside the iothread lock. This
900 * xxx removed from list
904 * call_rcu(reclaim_ramblock, xxx);
907 * qatomic_rcu_set is not needed here. The block was already published
908 * when it was placed into the list. Here we're just making an extra
909 * copy of the pointer.
911 ram_list
.mru_block
= block
;
915 static void tlb_reset_dirty_range_all(ram_addr_t start
, ram_addr_t length
)
922 assert(tcg_enabled());
923 end
= TARGET_PAGE_ALIGN(start
+ length
);
924 start
&= TARGET_PAGE_MASK
;
926 RCU_READ_LOCK_GUARD();
927 block
= qemu_get_ram_block(start
);
928 assert(block
== qemu_get_ram_block(end
- 1));
929 start1
= (uintptr_t)ramblock_ptr(block
, start
- block
->offset
);
931 tlb_reset_dirty(cpu
, start1
, length
);
935 /* Note: start and end must be within the same ram block. */
936 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start
,
940 DirtyMemoryBlocks
*blocks
;
941 unsigned long end
, page
, start_page
;
944 uint64_t mr_offset
, mr_size
;
950 end
= TARGET_PAGE_ALIGN(start
+ length
) >> TARGET_PAGE_BITS
;
951 start_page
= start
>> TARGET_PAGE_BITS
;
954 WITH_RCU_READ_LOCK_GUARD() {
955 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
956 ramblock
= qemu_get_ram_block(start
);
957 /* Range sanity check on the ramblock */
958 assert(start
>= ramblock
->offset
&&
959 start
+ length
<= ramblock
->offset
+ ramblock
->used_length
);
962 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
963 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
964 unsigned long num
= MIN(end
- page
,
965 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
967 dirty
|= bitmap_test_and_clear_atomic(blocks
->blocks
[idx
],
972 mr_offset
= (ram_addr_t
)(start_page
<< TARGET_PAGE_BITS
) - ramblock
->offset
;
973 mr_size
= (end
- start_page
) << TARGET_PAGE_BITS
;
974 memory_region_clear_dirty_bitmap(ramblock
->mr
, mr_offset
, mr_size
);
977 if (dirty
&& tcg_enabled()) {
978 tlb_reset_dirty_range_all(start
, length
);
984 DirtyBitmapSnapshot
*cpu_physical_memory_snapshot_and_clear_dirty
985 (MemoryRegion
*mr
, hwaddr offset
, hwaddr length
, unsigned client
)
987 DirtyMemoryBlocks
*blocks
;
988 ram_addr_t start
= memory_region_get_ram_addr(mr
) + offset
;
989 unsigned long align
= 1UL << (TARGET_PAGE_BITS
+ BITS_PER_LEVEL
);
990 ram_addr_t first
= QEMU_ALIGN_DOWN(start
, align
);
991 ram_addr_t last
= QEMU_ALIGN_UP(start
+ length
, align
);
992 DirtyBitmapSnapshot
*snap
;
993 unsigned long page
, end
, dest
;
995 snap
= g_malloc0(sizeof(*snap
) +
996 ((last
- first
) >> (TARGET_PAGE_BITS
+ 3)));
1000 page
= first
>> TARGET_PAGE_BITS
;
1001 end
= last
>> TARGET_PAGE_BITS
;
1004 WITH_RCU_READ_LOCK_GUARD() {
1005 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1007 while (page
< end
) {
1008 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1009 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1010 unsigned long num
= MIN(end
- page
,
1011 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1013 assert(QEMU_IS_ALIGNED(offset
, (1 << BITS_PER_LEVEL
)));
1014 assert(QEMU_IS_ALIGNED(num
, (1 << BITS_PER_LEVEL
)));
1015 offset
>>= BITS_PER_LEVEL
;
1017 bitmap_copy_and_clear_atomic(snap
->dirty
+ dest
,
1018 blocks
->blocks
[idx
] + offset
,
1021 dest
+= num
>> BITS_PER_LEVEL
;
1025 if (tcg_enabled()) {
1026 tlb_reset_dirty_range_all(start
, length
);
1029 memory_region_clear_dirty_bitmap(mr
, offset
, length
);
1034 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot
*snap
,
1038 unsigned long page
, end
;
1040 assert(start
>= snap
->start
);
1041 assert(start
+ length
<= snap
->end
);
1043 end
= TARGET_PAGE_ALIGN(start
+ length
- snap
->start
) >> TARGET_PAGE_BITS
;
1044 page
= (start
- snap
->start
) >> TARGET_PAGE_BITS
;
1046 while (page
< end
) {
1047 if (test_bit(page
, snap
->dirty
)) {
1055 /* Called from RCU critical section */
1056 hwaddr
memory_region_section_get_iotlb(CPUState
*cpu
,
1057 MemoryRegionSection
*section
)
1059 AddressSpaceDispatch
*d
= flatview_to_dispatch(section
->fv
);
1060 return section
- d
->map
.sections
;
1063 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
1065 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
);
1067 static void *(*phys_mem_alloc
)(size_t size
, uint64_t *align
, bool shared
) =
1068 qemu_anon_ram_alloc
;
1071 * Set a custom physical guest memory alloator.
1072 * Accelerators with unusual needs may need this. Hopefully, we can
1073 * get rid of it eventually.
1075 void phys_mem_set_alloc(void *(*alloc
)(size_t, uint64_t *align
, bool shared
))
1077 phys_mem_alloc
= alloc
;
1080 static uint16_t phys_section_add(PhysPageMap
*map
,
1081 MemoryRegionSection
*section
)
1083 /* The physical section number is ORed with a page-aligned
1084 * pointer to produce the iotlb entries. Thus it should
1085 * never overflow into the page-aligned value.
1087 assert(map
->sections_nb
< TARGET_PAGE_SIZE
);
1089 if (map
->sections_nb
== map
->sections_nb_alloc
) {
1090 map
->sections_nb_alloc
= MAX(map
->sections_nb_alloc
* 2, 16);
1091 map
->sections
= g_renew(MemoryRegionSection
, map
->sections
,
1092 map
->sections_nb_alloc
);
1094 map
->sections
[map
->sections_nb
] = *section
;
1095 memory_region_ref(section
->mr
);
1096 return map
->sections_nb
++;
1099 static void phys_section_destroy(MemoryRegion
*mr
)
1101 bool have_sub_page
= mr
->subpage
;
1103 memory_region_unref(mr
);
1105 if (have_sub_page
) {
1106 subpage_t
*subpage
= container_of(mr
, subpage_t
, iomem
);
1107 object_unref(OBJECT(&subpage
->iomem
));
1112 static void phys_sections_free(PhysPageMap
*map
)
1114 while (map
->sections_nb
> 0) {
1115 MemoryRegionSection
*section
= &map
->sections
[--map
->sections_nb
];
1116 phys_section_destroy(section
->mr
);
1118 g_free(map
->sections
);
1122 static void register_subpage(FlatView
*fv
, MemoryRegionSection
*section
)
1124 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1126 hwaddr base
= section
->offset_within_address_space
1128 MemoryRegionSection
*existing
= phys_page_find(d
, base
);
1129 MemoryRegionSection subsection
= {
1130 .offset_within_address_space
= base
,
1131 .size
= int128_make64(TARGET_PAGE_SIZE
),
1135 assert(existing
->mr
->subpage
|| existing
->mr
== &io_mem_unassigned
);
1137 if (!(existing
->mr
->subpage
)) {
1138 subpage
= subpage_init(fv
, base
);
1140 subsection
.mr
= &subpage
->iomem
;
1141 phys_page_set(d
, base
>> TARGET_PAGE_BITS
, 1,
1142 phys_section_add(&d
->map
, &subsection
));
1144 subpage
= container_of(existing
->mr
, subpage_t
, iomem
);
1146 start
= section
->offset_within_address_space
& ~TARGET_PAGE_MASK
;
1147 end
= start
+ int128_get64(section
->size
) - 1;
1148 subpage_register(subpage
, start
, end
,
1149 phys_section_add(&d
->map
, section
));
1153 static void register_multipage(FlatView
*fv
,
1154 MemoryRegionSection
*section
)
1156 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1157 hwaddr start_addr
= section
->offset_within_address_space
;
1158 uint16_t section_index
= phys_section_add(&d
->map
, section
);
1159 uint64_t num_pages
= int128_get64(int128_rshift(section
->size
,
1163 phys_page_set(d
, start_addr
>> TARGET_PAGE_BITS
, num_pages
, section_index
);
1167 * The range in *section* may look like this:
1171 * where s stands for subpage and P for page.
1173 void flatview_add_to_dispatch(FlatView
*fv
, MemoryRegionSection
*section
)
1175 MemoryRegionSection remain
= *section
;
1176 Int128 page_size
= int128_make64(TARGET_PAGE_SIZE
);
1178 /* register first subpage */
1179 if (remain
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1180 uint64_t left
= TARGET_PAGE_ALIGN(remain
.offset_within_address_space
)
1181 - remain
.offset_within_address_space
;
1183 MemoryRegionSection now
= remain
;
1184 now
.size
= int128_min(int128_make64(left
), now
.size
);
1185 register_subpage(fv
, &now
);
1186 if (int128_eq(remain
.size
, now
.size
)) {
1189 remain
.size
= int128_sub(remain
.size
, now
.size
);
1190 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1191 remain
.offset_within_region
+= int128_get64(now
.size
);
1194 /* register whole pages */
1195 if (int128_ge(remain
.size
, page_size
)) {
1196 MemoryRegionSection now
= remain
;
1197 now
.size
= int128_and(now
.size
, int128_neg(page_size
));
1198 register_multipage(fv
, &now
);
1199 if (int128_eq(remain
.size
, now
.size
)) {
1202 remain
.size
= int128_sub(remain
.size
, now
.size
);
1203 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1204 remain
.offset_within_region
+= int128_get64(now
.size
);
1207 /* register last subpage */
1208 register_subpage(fv
, &remain
);
1211 void qemu_flush_coalesced_mmio_buffer(void)
1214 kvm_flush_coalesced_mmio_buffer();
1217 void qemu_mutex_lock_ramlist(void)
1219 qemu_mutex_lock(&ram_list
.mutex
);
1222 void qemu_mutex_unlock_ramlist(void)
1224 qemu_mutex_unlock(&ram_list
.mutex
);
1227 void ram_block_dump(Monitor
*mon
)
1232 RCU_READ_LOCK_GUARD();
1233 monitor_printf(mon
, "%24s %8s %18s %18s %18s\n",
1234 "Block Name", "PSize", "Offset", "Used", "Total");
1235 RAMBLOCK_FOREACH(block
) {
1236 psize
= size_to_str(block
->page_size
);
1237 monitor_printf(mon
, "%24s %8s 0x%016" PRIx64
" 0x%016" PRIx64
1238 " 0x%016" PRIx64
"\n", block
->idstr
, psize
,
1239 (uint64_t)block
->offset
,
1240 (uint64_t)block
->used_length
,
1241 (uint64_t)block
->max_length
);
1248 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1249 * may or may not name the same files / on the same filesystem now as
1250 * when we actually open and map them. Iterate over the file
1251 * descriptors instead, and use qemu_fd_getpagesize().
1253 static int find_min_backend_pagesize(Object
*obj
, void *opaque
)
1255 long *hpsize_min
= opaque
;
1257 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1258 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1259 long hpsize
= host_memory_backend_pagesize(backend
);
1261 if (host_memory_backend_is_mapped(backend
) && (hpsize
< *hpsize_min
)) {
1262 *hpsize_min
= hpsize
;
1269 static int find_max_backend_pagesize(Object
*obj
, void *opaque
)
1271 long *hpsize_max
= opaque
;
1273 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1274 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1275 long hpsize
= host_memory_backend_pagesize(backend
);
1277 if (host_memory_backend_is_mapped(backend
) && (hpsize
> *hpsize_max
)) {
1278 *hpsize_max
= hpsize
;
1286 * TODO: We assume right now that all mapped host memory backends are
1287 * used as RAM, however some might be used for different purposes.
1289 long qemu_minrampagesize(void)
1291 long hpsize
= LONG_MAX
;
1292 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1294 object_child_foreach(memdev_root
, find_min_backend_pagesize
, &hpsize
);
1298 long qemu_maxrampagesize(void)
1301 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1303 object_child_foreach(memdev_root
, find_max_backend_pagesize
, &pagesize
);
1307 long qemu_minrampagesize(void)
1309 return qemu_real_host_page_size
;
1311 long qemu_maxrampagesize(void)
1313 return qemu_real_host_page_size
;
1318 static int64_t get_file_size(int fd
)
1321 #if defined(__linux__)
1324 if (fstat(fd
, &st
) < 0) {
1328 /* Special handling for devdax character devices */
1329 if (S_ISCHR(st
.st_mode
)) {
1330 g_autofree
char *subsystem_path
= NULL
;
1331 g_autofree
char *subsystem
= NULL
;
1333 subsystem_path
= g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1334 major(st
.st_rdev
), minor(st
.st_rdev
));
1335 subsystem
= g_file_read_link(subsystem_path
, NULL
);
1337 if (subsystem
&& g_str_has_suffix(subsystem
, "/dax")) {
1338 g_autofree
char *size_path
= NULL
;
1339 g_autofree
char *size_str
= NULL
;
1341 size_path
= g_strdup_printf("/sys/dev/char/%d:%d/size",
1342 major(st
.st_rdev
), minor(st
.st_rdev
));
1344 if (g_file_get_contents(size_path
, &size_str
, NULL
, NULL
)) {
1345 return g_ascii_strtoll(size_str
, NULL
, 0);
1349 #endif /* defined(__linux__) */
1351 /* st.st_size may be zero for special files yet lseek(2) works */
1352 size
= lseek(fd
, 0, SEEK_END
);
1359 static int64_t get_file_align(int fd
)
1362 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1365 if (fstat(fd
, &st
) < 0) {
1369 /* Special handling for devdax character devices */
1370 if (S_ISCHR(st
.st_mode
)) {
1371 g_autofree
char *path
= NULL
;
1372 g_autofree
char *rpath
= NULL
;
1373 struct daxctl_ctx
*ctx
;
1374 struct daxctl_region
*region
;
1377 path
= g_strdup_printf("/sys/dev/char/%d:%d",
1378 major(st
.st_rdev
), minor(st
.st_rdev
));
1379 rpath
= realpath(path
, NULL
);
1381 rc
= daxctl_new(&ctx
);
1386 daxctl_region_foreach(ctx
, region
) {
1387 if (strstr(rpath
, daxctl_region_get_path(region
))) {
1388 align
= daxctl_region_get_align(region
);
1394 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1399 static int file_ram_open(const char *path
,
1400 const char *region_name
,
1405 char *sanitized_name
;
1411 fd
= open(path
, O_RDWR
);
1413 /* @path names an existing file, use it */
1416 if (errno
== ENOENT
) {
1417 /* @path names a file that doesn't exist, create it */
1418 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0644);
1423 } else if (errno
== EISDIR
) {
1424 /* @path names a directory, create a file there */
1425 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1426 sanitized_name
= g_strdup(region_name
);
1427 for (c
= sanitized_name
; *c
!= '\0'; c
++) {
1433 filename
= g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path
,
1435 g_free(sanitized_name
);
1437 fd
= mkstemp(filename
);
1445 if (errno
!= EEXIST
&& errno
!= EINTR
) {
1446 error_setg_errno(errp
, errno
,
1447 "can't open backing store %s for guest RAM",
1452 * Try again on EINTR and EEXIST. The latter happens when
1453 * something else creates the file between our two open().
1460 static void *file_ram_alloc(RAMBlock
*block
,
1468 block
->page_size
= qemu_fd_getpagesize(fd
);
1469 if (block
->mr
->align
% block
->page_size
) {
1470 error_setg(errp
, "alignment 0x%" PRIx64
1471 " must be multiples of page size 0x%zx",
1472 block
->mr
->align
, block
->page_size
);
1474 } else if (block
->mr
->align
&& !is_power_of_2(block
->mr
->align
)) {
1475 error_setg(errp
, "alignment 0x%" PRIx64
1476 " must be a power of two", block
->mr
->align
);
1479 block
->mr
->align
= MAX(block
->page_size
, block
->mr
->align
);
1480 #if defined(__s390x__)
1481 if (kvm_enabled()) {
1482 block
->mr
->align
= MAX(block
->mr
->align
, QEMU_VMALLOC_ALIGN
);
1486 if (memory
< block
->page_size
) {
1487 error_setg(errp
, "memory size 0x" RAM_ADDR_FMT
" must be equal to "
1488 "or larger than page size 0x%zx",
1489 memory
, block
->page_size
);
1493 memory
= ROUND_UP(memory
, block
->page_size
);
1496 * ftruncate is not supported by hugetlbfs in older
1497 * hosts, so don't bother bailing out on errors.
1498 * If anything goes wrong with it under other filesystems,
1501 * Do not truncate the non-empty backend file to avoid corrupting
1502 * the existing data in the file. Disabling shrinking is not
1503 * enough. For example, the current vNVDIMM implementation stores
1504 * the guest NVDIMM labels at the end of the backend file. If the
1505 * backend file is later extended, QEMU will not be able to find
1506 * those labels. Therefore, extending the non-empty backend file
1507 * is disabled as well.
1509 if (truncate
&& ftruncate(fd
, memory
)) {
1510 perror("ftruncate");
1513 area
= qemu_ram_mmap(fd
, memory
, block
->mr
->align
,
1514 block
->flags
& RAM_SHARED
, block
->flags
& RAM_PMEM
);
1515 if (area
== MAP_FAILED
) {
1516 error_setg_errno(errp
, errno
,
1517 "unable to map backing store for guest RAM");
1526 /* Allocate space within the ram_addr_t space that governs the
1528 * Called with the ramlist lock held.
1530 static ram_addr_t
find_ram_offset(ram_addr_t size
)
1532 RAMBlock
*block
, *next_block
;
1533 ram_addr_t offset
= RAM_ADDR_MAX
, mingap
= RAM_ADDR_MAX
;
1535 assert(size
!= 0); /* it would hand out same offset multiple times */
1537 if (QLIST_EMPTY_RCU(&ram_list
.blocks
)) {
1541 RAMBLOCK_FOREACH(block
) {
1542 ram_addr_t candidate
, next
= RAM_ADDR_MAX
;
1544 /* Align blocks to start on a 'long' in the bitmap
1545 * which makes the bitmap sync'ing take the fast path.
1547 candidate
= block
->offset
+ block
->max_length
;
1548 candidate
= ROUND_UP(candidate
, BITS_PER_LONG
<< TARGET_PAGE_BITS
);
1550 /* Search for the closest following block
1553 RAMBLOCK_FOREACH(next_block
) {
1554 if (next_block
->offset
>= candidate
) {
1555 next
= MIN(next
, next_block
->offset
);
1559 /* If it fits remember our place and remember the size
1560 * of gap, but keep going so that we might find a smaller
1561 * gap to fill so avoiding fragmentation.
1563 if (next
- candidate
>= size
&& next
- candidate
< mingap
) {
1565 mingap
= next
- candidate
;
1568 trace_find_ram_offset_loop(size
, candidate
, offset
, next
, mingap
);
1571 if (offset
== RAM_ADDR_MAX
) {
1572 fprintf(stderr
, "Failed to find gap of requested size: %" PRIu64
"\n",
1577 trace_find_ram_offset(size
, offset
);
1582 static unsigned long last_ram_page(void)
1585 ram_addr_t last
= 0;
1587 RCU_READ_LOCK_GUARD();
1588 RAMBLOCK_FOREACH(block
) {
1589 last
= MAX(last
, block
->offset
+ block
->max_length
);
1591 return last
>> TARGET_PAGE_BITS
;
1594 static void qemu_ram_setup_dump(void *addr
, ram_addr_t size
)
1598 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1599 if (!machine_dump_guest_core(current_machine
)) {
1600 ret
= qemu_madvise(addr
, size
, QEMU_MADV_DONTDUMP
);
1602 perror("qemu_madvise");
1603 fprintf(stderr
, "madvise doesn't support MADV_DONTDUMP, "
1604 "but dump_guest_core=off specified\n");
1609 const char *qemu_ram_get_idstr(RAMBlock
*rb
)
1614 void *qemu_ram_get_host_addr(RAMBlock
*rb
)
1619 ram_addr_t
qemu_ram_get_offset(RAMBlock
*rb
)
1624 ram_addr_t
qemu_ram_get_used_length(RAMBlock
*rb
)
1626 return rb
->used_length
;
1629 bool qemu_ram_is_shared(RAMBlock
*rb
)
1631 return rb
->flags
& RAM_SHARED
;
1634 /* Note: Only set at the start of postcopy */
1635 bool qemu_ram_is_uf_zeroable(RAMBlock
*rb
)
1637 return rb
->flags
& RAM_UF_ZEROPAGE
;
1640 void qemu_ram_set_uf_zeroable(RAMBlock
*rb
)
1642 rb
->flags
|= RAM_UF_ZEROPAGE
;
1645 bool qemu_ram_is_migratable(RAMBlock
*rb
)
1647 return rb
->flags
& RAM_MIGRATABLE
;
1650 void qemu_ram_set_migratable(RAMBlock
*rb
)
1652 rb
->flags
|= RAM_MIGRATABLE
;
1655 void qemu_ram_unset_migratable(RAMBlock
*rb
)
1657 rb
->flags
&= ~RAM_MIGRATABLE
;
1660 /* Called with iothread lock held. */
1661 void qemu_ram_set_idstr(RAMBlock
*new_block
, const char *name
, DeviceState
*dev
)
1666 assert(!new_block
->idstr
[0]);
1669 char *id
= qdev_get_dev_path(dev
);
1671 snprintf(new_block
->idstr
, sizeof(new_block
->idstr
), "%s/", id
);
1675 pstrcat(new_block
->idstr
, sizeof(new_block
->idstr
), name
);
1677 RCU_READ_LOCK_GUARD();
1678 RAMBLOCK_FOREACH(block
) {
1679 if (block
!= new_block
&&
1680 !strcmp(block
->idstr
, new_block
->idstr
)) {
1681 fprintf(stderr
, "RAMBlock \"%s\" already registered, abort!\n",
1688 /* Called with iothread lock held. */
1689 void qemu_ram_unset_idstr(RAMBlock
*block
)
1691 /* FIXME: arch_init.c assumes that this is not called throughout
1692 * migration. Ignore the problem since hot-unplug during migration
1693 * does not work anyway.
1696 memset(block
->idstr
, 0, sizeof(block
->idstr
));
1700 size_t qemu_ram_pagesize(RAMBlock
*rb
)
1702 return rb
->page_size
;
1705 /* Returns the largest size of page in use */
1706 size_t qemu_ram_pagesize_largest(void)
1711 RAMBLOCK_FOREACH(block
) {
1712 largest
= MAX(largest
, qemu_ram_pagesize(block
));
1718 static int memory_try_enable_merging(void *addr
, size_t len
)
1720 if (!machine_mem_merge(current_machine
)) {
1721 /* disabled by the user */
1725 return qemu_madvise(addr
, len
, QEMU_MADV_MERGEABLE
);
1728 /* Only legal before guest might have detected the memory size: e.g. on
1729 * incoming migration, or right after reset.
1731 * As memory core doesn't know how is memory accessed, it is up to
1732 * resize callback to update device state and/or add assertions to detect
1733 * misuse, if necessary.
1735 int qemu_ram_resize(RAMBlock
*block
, ram_addr_t newsize
, Error
**errp
)
1737 const ram_addr_t unaligned_size
= newsize
;
1741 newsize
= HOST_PAGE_ALIGN(newsize
);
1743 if (block
->used_length
== newsize
) {
1745 * We don't have to resize the ram block (which only knows aligned
1746 * sizes), however, we have to notify if the unaligned size changed.
1748 if (unaligned_size
!= memory_region_size(block
->mr
)) {
1749 memory_region_set_size(block
->mr
, unaligned_size
);
1750 if (block
->resized
) {
1751 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1757 if (!(block
->flags
& RAM_RESIZEABLE
)) {
1758 error_setg_errno(errp
, EINVAL
,
1759 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1760 " in != 0x" RAM_ADDR_FMT
, block
->idstr
,
1761 newsize
, block
->used_length
);
1765 if (block
->max_length
< newsize
) {
1766 error_setg_errno(errp
, EINVAL
,
1767 "Length too large: %s: 0x" RAM_ADDR_FMT
1768 " > 0x" RAM_ADDR_FMT
, block
->idstr
,
1769 newsize
, block
->max_length
);
1773 cpu_physical_memory_clear_dirty_range(block
->offset
, block
->used_length
);
1774 block
->used_length
= newsize
;
1775 cpu_physical_memory_set_dirty_range(block
->offset
, block
->used_length
,
1777 memory_region_set_size(block
->mr
, unaligned_size
);
1778 if (block
->resized
) {
1779 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1785 * Trigger sync on the given ram block for range [start, start + length]
1786 * with the backing store if one is available.
1788 * @Note: this is supposed to be a synchronous op.
1790 void qemu_ram_msync(RAMBlock
*block
, ram_addr_t start
, ram_addr_t length
)
1792 /* The requested range should fit in within the block range */
1793 g_assert((start
+ length
) <= block
->used_length
);
1795 #ifdef CONFIG_LIBPMEM
1796 /* The lack of support for pmem should not block the sync */
1797 if (ramblock_is_pmem(block
)) {
1798 void *addr
= ramblock_ptr(block
, start
);
1799 pmem_persist(addr
, length
);
1803 if (block
->fd
>= 0) {
1805 * Case there is no support for PMEM or the memory has not been
1806 * specified as persistent (or is not one) - use the msync.
1807 * Less optimal but still achieves the same goal
1809 void *addr
= ramblock_ptr(block
, start
);
1810 if (qemu_msync(addr
, length
, block
->fd
)) {
1811 warn_report("%s: failed to sync memory range: start: "
1812 RAM_ADDR_FMT
" length: " RAM_ADDR_FMT
,
1813 __func__
, start
, length
);
1818 /* Called with ram_list.mutex held */
1819 static void dirty_memory_extend(ram_addr_t old_ram_size
,
1820 ram_addr_t new_ram_size
)
1822 ram_addr_t old_num_blocks
= DIV_ROUND_UP(old_ram_size
,
1823 DIRTY_MEMORY_BLOCK_SIZE
);
1824 ram_addr_t new_num_blocks
= DIV_ROUND_UP(new_ram_size
,
1825 DIRTY_MEMORY_BLOCK_SIZE
);
1828 /* Only need to extend if block count increased */
1829 if (new_num_blocks
<= old_num_blocks
) {
1833 for (i
= 0; i
< DIRTY_MEMORY_NUM
; i
++) {
1834 DirtyMemoryBlocks
*old_blocks
;
1835 DirtyMemoryBlocks
*new_blocks
;
1838 old_blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[i
]);
1839 new_blocks
= g_malloc(sizeof(*new_blocks
) +
1840 sizeof(new_blocks
->blocks
[0]) * new_num_blocks
);
1842 if (old_num_blocks
) {
1843 memcpy(new_blocks
->blocks
, old_blocks
->blocks
,
1844 old_num_blocks
* sizeof(old_blocks
->blocks
[0]));
1847 for (j
= old_num_blocks
; j
< new_num_blocks
; j
++) {
1848 new_blocks
->blocks
[j
] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE
);
1851 qatomic_rcu_set(&ram_list
.dirty_memory
[i
], new_blocks
);
1854 g_free_rcu(old_blocks
, rcu
);
1859 static void ram_block_add(RAMBlock
*new_block
, Error
**errp
, bool shared
)
1862 RAMBlock
*last_block
= NULL
;
1863 ram_addr_t old_ram_size
, new_ram_size
;
1866 old_ram_size
= last_ram_page();
1868 qemu_mutex_lock_ramlist();
1869 new_block
->offset
= find_ram_offset(new_block
->max_length
);
1871 if (!new_block
->host
) {
1872 if (xen_enabled()) {
1873 xen_ram_alloc(new_block
->offset
, new_block
->max_length
,
1874 new_block
->mr
, &err
);
1876 error_propagate(errp
, err
);
1877 qemu_mutex_unlock_ramlist();
1881 new_block
->host
= phys_mem_alloc(new_block
->max_length
,
1882 &new_block
->mr
->align
, shared
);
1883 if (!new_block
->host
) {
1884 error_setg_errno(errp
, errno
,
1885 "cannot set up guest memory '%s'",
1886 memory_region_name(new_block
->mr
));
1887 qemu_mutex_unlock_ramlist();
1890 memory_try_enable_merging(new_block
->host
, new_block
->max_length
);
1894 new_ram_size
= MAX(old_ram_size
,
1895 (new_block
->offset
+ new_block
->max_length
) >> TARGET_PAGE_BITS
);
1896 if (new_ram_size
> old_ram_size
) {
1897 dirty_memory_extend(old_ram_size
, new_ram_size
);
1899 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1900 * QLIST (which has an RCU-friendly variant) does not have insertion at
1901 * tail, so save the last element in last_block.
1903 RAMBLOCK_FOREACH(block
) {
1905 if (block
->max_length
< new_block
->max_length
) {
1910 QLIST_INSERT_BEFORE_RCU(block
, new_block
, next
);
1911 } else if (last_block
) {
1912 QLIST_INSERT_AFTER_RCU(last_block
, new_block
, next
);
1913 } else { /* list is empty */
1914 QLIST_INSERT_HEAD_RCU(&ram_list
.blocks
, new_block
, next
);
1916 ram_list
.mru_block
= NULL
;
1918 /* Write list before version */
1921 qemu_mutex_unlock_ramlist();
1923 cpu_physical_memory_set_dirty_range(new_block
->offset
,
1924 new_block
->used_length
,
1927 if (new_block
->host
) {
1928 qemu_ram_setup_dump(new_block
->host
, new_block
->max_length
);
1929 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_HUGEPAGE
);
1931 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
1932 * Configure it unless the machine is a qtest server, in which case
1933 * KVM is not used and it may be forked (eg for fuzzing purposes).
1935 if (!qtest_enabled()) {
1936 qemu_madvise(new_block
->host
, new_block
->max_length
,
1937 QEMU_MADV_DONTFORK
);
1939 ram_block_notify_add(new_block
->host
, new_block
->max_length
);
1944 RAMBlock
*qemu_ram_alloc_from_fd(ram_addr_t size
, MemoryRegion
*mr
,
1945 uint32_t ram_flags
, int fd
,
1948 RAMBlock
*new_block
;
1949 Error
*local_err
= NULL
;
1950 int64_t file_size
, file_align
;
1952 /* Just support these ram flags by now. */
1953 assert((ram_flags
& ~(RAM_SHARED
| RAM_PMEM
)) == 0);
1955 if (xen_enabled()) {
1956 error_setg(errp
, "-mem-path not supported with Xen");
1960 if (kvm_enabled() && !kvm_has_sync_mmu()) {
1962 "host lacks kvm mmu notifiers, -mem-path unsupported");
1966 if (phys_mem_alloc
!= qemu_anon_ram_alloc
) {
1968 * file_ram_alloc() needs to allocate just like
1969 * phys_mem_alloc, but we haven't bothered to provide
1973 "-mem-path not supported with this accelerator");
1977 size
= HOST_PAGE_ALIGN(size
);
1978 file_size
= get_file_size(fd
);
1979 if (file_size
> 0 && file_size
< size
) {
1980 error_setg(errp
, "backing store size 0x%" PRIx64
1981 " does not match 'size' option 0x" RAM_ADDR_FMT
,
1986 file_align
= get_file_align(fd
);
1987 if (file_align
> 0 && mr
&& file_align
> mr
->align
) {
1988 error_setg(errp
, "backing store align 0x%" PRIx64
1989 " is larger than 'align' option 0x%" PRIx64
,
1990 file_align
, mr
->align
);
1994 new_block
= g_malloc0(sizeof(*new_block
));
1996 new_block
->used_length
= size
;
1997 new_block
->max_length
= size
;
1998 new_block
->flags
= ram_flags
;
1999 new_block
->host
= file_ram_alloc(new_block
, size
, fd
, !file_size
, errp
);
2000 if (!new_block
->host
) {
2005 ram_block_add(new_block
, &local_err
, ram_flags
& RAM_SHARED
);
2008 error_propagate(errp
, local_err
);
2016 RAMBlock
*qemu_ram_alloc_from_file(ram_addr_t size
, MemoryRegion
*mr
,
2017 uint32_t ram_flags
, const char *mem_path
,
2024 fd
= file_ram_open(mem_path
, memory_region_name(mr
), &created
, errp
);
2029 block
= qemu_ram_alloc_from_fd(size
, mr
, ram_flags
, fd
, errp
);
2043 RAMBlock
*qemu_ram_alloc_internal(ram_addr_t size
, ram_addr_t max_size
,
2044 void (*resized
)(const char*,
2047 void *host
, bool resizeable
, bool share
,
2048 MemoryRegion
*mr
, Error
**errp
)
2050 RAMBlock
*new_block
;
2051 Error
*local_err
= NULL
;
2053 size
= HOST_PAGE_ALIGN(size
);
2054 max_size
= HOST_PAGE_ALIGN(max_size
);
2055 new_block
= g_malloc0(sizeof(*new_block
));
2057 new_block
->resized
= resized
;
2058 new_block
->used_length
= size
;
2059 new_block
->max_length
= max_size
;
2060 assert(max_size
>= size
);
2062 new_block
->page_size
= qemu_real_host_page_size
;
2063 new_block
->host
= host
;
2065 new_block
->flags
|= RAM_PREALLOC
;
2068 new_block
->flags
|= RAM_RESIZEABLE
;
2070 ram_block_add(new_block
, &local_err
, share
);
2073 error_propagate(errp
, local_err
);
2079 RAMBlock
*qemu_ram_alloc_from_ptr(ram_addr_t size
, void *host
,
2080 MemoryRegion
*mr
, Error
**errp
)
2082 return qemu_ram_alloc_internal(size
, size
, NULL
, host
, false,
2086 RAMBlock
*qemu_ram_alloc(ram_addr_t size
, bool share
,
2087 MemoryRegion
*mr
, Error
**errp
)
2089 return qemu_ram_alloc_internal(size
, size
, NULL
, NULL
, false,
2093 RAMBlock
*qemu_ram_alloc_resizeable(ram_addr_t size
, ram_addr_t maxsz
,
2094 void (*resized
)(const char*,
2097 MemoryRegion
*mr
, Error
**errp
)
2099 return qemu_ram_alloc_internal(size
, maxsz
, resized
, NULL
, true,
2103 static void reclaim_ramblock(RAMBlock
*block
)
2105 if (block
->flags
& RAM_PREALLOC
) {
2107 } else if (xen_enabled()) {
2108 xen_invalidate_map_cache_entry(block
->host
);
2110 } else if (block
->fd
>= 0) {
2111 qemu_ram_munmap(block
->fd
, block
->host
, block
->max_length
);
2115 qemu_anon_ram_free(block
->host
, block
->max_length
);
2120 void qemu_ram_free(RAMBlock
*block
)
2127 ram_block_notify_remove(block
->host
, block
->max_length
);
2130 qemu_mutex_lock_ramlist();
2131 QLIST_REMOVE_RCU(block
, next
);
2132 ram_list
.mru_block
= NULL
;
2133 /* Write list before version */
2136 call_rcu(block
, reclaim_ramblock
, rcu
);
2137 qemu_mutex_unlock_ramlist();
2141 void qemu_ram_remap(ram_addr_t addr
, ram_addr_t length
)
2148 RAMBLOCK_FOREACH(block
) {
2149 offset
= addr
- block
->offset
;
2150 if (offset
< block
->max_length
) {
2151 vaddr
= ramblock_ptr(block
, offset
);
2152 if (block
->flags
& RAM_PREALLOC
) {
2154 } else if (xen_enabled()) {
2158 if (block
->fd
>= 0) {
2159 flags
|= (block
->flags
& RAM_SHARED
?
2160 MAP_SHARED
: MAP_PRIVATE
);
2161 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2162 flags
, block
->fd
, offset
);
2165 * Remap needs to match alloc. Accelerators that
2166 * set phys_mem_alloc never remap. If they did,
2167 * we'd need a remap hook here.
2169 assert(phys_mem_alloc
== qemu_anon_ram_alloc
);
2171 flags
|= MAP_PRIVATE
| MAP_ANONYMOUS
;
2172 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2175 if (area
!= vaddr
) {
2176 error_report("Could not remap addr: "
2177 RAM_ADDR_FMT
"@" RAM_ADDR_FMT
"",
2181 memory_try_enable_merging(vaddr
, length
);
2182 qemu_ram_setup_dump(vaddr
, length
);
2187 #endif /* !_WIN32 */
2189 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2190 * This should not be used for general purpose DMA. Use address_space_map
2191 * or address_space_rw instead. For local memory (e.g. video ram) that the
2192 * device owns, use memory_region_get_ram_ptr.
2194 * Called within RCU critical section.
2196 void *qemu_map_ram_ptr(RAMBlock
*ram_block
, ram_addr_t addr
)
2198 RAMBlock
*block
= ram_block
;
2200 if (block
== NULL
) {
2201 block
= qemu_get_ram_block(addr
);
2202 addr
-= block
->offset
;
2205 if (xen_enabled() && block
->host
== NULL
) {
2206 /* We need to check if the requested address is in the RAM
2207 * because we don't want to map the entire memory in QEMU.
2208 * In that case just map until the end of the page.
2210 if (block
->offset
== 0) {
2211 return xen_map_cache(addr
, 0, 0, false);
2214 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, false);
2216 return ramblock_ptr(block
, addr
);
2219 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2220 * but takes a size argument.
2222 * Called within RCU critical section.
2224 static void *qemu_ram_ptr_length(RAMBlock
*ram_block
, ram_addr_t addr
,
2225 hwaddr
*size
, bool lock
)
2227 RAMBlock
*block
= ram_block
;
2232 if (block
== NULL
) {
2233 block
= qemu_get_ram_block(addr
);
2234 addr
-= block
->offset
;
2236 *size
= MIN(*size
, block
->max_length
- addr
);
2238 if (xen_enabled() && block
->host
== NULL
) {
2239 /* We need to check if the requested address is in the RAM
2240 * because we don't want to map the entire memory in QEMU.
2241 * In that case just map the requested area.
2243 if (block
->offset
== 0) {
2244 return xen_map_cache(addr
, *size
, lock
, lock
);
2247 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, lock
);
2250 return ramblock_ptr(block
, addr
);
2253 /* Return the offset of a hostpointer within a ramblock */
2254 ram_addr_t
qemu_ram_block_host_offset(RAMBlock
*rb
, void *host
)
2256 ram_addr_t res
= (uint8_t *)host
- (uint8_t *)rb
->host
;
2257 assert((uintptr_t)host
>= (uintptr_t)rb
->host
);
2258 assert(res
< rb
->max_length
);
2264 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2267 * ptr: Host pointer to look up
2268 * round_offset: If true round the result offset down to a page boundary
2269 * *ram_addr: set to result ram_addr
2270 * *offset: set to result offset within the RAMBlock
2272 * Returns: RAMBlock (or NULL if not found)
2274 * By the time this function returns, the returned pointer is not protected
2275 * by RCU anymore. If the caller is not within an RCU critical section and
2276 * does not hold the iothread lock, it must have other means of protecting the
2277 * pointer, such as a reference to the region that includes the incoming
2280 RAMBlock
*qemu_ram_block_from_host(void *ptr
, bool round_offset
,
2284 uint8_t *host
= ptr
;
2286 if (xen_enabled()) {
2287 ram_addr_t ram_addr
;
2288 RCU_READ_LOCK_GUARD();
2289 ram_addr
= xen_ram_addr_from_mapcache(ptr
);
2290 block
= qemu_get_ram_block(ram_addr
);
2292 *offset
= ram_addr
- block
->offset
;
2297 RCU_READ_LOCK_GUARD();
2298 block
= qatomic_rcu_read(&ram_list
.mru_block
);
2299 if (block
&& block
->host
&& host
- block
->host
< block
->max_length
) {
2303 RAMBLOCK_FOREACH(block
) {
2304 /* This case append when the block is not mapped. */
2305 if (block
->host
== NULL
) {
2308 if (host
- block
->host
< block
->max_length
) {
2316 *offset
= (host
- block
->host
);
2318 *offset
&= TARGET_PAGE_MASK
;
2324 * Finds the named RAMBlock
2326 * name: The name of RAMBlock to find
2328 * Returns: RAMBlock (or NULL if not found)
2330 RAMBlock
*qemu_ram_block_by_name(const char *name
)
2334 RAMBLOCK_FOREACH(block
) {
2335 if (!strcmp(name
, block
->idstr
)) {
2343 /* Some of the softmmu routines need to translate from a host pointer
2344 (typically a TLB entry) back to a ram offset. */
2345 ram_addr_t
qemu_ram_addr_from_host(void *ptr
)
2350 block
= qemu_ram_block_from_host(ptr
, false, &offset
);
2352 return RAM_ADDR_INVALID
;
2355 return block
->offset
+ offset
;
2358 /* Generate a debug exception if a watchpoint has been hit. */
2359 void cpu_check_watchpoint(CPUState
*cpu
, vaddr addr
, vaddr len
,
2360 MemTxAttrs attrs
, int flags
, uintptr_t ra
)
2362 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
2365 assert(tcg_enabled());
2366 if (cpu
->watchpoint_hit
) {
2368 * We re-entered the check after replacing the TB.
2369 * Now raise the debug interrupt so that it will
2370 * trigger after the current instruction.
2372 qemu_mutex_lock_iothread();
2373 cpu_interrupt(cpu
, CPU_INTERRUPT_DEBUG
);
2374 qemu_mutex_unlock_iothread();
2378 addr
= cc
->adjust_watchpoint_address(cpu
, addr
, len
);
2379 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
2380 if (watchpoint_address_matches(wp
, addr
, len
)
2381 && (wp
->flags
& flags
)) {
2382 if (replay_running_debug()) {
2384 * Don't process the watchpoints when we are
2385 * in a reverse debugging operation.
2387 replay_breakpoint();
2390 if (flags
== BP_MEM_READ
) {
2391 wp
->flags
|= BP_WATCHPOINT_HIT_READ
;
2393 wp
->flags
|= BP_WATCHPOINT_HIT_WRITE
;
2395 wp
->hitaddr
= MAX(addr
, wp
->vaddr
);
2396 wp
->hitattrs
= attrs
;
2397 if (!cpu
->watchpoint_hit
) {
2398 if (wp
->flags
& BP_CPU
&&
2399 !cc
->debug_check_watchpoint(cpu
, wp
)) {
2400 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
2403 cpu
->watchpoint_hit
= wp
;
2406 tb_check_watchpoint(cpu
, ra
);
2407 if (wp
->flags
& BP_STOP_BEFORE_ACCESS
) {
2408 cpu
->exception_index
= EXCP_DEBUG
;
2410 cpu_loop_exit_restore(cpu
, ra
);
2412 /* Force execution of one insn next time. */
2413 cpu
->cflags_next_tb
= 1 | curr_cflags();
2416 cpu_restore_state(cpu
, ra
, true);
2418 cpu_loop_exit_noexc(cpu
);
2422 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
2427 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2428 MemTxAttrs attrs
, void *buf
, hwaddr len
);
2429 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2430 const void *buf
, hwaddr len
);
2431 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
2432 bool is_write
, MemTxAttrs attrs
);
2434 static MemTxResult
subpage_read(void *opaque
, hwaddr addr
, uint64_t *data
,
2435 unsigned len
, MemTxAttrs attrs
)
2437 subpage_t
*subpage
= opaque
;
2441 #if defined(DEBUG_SUBPAGE)
2442 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
"\n", __func__
,
2443 subpage
, len
, addr
);
2445 res
= flatview_read(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2449 *data
= ldn_p(buf
, len
);
2453 static MemTxResult
subpage_write(void *opaque
, hwaddr addr
,
2454 uint64_t value
, unsigned len
, MemTxAttrs attrs
)
2456 subpage_t
*subpage
= opaque
;
2459 #if defined(DEBUG_SUBPAGE)
2460 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2461 " value %"PRIx64
"\n",
2462 __func__
, subpage
, len
, addr
, value
);
2464 stn_p(buf
, len
, value
);
2465 return flatview_write(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2468 static bool subpage_accepts(void *opaque
, hwaddr addr
,
2469 unsigned len
, bool is_write
,
2472 subpage_t
*subpage
= opaque
;
2473 #if defined(DEBUG_SUBPAGE)
2474 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx
"\n",
2475 __func__
, subpage
, is_write
? 'w' : 'r', len
, addr
);
2478 return flatview_access_valid(subpage
->fv
, addr
+ subpage
->base
,
2479 len
, is_write
, attrs
);
2482 static const MemoryRegionOps subpage_ops
= {
2483 .read_with_attrs
= subpage_read
,
2484 .write_with_attrs
= subpage_write
,
2485 .impl
.min_access_size
= 1,
2486 .impl
.max_access_size
= 8,
2487 .valid
.min_access_size
= 1,
2488 .valid
.max_access_size
= 8,
2489 .valid
.accepts
= subpage_accepts
,
2490 .endianness
= DEVICE_NATIVE_ENDIAN
,
2493 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
2498 if (start
>= TARGET_PAGE_SIZE
|| end
>= TARGET_PAGE_SIZE
)
2500 idx
= SUBPAGE_IDX(start
);
2501 eidx
= SUBPAGE_IDX(end
);
2502 #if defined(DEBUG_SUBPAGE)
2503 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2504 __func__
, mmio
, start
, end
, idx
, eidx
, section
);
2506 for (; idx
<= eidx
; idx
++) {
2507 mmio
->sub_section
[idx
] = section
;
2513 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
)
2517 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2518 mmio
= g_malloc0(sizeof(subpage_t
) + TARGET_PAGE_SIZE
* sizeof(uint16_t));
2521 memory_region_init_io(&mmio
->iomem
, NULL
, &subpage_ops
, mmio
,
2522 NULL
, TARGET_PAGE_SIZE
);
2523 mmio
->iomem
.subpage
= true;
2524 #if defined(DEBUG_SUBPAGE)
2525 printf("%s: %p base " TARGET_FMT_plx
" len %08x\n", __func__
,
2526 mmio
, base
, TARGET_PAGE_SIZE
);
2532 static uint16_t dummy_section(PhysPageMap
*map
, FlatView
*fv
, MemoryRegion
*mr
)
2535 MemoryRegionSection section
= {
2538 .offset_within_address_space
= 0,
2539 .offset_within_region
= 0,
2540 .size
= int128_2_64(),
2543 return phys_section_add(map
, §ion
);
2546 MemoryRegionSection
*iotlb_to_section(CPUState
*cpu
,
2547 hwaddr index
, MemTxAttrs attrs
)
2549 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
2550 CPUAddressSpace
*cpuas
= &cpu
->cpu_ases
[asidx
];
2551 AddressSpaceDispatch
*d
= qatomic_rcu_read(&cpuas
->memory_dispatch
);
2552 MemoryRegionSection
*sections
= d
->map
.sections
;
2554 return §ions
[index
& ~TARGET_PAGE_MASK
];
2557 static void io_mem_init(void)
2559 memory_region_init_io(&io_mem_unassigned
, NULL
, &unassigned_mem_ops
, NULL
,
2563 AddressSpaceDispatch
*address_space_dispatch_new(FlatView
*fv
)
2565 AddressSpaceDispatch
*d
= g_new0(AddressSpaceDispatch
, 1);
2568 n
= dummy_section(&d
->map
, fv
, &io_mem_unassigned
);
2569 assert(n
== PHYS_SECTION_UNASSIGNED
);
2571 d
->phys_map
= (PhysPageEntry
) { .ptr
= PHYS_MAP_NODE_NIL
, .skip
= 1 };
2576 void address_space_dispatch_free(AddressSpaceDispatch
*d
)
2578 phys_sections_free(&d
->map
);
2582 static void do_nothing(CPUState
*cpu
, run_on_cpu_data d
)
2586 static void tcg_log_global_after_sync(MemoryListener
*listener
)
2588 CPUAddressSpace
*cpuas
;
2590 /* Wait for the CPU to end the current TB. This avoids the following
2594 * ---------------------- -------------------------
2595 * TLB check -> slow path
2596 * notdirty_mem_write
2600 * TLB check -> fast path
2604 * by pushing the migration thread's memory read after the vCPU thread has
2605 * written the memory.
2607 if (replay_mode
== REPLAY_MODE_NONE
) {
2609 * VGA can make calls to this function while updating the screen.
2610 * In record/replay mode this causes a deadlock, because
2611 * run_on_cpu waits for rr mutex. Therefore no races are possible
2612 * in this case and no need for making run_on_cpu when
2613 * record/replay is not enabled.
2615 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2616 run_on_cpu(cpuas
->cpu
, do_nothing
, RUN_ON_CPU_NULL
);
2620 static void tcg_commit(MemoryListener
*listener
)
2622 CPUAddressSpace
*cpuas
;
2623 AddressSpaceDispatch
*d
;
2625 assert(tcg_enabled());
2626 /* since each CPU stores ram addresses in its TLB cache, we must
2627 reset the modified entries */
2628 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2629 cpu_reloading_memory_map();
2630 /* The CPU and TLB are protected by the iothread lock.
2631 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2632 * may have split the RCU critical section.
2634 d
= address_space_to_dispatch(cpuas
->as
);
2635 qatomic_rcu_set(&cpuas
->memory_dispatch
, d
);
2636 tlb_flush(cpuas
->cpu
);
2639 static void memory_map_init(void)
2641 system_memory
= g_malloc(sizeof(*system_memory
));
2643 memory_region_init(system_memory
, NULL
, "system", UINT64_MAX
);
2644 address_space_init(&address_space_memory
, system_memory
, "memory");
2646 system_io
= g_malloc(sizeof(*system_io
));
2647 memory_region_init_io(system_io
, NULL
, &unassigned_io_ops
, NULL
, "io",
2649 address_space_init(&address_space_io
, system_io
, "I/O");
2652 MemoryRegion
*get_system_memory(void)
2654 return system_memory
;
2657 MemoryRegion
*get_system_io(void)
2662 static void invalidate_and_set_dirty(MemoryRegion
*mr
, hwaddr addr
,
2665 uint8_t dirty_log_mask
= memory_region_get_dirty_log_mask(mr
);
2666 addr
+= memory_region_get_ram_addr(mr
);
2668 /* No early return if dirty_log_mask is or becomes 0, because
2669 * cpu_physical_memory_set_dirty_range will still call
2670 * xen_modified_memory.
2672 if (dirty_log_mask
) {
2674 cpu_physical_memory_range_includes_clean(addr
, length
, dirty_log_mask
);
2676 if (dirty_log_mask
& (1 << DIRTY_MEMORY_CODE
)) {
2677 assert(tcg_enabled());
2678 tb_invalidate_phys_range(addr
, addr
+ length
);
2679 dirty_log_mask
&= ~(1 << DIRTY_MEMORY_CODE
);
2681 cpu_physical_memory_set_dirty_range(addr
, length
, dirty_log_mask
);
2684 void memory_region_flush_rom_device(MemoryRegion
*mr
, hwaddr addr
, hwaddr size
)
2687 * In principle this function would work on other memory region types too,
2688 * but the ROM device use case is the only one where this operation is
2689 * necessary. Other memory regions should use the
2690 * address_space_read/write() APIs.
2692 assert(memory_region_is_romd(mr
));
2694 invalidate_and_set_dirty(mr
, addr
, size
);
2697 static int memory_access_size(MemoryRegion
*mr
, unsigned l
, hwaddr addr
)
2699 unsigned access_size_max
= mr
->ops
->valid
.max_access_size
;
2701 /* Regions are assumed to support 1-4 byte accesses unless
2702 otherwise specified. */
2703 if (access_size_max
== 0) {
2704 access_size_max
= 4;
2707 /* Bound the maximum access by the alignment of the address. */
2708 if (!mr
->ops
->impl
.unaligned
) {
2709 unsigned align_size_max
= addr
& -addr
;
2710 if (align_size_max
!= 0 && align_size_max
< access_size_max
) {
2711 access_size_max
= align_size_max
;
2715 /* Don't attempt accesses larger than the maximum. */
2716 if (l
> access_size_max
) {
2717 l
= access_size_max
;
2724 static bool prepare_mmio_access(MemoryRegion
*mr
)
2726 bool unlocked
= !qemu_mutex_iothread_locked();
2727 bool release_lock
= false;
2730 qemu_mutex_lock_iothread();
2732 release_lock
= true;
2734 if (mr
->flush_coalesced_mmio
) {
2736 qemu_mutex_lock_iothread();
2738 qemu_flush_coalesced_mmio_buffer();
2740 qemu_mutex_unlock_iothread();
2744 return release_lock
;
2747 /* Called within RCU critical section. */
2748 static MemTxResult
flatview_write_continue(FlatView
*fv
, hwaddr addr
,
2751 hwaddr len
, hwaddr addr1
,
2752 hwaddr l
, MemoryRegion
*mr
)
2756 MemTxResult result
= MEMTX_OK
;
2757 bool release_lock
= false;
2758 const uint8_t *buf
= ptr
;
2761 if (!memory_access_is_direct(mr
, true)) {
2762 release_lock
|= prepare_mmio_access(mr
);
2763 l
= memory_access_size(mr
, l
, addr1
);
2764 /* XXX: could force current_cpu to NULL to avoid
2766 val
= ldn_he_p(buf
, l
);
2767 result
|= memory_region_dispatch_write(mr
, addr1
, val
,
2768 size_memop(l
), attrs
);
2771 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2772 memcpy(ram_ptr
, buf
, l
);
2773 invalidate_and_set_dirty(mr
, addr1
, l
);
2777 qemu_mutex_unlock_iothread();
2778 release_lock
= false;
2790 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2796 /* Called from RCU critical section. */
2797 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2798 const void *buf
, hwaddr len
)
2803 MemTxResult result
= MEMTX_OK
;
2806 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2807 result
= flatview_write_continue(fv
, addr
, attrs
, buf
, len
,
2813 /* Called within RCU critical section. */
2814 MemTxResult
flatview_read_continue(FlatView
*fv
, hwaddr addr
,
2815 MemTxAttrs attrs
, void *ptr
,
2816 hwaddr len
, hwaddr addr1
, hwaddr l
,
2821 MemTxResult result
= MEMTX_OK
;
2822 bool release_lock
= false;
2826 if (!memory_access_is_direct(mr
, false)) {
2828 release_lock
|= prepare_mmio_access(mr
);
2829 l
= memory_access_size(mr
, l
, addr1
);
2830 result
|= memory_region_dispatch_read(mr
, addr1
, &val
,
2831 size_memop(l
), attrs
);
2832 stn_he_p(buf
, l
, val
);
2835 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2836 memcpy(buf
, ram_ptr
, l
);
2840 qemu_mutex_unlock_iothread();
2841 release_lock
= false;
2853 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2859 /* Called from RCU critical section. */
2860 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2861 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2868 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2869 return flatview_read_continue(fv
, addr
, attrs
, buf
, len
,
2873 MemTxResult
address_space_read_full(AddressSpace
*as
, hwaddr addr
,
2874 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2876 MemTxResult result
= MEMTX_OK
;
2880 RCU_READ_LOCK_GUARD();
2881 fv
= address_space_to_flatview(as
);
2882 result
= flatview_read(fv
, addr
, attrs
, buf
, len
);
2888 MemTxResult
address_space_write(AddressSpace
*as
, hwaddr addr
,
2890 const void *buf
, hwaddr len
)
2892 MemTxResult result
= MEMTX_OK
;
2896 RCU_READ_LOCK_GUARD();
2897 fv
= address_space_to_flatview(as
);
2898 result
= flatview_write(fv
, addr
, attrs
, buf
, len
);
2904 MemTxResult
address_space_rw(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
,
2905 void *buf
, hwaddr len
, bool is_write
)
2908 return address_space_write(as
, addr
, attrs
, buf
, len
);
2910 return address_space_read_full(as
, addr
, attrs
, buf
, len
);
2914 void cpu_physical_memory_rw(hwaddr addr
, void *buf
,
2915 hwaddr len
, bool is_write
)
2917 address_space_rw(&address_space_memory
, addr
, MEMTXATTRS_UNSPECIFIED
,
2918 buf
, len
, is_write
);
2921 enum write_rom_type
{
2926 static inline MemTxResult
address_space_write_rom_internal(AddressSpace
*as
,
2931 enum write_rom_type type
)
2937 const uint8_t *buf
= ptr
;
2939 RCU_READ_LOCK_GUARD();
2942 mr
= address_space_translate(as
, addr
, &addr1
, &l
, true, attrs
);
2944 if (!(memory_region_is_ram(mr
) ||
2945 memory_region_is_romd(mr
))) {
2946 l
= memory_access_size(mr
, l
, addr1
);
2949 ram_ptr
= qemu_map_ram_ptr(mr
->ram_block
, addr1
);
2952 memcpy(ram_ptr
, buf
, l
);
2953 invalidate_and_set_dirty(mr
, addr1
, l
);
2956 flush_icache_range((uintptr_t)ram_ptr
, (uintptr_t)ram_ptr
+ l
);
2967 /* used for ROM loading : can write in RAM and ROM */
2968 MemTxResult
address_space_write_rom(AddressSpace
*as
, hwaddr addr
,
2970 const void *buf
, hwaddr len
)
2972 return address_space_write_rom_internal(as
, addr
, attrs
,
2973 buf
, len
, WRITE_DATA
);
2976 void cpu_flush_icache_range(hwaddr start
, hwaddr len
)
2979 * This function should do the same thing as an icache flush that was
2980 * triggered from within the guest. For TCG we are always cache coherent,
2981 * so there is no need to flush anything. For KVM / Xen we need to flush
2982 * the host's instruction cache at least.
2984 if (tcg_enabled()) {
2988 address_space_write_rom_internal(&address_space_memory
,
2989 start
, MEMTXATTRS_UNSPECIFIED
,
2990 NULL
, len
, FLUSH_CACHE
);
3001 static BounceBuffer bounce
;
3003 typedef struct MapClient
{
3005 QLIST_ENTRY(MapClient
) link
;
3008 QemuMutex map_client_list_lock
;
3009 static QLIST_HEAD(, MapClient
) map_client_list
3010 = QLIST_HEAD_INITIALIZER(map_client_list
);
3012 static void cpu_unregister_map_client_do(MapClient
*client
)
3014 QLIST_REMOVE(client
, link
);
3018 static void cpu_notify_map_clients_locked(void)
3022 while (!QLIST_EMPTY(&map_client_list
)) {
3023 client
= QLIST_FIRST(&map_client_list
);
3024 qemu_bh_schedule(client
->bh
);
3025 cpu_unregister_map_client_do(client
);
3029 void cpu_register_map_client(QEMUBH
*bh
)
3031 MapClient
*client
= g_malloc(sizeof(*client
));
3033 qemu_mutex_lock(&map_client_list_lock
);
3035 QLIST_INSERT_HEAD(&map_client_list
, client
, link
);
3036 if (!qatomic_read(&bounce
.in_use
)) {
3037 cpu_notify_map_clients_locked();
3039 qemu_mutex_unlock(&map_client_list_lock
);
3042 void cpu_exec_init_all(void)
3044 qemu_mutex_init(&ram_list
.mutex
);
3045 /* The data structures we set up here depend on knowing the page size,
3046 * so no more changes can be made after this point.
3047 * In an ideal world, nothing we did before we had finished the
3048 * machine setup would care about the target page size, and we could
3049 * do this much later, rather than requiring board models to state
3050 * up front what their requirements are.
3052 finalize_target_page_bits();
3055 qemu_mutex_init(&map_client_list_lock
);
3058 void cpu_unregister_map_client(QEMUBH
*bh
)
3062 qemu_mutex_lock(&map_client_list_lock
);
3063 QLIST_FOREACH(client
, &map_client_list
, link
) {
3064 if (client
->bh
== bh
) {
3065 cpu_unregister_map_client_do(client
);
3069 qemu_mutex_unlock(&map_client_list_lock
);
3072 static void cpu_notify_map_clients(void)
3074 qemu_mutex_lock(&map_client_list_lock
);
3075 cpu_notify_map_clients_locked();
3076 qemu_mutex_unlock(&map_client_list_lock
);
3079 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
3080 bool is_write
, MemTxAttrs attrs
)
3087 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3088 if (!memory_access_is_direct(mr
, is_write
)) {
3089 l
= memory_access_size(mr
, l
, addr
);
3090 if (!memory_region_access_valid(mr
, xlat
, l
, is_write
, attrs
)) {
3101 bool address_space_access_valid(AddressSpace
*as
, hwaddr addr
,
3102 hwaddr len
, bool is_write
,
3108 RCU_READ_LOCK_GUARD();
3109 fv
= address_space_to_flatview(as
);
3110 result
= flatview_access_valid(fv
, addr
, len
, is_write
, attrs
);
3115 flatview_extend_translation(FlatView
*fv
, hwaddr addr
,
3117 MemoryRegion
*mr
, hwaddr base
, hwaddr len
,
3118 bool is_write
, MemTxAttrs attrs
)
3122 MemoryRegion
*this_mr
;
3128 if (target_len
== 0) {
3133 this_mr
= flatview_translate(fv
, addr
, &xlat
,
3134 &len
, is_write
, attrs
);
3135 if (this_mr
!= mr
|| xlat
!= base
+ done
) {
3141 /* Map a physical memory region into a host virtual address.
3142 * May map a subset of the requested range, given by and returned in *plen.
3143 * May return NULL if resources needed to perform the mapping are exhausted.
3144 * Use only for reads OR writes - not for read-modify-write operations.
3145 * Use cpu_register_map_client() to know when retrying the map operation is
3146 * likely to succeed.
3148 void *address_space_map(AddressSpace
*as
,
3165 RCU_READ_LOCK_GUARD();
3166 fv
= address_space_to_flatview(as
);
3167 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3169 if (!memory_access_is_direct(mr
, is_write
)) {
3170 if (qatomic_xchg(&bounce
.in_use
, true)) {
3174 /* Avoid unbounded allocations */
3175 l
= MIN(l
, TARGET_PAGE_SIZE
);
3176 bounce
.buffer
= qemu_memalign(TARGET_PAGE_SIZE
, l
);
3180 memory_region_ref(mr
);
3183 flatview_read(fv
, addr
, MEMTXATTRS_UNSPECIFIED
,
3188 return bounce
.buffer
;
3192 memory_region_ref(mr
);
3193 *plen
= flatview_extend_translation(fv
, addr
, len
, mr
, xlat
,
3194 l
, is_write
, attrs
);
3195 ptr
= qemu_ram_ptr_length(mr
->ram_block
, xlat
, plen
, true);
3200 /* Unmaps a memory region previously mapped by address_space_map().
3201 * Will also mark the memory as dirty if is_write is true. access_len gives
3202 * the amount of memory that was actually read or written by the caller.
3204 void address_space_unmap(AddressSpace
*as
, void *buffer
, hwaddr len
,
3205 bool is_write
, hwaddr access_len
)
3207 if (buffer
!= bounce
.buffer
) {
3211 mr
= memory_region_from_host(buffer
, &addr1
);
3214 invalidate_and_set_dirty(mr
, addr1
, access_len
);
3216 if (xen_enabled()) {
3217 xen_invalidate_map_cache_entry(buffer
);
3219 memory_region_unref(mr
);
3223 address_space_write(as
, bounce
.addr
, MEMTXATTRS_UNSPECIFIED
,
3224 bounce
.buffer
, access_len
);
3226 qemu_vfree(bounce
.buffer
);
3227 bounce
.buffer
= NULL
;
3228 memory_region_unref(bounce
.mr
);
3229 qatomic_mb_set(&bounce
.in_use
, false);
3230 cpu_notify_map_clients();
3233 void *cpu_physical_memory_map(hwaddr addr
,
3237 return address_space_map(&address_space_memory
, addr
, plen
, is_write
,
3238 MEMTXATTRS_UNSPECIFIED
);
3241 void cpu_physical_memory_unmap(void *buffer
, hwaddr len
,
3242 bool is_write
, hwaddr access_len
)
3244 return address_space_unmap(&address_space_memory
, buffer
, len
, is_write
, access_len
);
3247 #define ARG1_DECL AddressSpace *as
3250 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3251 #define RCU_READ_LOCK(...) rcu_read_lock()
3252 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3253 #include "memory_ldst.c.inc"
3255 int64_t address_space_cache_init(MemoryRegionCache
*cache
,
3261 AddressSpaceDispatch
*d
;
3268 cache
->fv
= address_space_get_flatview(as
);
3269 d
= flatview_to_dispatch(cache
->fv
);
3270 cache
->mrs
= *address_space_translate_internal(d
, addr
, &cache
->xlat
, &l
, true);
3273 memory_region_ref(mr
);
3274 if (memory_access_is_direct(mr
, is_write
)) {
3275 /* We don't care about the memory attributes here as we're only
3276 * doing this if we found actual RAM, which behaves the same
3277 * regardless of attributes; so UNSPECIFIED is fine.
3279 l
= flatview_extend_translation(cache
->fv
, addr
, len
, mr
,
3280 cache
->xlat
, l
, is_write
,
3281 MEMTXATTRS_UNSPECIFIED
);
3282 cache
->ptr
= qemu_ram_ptr_length(mr
->ram_block
, cache
->xlat
, &l
, true);
3288 cache
->is_write
= is_write
;
3292 void address_space_cache_invalidate(MemoryRegionCache
*cache
,
3296 assert(cache
->is_write
);
3297 if (likely(cache
->ptr
)) {
3298 invalidate_and_set_dirty(cache
->mrs
.mr
, addr
+ cache
->xlat
, access_len
);
3302 void address_space_cache_destroy(MemoryRegionCache
*cache
)
3304 if (!cache
->mrs
.mr
) {
3308 if (xen_enabled()) {
3309 xen_invalidate_map_cache_entry(cache
->ptr
);
3311 memory_region_unref(cache
->mrs
.mr
);
3312 flatview_unref(cache
->fv
);
3313 cache
->mrs
.mr
= NULL
;
3317 /* Called from RCU critical section. This function has the same
3318 * semantics as address_space_translate, but it only works on a
3319 * predefined range of a MemoryRegion that was mapped with
3320 * address_space_cache_init.
3322 static inline MemoryRegion
*address_space_translate_cached(
3323 MemoryRegionCache
*cache
, hwaddr addr
, hwaddr
*xlat
,
3324 hwaddr
*plen
, bool is_write
, MemTxAttrs attrs
)
3326 MemoryRegionSection section
;
3328 IOMMUMemoryRegion
*iommu_mr
;
3329 AddressSpace
*target_as
;
3331 assert(!cache
->ptr
);
3332 *xlat
= addr
+ cache
->xlat
;
3335 iommu_mr
= memory_region_get_iommu(mr
);
3341 section
= address_space_translate_iommu(iommu_mr
, xlat
, plen
,
3342 NULL
, is_write
, true,
3347 /* Called from RCU critical section. address_space_read_cached uses this
3348 * out of line function when the target is an MMIO or IOMMU region.
3351 address_space_read_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3352 void *buf
, hwaddr len
)
3358 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, false,
3359 MEMTXATTRS_UNSPECIFIED
);
3360 return flatview_read_continue(cache
->fv
,
3361 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3365 /* Called from RCU critical section. address_space_write_cached uses this
3366 * out of line function when the target is an MMIO or IOMMU region.
3369 address_space_write_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3370 const void *buf
, hwaddr len
)
3376 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, true,
3377 MEMTXATTRS_UNSPECIFIED
);
3378 return flatview_write_continue(cache
->fv
,
3379 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3383 #define ARG1_DECL MemoryRegionCache *cache
3385 #define SUFFIX _cached_slow
3386 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3387 #define RCU_READ_LOCK() ((void)0)
3388 #define RCU_READ_UNLOCK() ((void)0)
3389 #include "memory_ldst.c.inc"
3391 /* virtual memory access for debug (includes writing to ROM) */
3392 int cpu_memory_rw_debug(CPUState
*cpu
, target_ulong addr
,
3393 void *ptr
, target_ulong len
, bool is_write
)
3396 target_ulong l
, page
;
3399 cpu_synchronize_state(cpu
);
3405 page
= addr
& TARGET_PAGE_MASK
;
3406 phys_addr
= cpu_get_phys_page_attrs_debug(cpu
, page
, &attrs
);
3407 asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
3408 /* if no physical page mapped, return an error */
3409 if (phys_addr
== -1)
3411 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3414 phys_addr
+= (addr
& ~TARGET_PAGE_MASK
);
3416 res
= address_space_write_rom(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3419 res
= address_space_read(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3422 if (res
!= MEMTX_OK
) {
3433 * Allows code that needs to deal with migration bitmaps etc to still be built
3434 * target independent.
3436 size_t qemu_target_page_size(void)
3438 return TARGET_PAGE_SIZE
;
3441 int qemu_target_page_bits(void)
3443 return TARGET_PAGE_BITS
;
3446 int qemu_target_page_bits_min(void)
3448 return TARGET_PAGE_BITS_MIN
;
3451 bool cpu_physical_memory_is_io(hwaddr phys_addr
)
3457 RCU_READ_LOCK_GUARD();
3458 mr
= address_space_translate(&address_space_memory
,
3459 phys_addr
, &phys_addr
, &l
, false,
3460 MEMTXATTRS_UNSPECIFIED
);
3462 res
= !(memory_region_is_ram(mr
) || memory_region_is_romd(mr
));
3466 int qemu_ram_foreach_block(RAMBlockIterFunc func
, void *opaque
)
3471 RCU_READ_LOCK_GUARD();
3472 RAMBLOCK_FOREACH(block
) {
3473 ret
= func(block
, opaque
);
3482 * Unmap pages of memory from start to start+length such that
3483 * they a) read as 0, b) Trigger whatever fault mechanism
3484 * the OS provides for postcopy.
3485 * The pages must be unmapped by the end of the function.
3486 * Returns: 0 on success, none-0 on failure
3489 int ram_block_discard_range(RAMBlock
*rb
, uint64_t start
, size_t length
)
3493 uint8_t *host_startaddr
= rb
->host
+ start
;
3495 if (!QEMU_PTR_IS_ALIGNED(host_startaddr
, rb
->page_size
)) {
3496 error_report("ram_block_discard_range: Unaligned start address: %p",
3501 if ((start
+ length
) <= rb
->used_length
) {
3502 bool need_madvise
, need_fallocate
;
3503 if (!QEMU_IS_ALIGNED(length
, rb
->page_size
)) {
3504 error_report("ram_block_discard_range: Unaligned length: %zx",
3509 errno
= ENOTSUP
; /* If we are missing MADVISE etc */
3511 /* The logic here is messy;
3512 * madvise DONTNEED fails for hugepages
3513 * fallocate works on hugepages and shmem
3515 need_madvise
= (rb
->page_size
== qemu_host_page_size
);
3516 need_fallocate
= rb
->fd
!= -1;
3517 if (need_fallocate
) {
3518 /* For a file, this causes the area of the file to be zero'd
3519 * if read, and for hugetlbfs also causes it to be unmapped
3520 * so a userfault will trigger.
3522 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3523 ret
= fallocate(rb
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3527 error_report("ram_block_discard_range: Failed to fallocate "
3528 "%s:%" PRIx64
" +%zx (%d)",
3529 rb
->idstr
, start
, length
, ret
);
3534 error_report("ram_block_discard_range: fallocate not available/file"
3535 "%s:%" PRIx64
" +%zx (%d)",
3536 rb
->idstr
, start
, length
, ret
);
3541 /* For normal RAM this causes it to be unmapped,
3542 * for shared memory it causes the local mapping to disappear
3543 * and to fall back on the file contents (which we just
3544 * fallocate'd away).
3546 #if defined(CONFIG_MADVISE)
3547 ret
= madvise(host_startaddr
, length
, MADV_DONTNEED
);
3550 error_report("ram_block_discard_range: Failed to discard range "
3551 "%s:%" PRIx64
" +%zx (%d)",
3552 rb
->idstr
, start
, length
, ret
);
3557 error_report("ram_block_discard_range: MADVISE not available"
3558 "%s:%" PRIx64
" +%zx (%d)",
3559 rb
->idstr
, start
, length
, ret
);
3563 trace_ram_block_discard_range(rb
->idstr
, host_startaddr
, length
,
3564 need_madvise
, need_fallocate
, ret
);
3566 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3567 "/%zx/" RAM_ADDR_FMT
")",
3568 rb
->idstr
, start
, length
, rb
->used_length
);
3575 bool ramblock_is_pmem(RAMBlock
*rb
)
3577 return rb
->flags
& RAM_PMEM
;
3580 static void mtree_print_phys_entries(int start
, int end
, int skip
, int ptr
)
3582 if (start
== end
- 1) {
3583 qemu_printf("\t%3d ", start
);
3585 qemu_printf("\t%3d..%-3d ", start
, end
- 1);
3587 qemu_printf(" skip=%d ", skip
);
3588 if (ptr
== PHYS_MAP_NODE_NIL
) {
3589 qemu_printf(" ptr=NIL");
3591 qemu_printf(" ptr=#%d", ptr
);
3593 qemu_printf(" ptr=[%d]", ptr
);
3598 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3599 int128_sub((size), int128_one())) : 0)
3601 void mtree_print_dispatch(AddressSpaceDispatch
*d
, MemoryRegion
*root
)
3605 qemu_printf(" Dispatch\n");
3606 qemu_printf(" Physical sections\n");
3608 for (i
= 0; i
< d
->map
.sections_nb
; ++i
) {
3609 MemoryRegionSection
*s
= d
->map
.sections
+ i
;
3610 const char *names
[] = { " [unassigned]", " [not dirty]",
3611 " [ROM]", " [watch]" };
3613 qemu_printf(" #%d @" TARGET_FMT_plx
".." TARGET_FMT_plx
3616 s
->offset_within_address_space
,
3617 s
->offset_within_address_space
+ MR_SIZE(s
->mr
->size
),
3618 s
->mr
->name
? s
->mr
->name
: "(noname)",
3619 i
< ARRAY_SIZE(names
) ? names
[i
] : "",
3620 s
->mr
== root
? " [ROOT]" : "",
3621 s
== d
->mru_section
? " [MRU]" : "",
3622 s
->mr
->is_iommu
? " [iommu]" : "");
3625 qemu_printf(" alias=%s", s
->mr
->alias
->name
?
3626 s
->mr
->alias
->name
: "noname");
3631 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3632 P_L2_BITS
, P_L2_LEVELS
, d
->phys_map
.ptr
, d
->phys_map
.skip
);
3633 for (i
= 0; i
< d
->map
.nodes_nb
; ++i
) {
3636 Node
*n
= d
->map
.nodes
+ i
;
3638 qemu_printf(" [%d]\n", i
);
3640 for (j
= 0, jprev
= 0, prev
= *n
[0]; j
< ARRAY_SIZE(*n
); ++j
) {
3641 PhysPageEntry
*pe
= *n
+ j
;
3643 if (pe
->ptr
== prev
.ptr
&& pe
->skip
== prev
.skip
) {
3647 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3653 if (jprev
!= ARRAY_SIZE(*n
)) {
3654 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3660 * If positive, discarding RAM is disabled. If negative, discarding RAM is
3661 * required to work and cannot be disabled.
3663 static int ram_block_discard_disabled
;
3665 int ram_block_discard_disable(bool state
)
3670 qatomic_dec(&ram_block_discard_disabled
);
3675 old
= qatomic_read(&ram_block_discard_disabled
);
3679 } while (qatomic_cmpxchg(&ram_block_discard_disabled
,
3680 old
, old
+ 1) != old
);
3684 int ram_block_discard_require(bool state
)
3689 qatomic_inc(&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 bool ram_block_discard_is_disabled(void)
3705 return qatomic_read(&ram_block_discard_disabled
) > 0;
3708 bool ram_block_discard_is_required(void)
3710 return qatomic_read(&ram_block_discard_disabled
) < 0;