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"
27 #include "exec/exec-all.h"
28 #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 "exec/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
= NULL
;
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
,
1406 char *sanitized_name
;
1412 fd
= open(path
, readonly
? O_RDONLY
: O_RDWR
);
1414 /* @path names an existing file, use it */
1417 if (errno
== ENOENT
) {
1418 /* @path names a file that doesn't exist, create it */
1419 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0644);
1424 } else if (errno
== EISDIR
) {
1425 /* @path names a directory, create a file there */
1426 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1427 sanitized_name
= g_strdup(region_name
);
1428 for (c
= sanitized_name
; *c
!= '\0'; c
++) {
1434 filename
= g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path
,
1436 g_free(sanitized_name
);
1438 fd
= mkstemp(filename
);
1446 if (errno
!= EEXIST
&& errno
!= EINTR
) {
1447 error_setg_errno(errp
, errno
,
1448 "can't open backing store %s for guest RAM",
1453 * Try again on EINTR and EEXIST. The latter happens when
1454 * something else creates the file between our two open().
1461 static void *file_ram_alloc(RAMBlock
*block
,
1470 block
->page_size
= qemu_fd_getpagesize(fd
);
1471 if (block
->mr
->align
% block
->page_size
) {
1472 error_setg(errp
, "alignment 0x%" PRIx64
1473 " must be multiples of page size 0x%zx",
1474 block
->mr
->align
, block
->page_size
);
1476 } else if (block
->mr
->align
&& !is_power_of_2(block
->mr
->align
)) {
1477 error_setg(errp
, "alignment 0x%" PRIx64
1478 " must be a power of two", block
->mr
->align
);
1481 block
->mr
->align
= MAX(block
->page_size
, block
->mr
->align
);
1482 #if defined(__s390x__)
1483 if (kvm_enabled()) {
1484 block
->mr
->align
= MAX(block
->mr
->align
, QEMU_VMALLOC_ALIGN
);
1488 if (memory
< block
->page_size
) {
1489 error_setg(errp
, "memory size 0x" RAM_ADDR_FMT
" must be equal to "
1490 "or larger than page size 0x%zx",
1491 memory
, block
->page_size
);
1495 memory
= ROUND_UP(memory
, block
->page_size
);
1498 * ftruncate is not supported by hugetlbfs in older
1499 * hosts, so don't bother bailing out on errors.
1500 * If anything goes wrong with it under other filesystems,
1503 * Do not truncate the non-empty backend file to avoid corrupting
1504 * the existing data in the file. Disabling shrinking is not
1505 * enough. For example, the current vNVDIMM implementation stores
1506 * the guest NVDIMM labels at the end of the backend file. If the
1507 * backend file is later extended, QEMU will not be able to find
1508 * those labels. Therefore, extending the non-empty backend file
1509 * is disabled as well.
1511 if (truncate
&& ftruncate(fd
, memory
)) {
1512 perror("ftruncate");
1515 area
= qemu_ram_mmap(fd
, memory
, block
->mr
->align
, readonly
,
1516 block
->flags
& RAM_SHARED
, block
->flags
& RAM_PMEM
);
1517 if (area
== MAP_FAILED
) {
1518 error_setg_errno(errp
, errno
,
1519 "unable to map backing store for guest RAM");
1528 /* Allocate space within the ram_addr_t space that governs the
1530 * Called with the ramlist lock held.
1532 static ram_addr_t
find_ram_offset(ram_addr_t size
)
1534 RAMBlock
*block
, *next_block
;
1535 ram_addr_t offset
= RAM_ADDR_MAX
, mingap
= RAM_ADDR_MAX
;
1537 assert(size
!= 0); /* it would hand out same offset multiple times */
1539 if (QLIST_EMPTY_RCU(&ram_list
.blocks
)) {
1543 RAMBLOCK_FOREACH(block
) {
1544 ram_addr_t candidate
, next
= RAM_ADDR_MAX
;
1546 /* Align blocks to start on a 'long' in the bitmap
1547 * which makes the bitmap sync'ing take the fast path.
1549 candidate
= block
->offset
+ block
->max_length
;
1550 candidate
= ROUND_UP(candidate
, BITS_PER_LONG
<< TARGET_PAGE_BITS
);
1552 /* Search for the closest following block
1555 RAMBLOCK_FOREACH(next_block
) {
1556 if (next_block
->offset
>= candidate
) {
1557 next
= MIN(next
, next_block
->offset
);
1561 /* If it fits remember our place and remember the size
1562 * of gap, but keep going so that we might find a smaller
1563 * gap to fill so avoiding fragmentation.
1565 if (next
- candidate
>= size
&& next
- candidate
< mingap
) {
1567 mingap
= next
- candidate
;
1570 trace_find_ram_offset_loop(size
, candidate
, offset
, next
, mingap
);
1573 if (offset
== RAM_ADDR_MAX
) {
1574 fprintf(stderr
, "Failed to find gap of requested size: %" PRIu64
"\n",
1579 trace_find_ram_offset(size
, offset
);
1584 static unsigned long last_ram_page(void)
1587 ram_addr_t last
= 0;
1589 RCU_READ_LOCK_GUARD();
1590 RAMBLOCK_FOREACH(block
) {
1591 last
= MAX(last
, block
->offset
+ block
->max_length
);
1593 return last
>> TARGET_PAGE_BITS
;
1596 static void qemu_ram_setup_dump(void *addr
, ram_addr_t size
)
1600 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1601 if (!machine_dump_guest_core(current_machine
)) {
1602 ret
= qemu_madvise(addr
, size
, QEMU_MADV_DONTDUMP
);
1604 perror("qemu_madvise");
1605 fprintf(stderr
, "madvise doesn't support MADV_DONTDUMP, "
1606 "but dump_guest_core=off specified\n");
1611 const char *qemu_ram_get_idstr(RAMBlock
*rb
)
1616 void *qemu_ram_get_host_addr(RAMBlock
*rb
)
1621 ram_addr_t
qemu_ram_get_offset(RAMBlock
*rb
)
1626 ram_addr_t
qemu_ram_get_used_length(RAMBlock
*rb
)
1628 return rb
->used_length
;
1631 bool qemu_ram_is_shared(RAMBlock
*rb
)
1633 return rb
->flags
& RAM_SHARED
;
1636 /* Note: Only set at the start of postcopy */
1637 bool qemu_ram_is_uf_zeroable(RAMBlock
*rb
)
1639 return rb
->flags
& RAM_UF_ZEROPAGE
;
1642 void qemu_ram_set_uf_zeroable(RAMBlock
*rb
)
1644 rb
->flags
|= RAM_UF_ZEROPAGE
;
1647 bool qemu_ram_is_migratable(RAMBlock
*rb
)
1649 return rb
->flags
& RAM_MIGRATABLE
;
1652 void qemu_ram_set_migratable(RAMBlock
*rb
)
1654 rb
->flags
|= RAM_MIGRATABLE
;
1657 void qemu_ram_unset_migratable(RAMBlock
*rb
)
1659 rb
->flags
&= ~RAM_MIGRATABLE
;
1662 /* Called with iothread lock held. */
1663 void qemu_ram_set_idstr(RAMBlock
*new_block
, const char *name
, DeviceState
*dev
)
1668 assert(!new_block
->idstr
[0]);
1671 char *id
= qdev_get_dev_path(dev
);
1673 snprintf(new_block
->idstr
, sizeof(new_block
->idstr
), "%s/", id
);
1677 pstrcat(new_block
->idstr
, sizeof(new_block
->idstr
), name
);
1679 RCU_READ_LOCK_GUARD();
1680 RAMBLOCK_FOREACH(block
) {
1681 if (block
!= new_block
&&
1682 !strcmp(block
->idstr
, new_block
->idstr
)) {
1683 fprintf(stderr
, "RAMBlock \"%s\" already registered, abort!\n",
1690 /* Called with iothread lock held. */
1691 void qemu_ram_unset_idstr(RAMBlock
*block
)
1693 /* FIXME: arch_init.c assumes that this is not called throughout
1694 * migration. Ignore the problem since hot-unplug during migration
1695 * does not work anyway.
1698 memset(block
->idstr
, 0, sizeof(block
->idstr
));
1702 size_t qemu_ram_pagesize(RAMBlock
*rb
)
1704 return rb
->page_size
;
1707 /* Returns the largest size of page in use */
1708 size_t qemu_ram_pagesize_largest(void)
1713 RAMBLOCK_FOREACH(block
) {
1714 largest
= MAX(largest
, qemu_ram_pagesize(block
));
1720 static int memory_try_enable_merging(void *addr
, size_t len
)
1722 if (!machine_mem_merge(current_machine
)) {
1723 /* disabled by the user */
1727 return qemu_madvise(addr
, len
, QEMU_MADV_MERGEABLE
);
1730 /* Only legal before guest might have detected the memory size: e.g. on
1731 * incoming migration, or right after reset.
1733 * As memory core doesn't know how is memory accessed, it is up to
1734 * resize callback to update device state and/or add assertions to detect
1735 * misuse, if necessary.
1737 int qemu_ram_resize(RAMBlock
*block
, ram_addr_t newsize
, Error
**errp
)
1739 const ram_addr_t unaligned_size
= newsize
;
1743 newsize
= HOST_PAGE_ALIGN(newsize
);
1745 if (block
->used_length
== newsize
) {
1747 * We don't have to resize the ram block (which only knows aligned
1748 * sizes), however, we have to notify if the unaligned size changed.
1750 if (unaligned_size
!= memory_region_size(block
->mr
)) {
1751 memory_region_set_size(block
->mr
, unaligned_size
);
1752 if (block
->resized
) {
1753 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1759 if (!(block
->flags
& RAM_RESIZEABLE
)) {
1760 error_setg_errno(errp
, EINVAL
,
1761 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1762 " != 0x" RAM_ADDR_FMT
, block
->idstr
,
1763 newsize
, block
->used_length
);
1767 if (block
->max_length
< newsize
) {
1768 error_setg_errno(errp
, EINVAL
,
1769 "Size too large: %s: 0x" RAM_ADDR_FMT
1770 " > 0x" RAM_ADDR_FMT
, block
->idstr
,
1771 newsize
, block
->max_length
);
1775 cpu_physical_memory_clear_dirty_range(block
->offset
, block
->used_length
);
1776 block
->used_length
= newsize
;
1777 cpu_physical_memory_set_dirty_range(block
->offset
, block
->used_length
,
1779 memory_region_set_size(block
->mr
, unaligned_size
);
1780 if (block
->resized
) {
1781 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1787 * Trigger sync on the given ram block for range [start, start + length]
1788 * with the backing store if one is available.
1790 * @Note: this is supposed to be a synchronous op.
1792 void qemu_ram_msync(RAMBlock
*block
, ram_addr_t start
, ram_addr_t length
)
1794 /* The requested range should fit in within the block range */
1795 g_assert((start
+ length
) <= block
->used_length
);
1797 #ifdef CONFIG_LIBPMEM
1798 /* The lack of support for pmem should not block the sync */
1799 if (ramblock_is_pmem(block
)) {
1800 void *addr
= ramblock_ptr(block
, start
);
1801 pmem_persist(addr
, length
);
1805 if (block
->fd
>= 0) {
1807 * Case there is no support for PMEM or the memory has not been
1808 * specified as persistent (or is not one) - use the msync.
1809 * Less optimal but still achieves the same goal
1811 void *addr
= ramblock_ptr(block
, start
);
1812 if (qemu_msync(addr
, length
, block
->fd
)) {
1813 warn_report("%s: failed to sync memory range: start: "
1814 RAM_ADDR_FMT
" length: " RAM_ADDR_FMT
,
1815 __func__
, start
, length
);
1820 /* Called with ram_list.mutex held */
1821 static void dirty_memory_extend(ram_addr_t old_ram_size
,
1822 ram_addr_t new_ram_size
)
1824 ram_addr_t old_num_blocks
= DIV_ROUND_UP(old_ram_size
,
1825 DIRTY_MEMORY_BLOCK_SIZE
);
1826 ram_addr_t new_num_blocks
= DIV_ROUND_UP(new_ram_size
,
1827 DIRTY_MEMORY_BLOCK_SIZE
);
1830 /* Only need to extend if block count increased */
1831 if (new_num_blocks
<= old_num_blocks
) {
1835 for (i
= 0; i
< DIRTY_MEMORY_NUM
; i
++) {
1836 DirtyMemoryBlocks
*old_blocks
;
1837 DirtyMemoryBlocks
*new_blocks
;
1840 old_blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[i
]);
1841 new_blocks
= g_malloc(sizeof(*new_blocks
) +
1842 sizeof(new_blocks
->blocks
[0]) * new_num_blocks
);
1844 if (old_num_blocks
) {
1845 memcpy(new_blocks
->blocks
, old_blocks
->blocks
,
1846 old_num_blocks
* sizeof(old_blocks
->blocks
[0]));
1849 for (j
= old_num_blocks
; j
< new_num_blocks
; j
++) {
1850 new_blocks
->blocks
[j
] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE
);
1853 qatomic_rcu_set(&ram_list
.dirty_memory
[i
], new_blocks
);
1856 g_free_rcu(old_blocks
, rcu
);
1861 static void ram_block_add(RAMBlock
*new_block
, Error
**errp
, bool shared
)
1864 RAMBlock
*last_block
= NULL
;
1865 ram_addr_t old_ram_size
, new_ram_size
;
1868 old_ram_size
= last_ram_page();
1870 qemu_mutex_lock_ramlist();
1871 new_block
->offset
= find_ram_offset(new_block
->max_length
);
1873 if (!new_block
->host
) {
1874 if (xen_enabled()) {
1875 xen_ram_alloc(new_block
->offset
, new_block
->max_length
,
1876 new_block
->mr
, &err
);
1878 error_propagate(errp
, err
);
1879 qemu_mutex_unlock_ramlist();
1883 new_block
->host
= phys_mem_alloc(new_block
->max_length
,
1884 &new_block
->mr
->align
, shared
);
1885 if (!new_block
->host
) {
1886 error_setg_errno(errp
, errno
,
1887 "cannot set up guest memory '%s'",
1888 memory_region_name(new_block
->mr
));
1889 qemu_mutex_unlock_ramlist();
1892 memory_try_enable_merging(new_block
->host
, new_block
->max_length
);
1896 new_ram_size
= MAX(old_ram_size
,
1897 (new_block
->offset
+ new_block
->max_length
) >> TARGET_PAGE_BITS
);
1898 if (new_ram_size
> old_ram_size
) {
1899 dirty_memory_extend(old_ram_size
, new_ram_size
);
1901 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1902 * QLIST (which has an RCU-friendly variant) does not have insertion at
1903 * tail, so save the last element in last_block.
1905 RAMBLOCK_FOREACH(block
) {
1907 if (block
->max_length
< new_block
->max_length
) {
1912 QLIST_INSERT_BEFORE_RCU(block
, new_block
, next
);
1913 } else if (last_block
) {
1914 QLIST_INSERT_AFTER_RCU(last_block
, new_block
, next
);
1915 } else { /* list is empty */
1916 QLIST_INSERT_HEAD_RCU(&ram_list
.blocks
, new_block
, next
);
1918 ram_list
.mru_block
= NULL
;
1920 /* Write list before version */
1923 qemu_mutex_unlock_ramlist();
1925 cpu_physical_memory_set_dirty_range(new_block
->offset
,
1926 new_block
->used_length
,
1929 if (new_block
->host
) {
1930 qemu_ram_setup_dump(new_block
->host
, new_block
->max_length
);
1931 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_HUGEPAGE
);
1933 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
1934 * Configure it unless the machine is a qtest server, in which case
1935 * KVM is not used and it may be forked (eg for fuzzing purposes).
1937 if (!qtest_enabled()) {
1938 qemu_madvise(new_block
->host
, new_block
->max_length
,
1939 QEMU_MADV_DONTFORK
);
1941 ram_block_notify_add(new_block
->host
, new_block
->max_length
);
1946 RAMBlock
*qemu_ram_alloc_from_fd(ram_addr_t size
, MemoryRegion
*mr
,
1947 uint32_t ram_flags
, int fd
, bool readonly
,
1950 RAMBlock
*new_block
;
1951 Error
*local_err
= NULL
;
1952 int64_t file_size
, file_align
;
1954 /* Just support these ram flags by now. */
1955 assert((ram_flags
& ~(RAM_SHARED
| RAM_PMEM
)) == 0);
1957 if (xen_enabled()) {
1958 error_setg(errp
, "-mem-path not supported with Xen");
1962 if (kvm_enabled() && !kvm_has_sync_mmu()) {
1964 "host lacks kvm mmu notifiers, -mem-path unsupported");
1968 if (phys_mem_alloc
!= qemu_anon_ram_alloc
) {
1970 * file_ram_alloc() needs to allocate just like
1971 * phys_mem_alloc, but we haven't bothered to provide
1975 "-mem-path not supported with this accelerator");
1979 size
= HOST_PAGE_ALIGN(size
);
1980 file_size
= get_file_size(fd
);
1981 if (file_size
> 0 && file_size
< size
) {
1982 error_setg(errp
, "backing store size 0x%" PRIx64
1983 " does not match 'size' option 0x" RAM_ADDR_FMT
,
1988 file_align
= get_file_align(fd
);
1989 if (file_align
> 0 && mr
&& file_align
> mr
->align
) {
1990 error_setg(errp
, "backing store align 0x%" PRIx64
1991 " is larger than 'align' option 0x%" PRIx64
,
1992 file_align
, mr
->align
);
1996 new_block
= g_malloc0(sizeof(*new_block
));
1998 new_block
->used_length
= size
;
1999 new_block
->max_length
= size
;
2000 new_block
->flags
= ram_flags
;
2001 new_block
->host
= file_ram_alloc(new_block
, size
, fd
, readonly
,
2003 if (!new_block
->host
) {
2008 ram_block_add(new_block
, &local_err
, ram_flags
& RAM_SHARED
);
2011 error_propagate(errp
, local_err
);
2019 RAMBlock
*qemu_ram_alloc_from_file(ram_addr_t size
, MemoryRegion
*mr
,
2020 uint32_t ram_flags
, const char *mem_path
,
2021 bool readonly
, Error
**errp
)
2027 fd
= file_ram_open(mem_path
, memory_region_name(mr
), readonly
, &created
,
2033 block
= qemu_ram_alloc_from_fd(size
, mr
, ram_flags
, fd
, readonly
, errp
);
2047 RAMBlock
*qemu_ram_alloc_internal(ram_addr_t size
, ram_addr_t max_size
,
2048 void (*resized
)(const char*,
2051 void *host
, bool resizeable
, bool share
,
2052 MemoryRegion
*mr
, Error
**errp
)
2054 RAMBlock
*new_block
;
2055 Error
*local_err
= NULL
;
2057 size
= HOST_PAGE_ALIGN(size
);
2058 max_size
= HOST_PAGE_ALIGN(max_size
);
2059 new_block
= g_malloc0(sizeof(*new_block
));
2061 new_block
->resized
= resized
;
2062 new_block
->used_length
= size
;
2063 new_block
->max_length
= max_size
;
2064 assert(max_size
>= size
);
2066 new_block
->page_size
= qemu_real_host_page_size
;
2067 new_block
->host
= host
;
2069 new_block
->flags
|= RAM_PREALLOC
;
2072 new_block
->flags
|= RAM_RESIZEABLE
;
2074 ram_block_add(new_block
, &local_err
, share
);
2077 error_propagate(errp
, local_err
);
2083 RAMBlock
*qemu_ram_alloc_from_ptr(ram_addr_t size
, void *host
,
2084 MemoryRegion
*mr
, Error
**errp
)
2086 return qemu_ram_alloc_internal(size
, size
, NULL
, host
, false,
2090 RAMBlock
*qemu_ram_alloc(ram_addr_t size
, bool share
,
2091 MemoryRegion
*mr
, Error
**errp
)
2093 return qemu_ram_alloc_internal(size
, size
, NULL
, NULL
, false,
2097 RAMBlock
*qemu_ram_alloc_resizeable(ram_addr_t size
, ram_addr_t maxsz
,
2098 void (*resized
)(const char*,
2101 MemoryRegion
*mr
, Error
**errp
)
2103 return qemu_ram_alloc_internal(size
, maxsz
, resized
, NULL
, true,
2107 static void reclaim_ramblock(RAMBlock
*block
)
2109 if (block
->flags
& RAM_PREALLOC
) {
2111 } else if (xen_enabled()) {
2112 xen_invalidate_map_cache_entry(block
->host
);
2114 } else if (block
->fd
>= 0) {
2115 qemu_ram_munmap(block
->fd
, block
->host
, block
->max_length
);
2119 qemu_anon_ram_free(block
->host
, block
->max_length
);
2124 void qemu_ram_free(RAMBlock
*block
)
2131 ram_block_notify_remove(block
->host
, block
->max_length
);
2134 qemu_mutex_lock_ramlist();
2135 QLIST_REMOVE_RCU(block
, next
);
2136 ram_list
.mru_block
= NULL
;
2137 /* Write list before version */
2140 call_rcu(block
, reclaim_ramblock
, rcu
);
2141 qemu_mutex_unlock_ramlist();
2145 void qemu_ram_remap(ram_addr_t addr
, ram_addr_t length
)
2152 RAMBLOCK_FOREACH(block
) {
2153 offset
= addr
- block
->offset
;
2154 if (offset
< block
->max_length
) {
2155 vaddr
= ramblock_ptr(block
, offset
);
2156 if (block
->flags
& RAM_PREALLOC
) {
2158 } else if (xen_enabled()) {
2162 if (block
->fd
>= 0) {
2163 flags
|= (block
->flags
& RAM_SHARED
?
2164 MAP_SHARED
: MAP_PRIVATE
);
2165 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2166 flags
, block
->fd
, offset
);
2169 * Remap needs to match alloc. Accelerators that
2170 * set phys_mem_alloc never remap. If they did,
2171 * we'd need a remap hook here.
2173 assert(phys_mem_alloc
== qemu_anon_ram_alloc
);
2175 flags
|= MAP_PRIVATE
| MAP_ANONYMOUS
;
2176 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2179 if (area
!= vaddr
) {
2180 error_report("Could not remap addr: "
2181 RAM_ADDR_FMT
"@" RAM_ADDR_FMT
"",
2185 memory_try_enable_merging(vaddr
, length
);
2186 qemu_ram_setup_dump(vaddr
, length
);
2191 #endif /* !_WIN32 */
2193 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2194 * This should not be used for general purpose DMA. Use address_space_map
2195 * or address_space_rw instead. For local memory (e.g. video ram) that the
2196 * device owns, use memory_region_get_ram_ptr.
2198 * Called within RCU critical section.
2200 void *qemu_map_ram_ptr(RAMBlock
*ram_block
, ram_addr_t addr
)
2202 RAMBlock
*block
= ram_block
;
2204 if (block
== NULL
) {
2205 block
= qemu_get_ram_block(addr
);
2206 addr
-= block
->offset
;
2209 if (xen_enabled() && block
->host
== NULL
) {
2210 /* We need to check if the requested address is in the RAM
2211 * because we don't want to map the entire memory in QEMU.
2212 * In that case just map until the end of the page.
2214 if (block
->offset
== 0) {
2215 return xen_map_cache(addr
, 0, 0, false);
2218 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, false);
2220 return ramblock_ptr(block
, addr
);
2223 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2224 * but takes a size argument.
2226 * Called within RCU critical section.
2228 static void *qemu_ram_ptr_length(RAMBlock
*ram_block
, ram_addr_t addr
,
2229 hwaddr
*size
, bool lock
)
2231 RAMBlock
*block
= ram_block
;
2236 if (block
== NULL
) {
2237 block
= qemu_get_ram_block(addr
);
2238 addr
-= block
->offset
;
2240 *size
= MIN(*size
, block
->max_length
- addr
);
2242 if (xen_enabled() && block
->host
== NULL
) {
2243 /* We need to check if the requested address is in the RAM
2244 * because we don't want to map the entire memory in QEMU.
2245 * In that case just map the requested area.
2247 if (block
->offset
== 0) {
2248 return xen_map_cache(addr
, *size
, lock
, lock
);
2251 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, lock
);
2254 return ramblock_ptr(block
, addr
);
2257 /* Return the offset of a hostpointer within a ramblock */
2258 ram_addr_t
qemu_ram_block_host_offset(RAMBlock
*rb
, void *host
)
2260 ram_addr_t res
= (uint8_t *)host
- (uint8_t *)rb
->host
;
2261 assert((uintptr_t)host
>= (uintptr_t)rb
->host
);
2262 assert(res
< rb
->max_length
);
2268 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2271 * ptr: Host pointer to look up
2272 * round_offset: If true round the result offset down to a page boundary
2273 * *ram_addr: set to result ram_addr
2274 * *offset: set to result offset within the RAMBlock
2276 * Returns: RAMBlock (or NULL if not found)
2278 * By the time this function returns, the returned pointer is not protected
2279 * by RCU anymore. If the caller is not within an RCU critical section and
2280 * does not hold the iothread lock, it must have other means of protecting the
2281 * pointer, such as a reference to the region that includes the incoming
2284 RAMBlock
*qemu_ram_block_from_host(void *ptr
, bool round_offset
,
2288 uint8_t *host
= ptr
;
2290 if (xen_enabled()) {
2291 ram_addr_t ram_addr
;
2292 RCU_READ_LOCK_GUARD();
2293 ram_addr
= xen_ram_addr_from_mapcache(ptr
);
2294 block
= qemu_get_ram_block(ram_addr
);
2296 *offset
= ram_addr
- block
->offset
;
2301 RCU_READ_LOCK_GUARD();
2302 block
= qatomic_rcu_read(&ram_list
.mru_block
);
2303 if (block
&& block
->host
&& host
- block
->host
< block
->max_length
) {
2307 RAMBLOCK_FOREACH(block
) {
2308 /* This case append when the block is not mapped. */
2309 if (block
->host
== NULL
) {
2312 if (host
- block
->host
< block
->max_length
) {
2320 *offset
= (host
- block
->host
);
2322 *offset
&= TARGET_PAGE_MASK
;
2328 * Finds the named RAMBlock
2330 * name: The name of RAMBlock to find
2332 * Returns: RAMBlock (or NULL if not found)
2334 RAMBlock
*qemu_ram_block_by_name(const char *name
)
2338 RAMBLOCK_FOREACH(block
) {
2339 if (!strcmp(name
, block
->idstr
)) {
2347 /* Some of the softmmu routines need to translate from a host pointer
2348 (typically a TLB entry) back to a ram offset. */
2349 ram_addr_t
qemu_ram_addr_from_host(void *ptr
)
2354 block
= qemu_ram_block_from_host(ptr
, false, &offset
);
2356 return RAM_ADDR_INVALID
;
2359 return block
->offset
+ offset
;
2362 /* Generate a debug exception if a watchpoint has been hit. */
2363 void cpu_check_watchpoint(CPUState
*cpu
, vaddr addr
, vaddr len
,
2364 MemTxAttrs attrs
, int flags
, uintptr_t ra
)
2366 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
2369 assert(tcg_enabled());
2370 if (cpu
->watchpoint_hit
) {
2372 * We re-entered the check after replacing the TB.
2373 * Now raise the debug interrupt so that it will
2374 * trigger after the current instruction.
2376 qemu_mutex_lock_iothread();
2377 cpu_interrupt(cpu
, CPU_INTERRUPT_DEBUG
);
2378 qemu_mutex_unlock_iothread();
2382 addr
= cc
->adjust_watchpoint_address(cpu
, addr
, len
);
2383 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
2384 if (watchpoint_address_matches(wp
, addr
, len
)
2385 && (wp
->flags
& flags
)) {
2386 if (replay_running_debug()) {
2388 * Don't process the watchpoints when we are
2389 * in a reverse debugging operation.
2391 replay_breakpoint();
2394 if (flags
== BP_MEM_READ
) {
2395 wp
->flags
|= BP_WATCHPOINT_HIT_READ
;
2397 wp
->flags
|= BP_WATCHPOINT_HIT_WRITE
;
2399 wp
->hitaddr
= MAX(addr
, wp
->vaddr
);
2400 wp
->hitattrs
= attrs
;
2401 if (!cpu
->watchpoint_hit
) {
2402 if (wp
->flags
& BP_CPU
&&
2403 !cc
->debug_check_watchpoint(cpu
, wp
)) {
2404 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
2407 cpu
->watchpoint_hit
= wp
;
2410 tb_check_watchpoint(cpu
, ra
);
2411 if (wp
->flags
& BP_STOP_BEFORE_ACCESS
) {
2412 cpu
->exception_index
= EXCP_DEBUG
;
2414 cpu_loop_exit_restore(cpu
, ra
);
2416 /* Force execution of one insn next time. */
2417 cpu
->cflags_next_tb
= 1 | curr_cflags();
2420 cpu_restore_state(cpu
, ra
, true);
2422 cpu_loop_exit_noexc(cpu
);
2426 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
2431 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2432 MemTxAttrs attrs
, void *buf
, hwaddr len
);
2433 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2434 const void *buf
, hwaddr len
);
2435 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
2436 bool is_write
, MemTxAttrs attrs
);
2438 static MemTxResult
subpage_read(void *opaque
, hwaddr addr
, uint64_t *data
,
2439 unsigned len
, MemTxAttrs attrs
)
2441 subpage_t
*subpage
= opaque
;
2445 #if defined(DEBUG_SUBPAGE)
2446 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
"\n", __func__
,
2447 subpage
, len
, addr
);
2449 res
= flatview_read(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2453 *data
= ldn_p(buf
, len
);
2457 static MemTxResult
subpage_write(void *opaque
, hwaddr addr
,
2458 uint64_t value
, unsigned len
, MemTxAttrs attrs
)
2460 subpage_t
*subpage
= opaque
;
2463 #if defined(DEBUG_SUBPAGE)
2464 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2465 " value %"PRIx64
"\n",
2466 __func__
, subpage
, len
, addr
, value
);
2468 stn_p(buf
, len
, value
);
2469 return flatview_write(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2472 static bool subpage_accepts(void *opaque
, hwaddr addr
,
2473 unsigned len
, bool is_write
,
2476 subpage_t
*subpage
= opaque
;
2477 #if defined(DEBUG_SUBPAGE)
2478 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx
"\n",
2479 __func__
, subpage
, is_write
? 'w' : 'r', len
, addr
);
2482 return flatview_access_valid(subpage
->fv
, addr
+ subpage
->base
,
2483 len
, is_write
, attrs
);
2486 static const MemoryRegionOps subpage_ops
= {
2487 .read_with_attrs
= subpage_read
,
2488 .write_with_attrs
= subpage_write
,
2489 .impl
.min_access_size
= 1,
2490 .impl
.max_access_size
= 8,
2491 .valid
.min_access_size
= 1,
2492 .valid
.max_access_size
= 8,
2493 .valid
.accepts
= subpage_accepts
,
2494 .endianness
= DEVICE_NATIVE_ENDIAN
,
2497 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
2502 if (start
>= TARGET_PAGE_SIZE
|| end
>= TARGET_PAGE_SIZE
)
2504 idx
= SUBPAGE_IDX(start
);
2505 eidx
= SUBPAGE_IDX(end
);
2506 #if defined(DEBUG_SUBPAGE)
2507 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2508 __func__
, mmio
, start
, end
, idx
, eidx
, section
);
2510 for (; idx
<= eidx
; idx
++) {
2511 mmio
->sub_section
[idx
] = section
;
2517 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
)
2521 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2522 mmio
= g_malloc0(sizeof(subpage_t
) + TARGET_PAGE_SIZE
* sizeof(uint16_t));
2525 memory_region_init_io(&mmio
->iomem
, NULL
, &subpage_ops
, mmio
,
2526 NULL
, TARGET_PAGE_SIZE
);
2527 mmio
->iomem
.subpage
= true;
2528 #if defined(DEBUG_SUBPAGE)
2529 printf("%s: %p base " TARGET_FMT_plx
" len %08x\n", __func__
,
2530 mmio
, base
, TARGET_PAGE_SIZE
);
2536 static uint16_t dummy_section(PhysPageMap
*map
, FlatView
*fv
, MemoryRegion
*mr
)
2539 MemoryRegionSection section
= {
2542 .offset_within_address_space
= 0,
2543 .offset_within_region
= 0,
2544 .size
= int128_2_64(),
2547 return phys_section_add(map
, §ion
);
2550 MemoryRegionSection
*iotlb_to_section(CPUState
*cpu
,
2551 hwaddr index
, MemTxAttrs attrs
)
2553 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
2554 CPUAddressSpace
*cpuas
= &cpu
->cpu_ases
[asidx
];
2555 AddressSpaceDispatch
*d
= qatomic_rcu_read(&cpuas
->memory_dispatch
);
2556 MemoryRegionSection
*sections
= d
->map
.sections
;
2558 return §ions
[index
& ~TARGET_PAGE_MASK
];
2561 static void io_mem_init(void)
2563 memory_region_init_io(&io_mem_unassigned
, NULL
, &unassigned_mem_ops
, NULL
,
2567 AddressSpaceDispatch
*address_space_dispatch_new(FlatView
*fv
)
2569 AddressSpaceDispatch
*d
= g_new0(AddressSpaceDispatch
, 1);
2572 n
= dummy_section(&d
->map
, fv
, &io_mem_unassigned
);
2573 assert(n
== PHYS_SECTION_UNASSIGNED
);
2575 d
->phys_map
= (PhysPageEntry
) { .ptr
= PHYS_MAP_NODE_NIL
, .skip
= 1 };
2580 void address_space_dispatch_free(AddressSpaceDispatch
*d
)
2582 phys_sections_free(&d
->map
);
2586 static void do_nothing(CPUState
*cpu
, run_on_cpu_data d
)
2590 static void tcg_log_global_after_sync(MemoryListener
*listener
)
2592 CPUAddressSpace
*cpuas
;
2594 /* Wait for the CPU to end the current TB. This avoids the following
2598 * ---------------------- -------------------------
2599 * TLB check -> slow path
2600 * notdirty_mem_write
2604 * TLB check -> fast path
2608 * by pushing the migration thread's memory read after the vCPU thread has
2609 * written the memory.
2611 if (replay_mode
== REPLAY_MODE_NONE
) {
2613 * VGA can make calls to this function while updating the screen.
2614 * In record/replay mode this causes a deadlock, because
2615 * run_on_cpu waits for rr mutex. Therefore no races are possible
2616 * in this case and no need for making run_on_cpu when
2617 * record/replay is not enabled.
2619 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2620 run_on_cpu(cpuas
->cpu
, do_nothing
, RUN_ON_CPU_NULL
);
2624 static void tcg_commit(MemoryListener
*listener
)
2626 CPUAddressSpace
*cpuas
;
2627 AddressSpaceDispatch
*d
;
2629 assert(tcg_enabled());
2630 /* since each CPU stores ram addresses in its TLB cache, we must
2631 reset the modified entries */
2632 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2633 cpu_reloading_memory_map();
2634 /* The CPU and TLB are protected by the iothread lock.
2635 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2636 * may have split the RCU critical section.
2638 d
= address_space_to_dispatch(cpuas
->as
);
2639 qatomic_rcu_set(&cpuas
->memory_dispatch
, d
);
2640 tlb_flush(cpuas
->cpu
);
2643 static void memory_map_init(void)
2645 system_memory
= g_malloc(sizeof(*system_memory
));
2647 memory_region_init(system_memory
, NULL
, "system", UINT64_MAX
);
2648 address_space_init(&address_space_memory
, system_memory
, "memory");
2650 system_io
= g_malloc(sizeof(*system_io
));
2651 memory_region_init_io(system_io
, NULL
, &unassigned_io_ops
, NULL
, "io",
2653 address_space_init(&address_space_io
, system_io
, "I/O");
2656 MemoryRegion
*get_system_memory(void)
2658 return system_memory
;
2661 MemoryRegion
*get_system_io(void)
2666 static void invalidate_and_set_dirty(MemoryRegion
*mr
, hwaddr addr
,
2669 uint8_t dirty_log_mask
= memory_region_get_dirty_log_mask(mr
);
2670 addr
+= memory_region_get_ram_addr(mr
);
2672 /* No early return if dirty_log_mask is or becomes 0, because
2673 * cpu_physical_memory_set_dirty_range will still call
2674 * xen_modified_memory.
2676 if (dirty_log_mask
) {
2678 cpu_physical_memory_range_includes_clean(addr
, length
, dirty_log_mask
);
2680 if (dirty_log_mask
& (1 << DIRTY_MEMORY_CODE
)) {
2681 assert(tcg_enabled());
2682 tb_invalidate_phys_range(addr
, addr
+ length
);
2683 dirty_log_mask
&= ~(1 << DIRTY_MEMORY_CODE
);
2685 cpu_physical_memory_set_dirty_range(addr
, length
, dirty_log_mask
);
2688 void memory_region_flush_rom_device(MemoryRegion
*mr
, hwaddr addr
, hwaddr size
)
2691 * In principle this function would work on other memory region types too,
2692 * but the ROM device use case is the only one where this operation is
2693 * necessary. Other memory regions should use the
2694 * address_space_read/write() APIs.
2696 assert(memory_region_is_romd(mr
));
2698 invalidate_and_set_dirty(mr
, addr
, size
);
2701 static int memory_access_size(MemoryRegion
*mr
, unsigned l
, hwaddr addr
)
2703 unsigned access_size_max
= mr
->ops
->valid
.max_access_size
;
2705 /* Regions are assumed to support 1-4 byte accesses unless
2706 otherwise specified. */
2707 if (access_size_max
== 0) {
2708 access_size_max
= 4;
2711 /* Bound the maximum access by the alignment of the address. */
2712 if (!mr
->ops
->impl
.unaligned
) {
2713 unsigned align_size_max
= addr
& -addr
;
2714 if (align_size_max
!= 0 && align_size_max
< access_size_max
) {
2715 access_size_max
= align_size_max
;
2719 /* Don't attempt accesses larger than the maximum. */
2720 if (l
> access_size_max
) {
2721 l
= access_size_max
;
2728 static bool prepare_mmio_access(MemoryRegion
*mr
)
2730 bool release_lock
= false;
2732 if (!qemu_mutex_iothread_locked()) {
2733 qemu_mutex_lock_iothread();
2734 release_lock
= true;
2736 if (mr
->flush_coalesced_mmio
) {
2737 qemu_flush_coalesced_mmio_buffer();
2740 return release_lock
;
2743 /* Called within RCU critical section. */
2744 static MemTxResult
flatview_write_continue(FlatView
*fv
, hwaddr addr
,
2747 hwaddr len
, hwaddr addr1
,
2748 hwaddr l
, MemoryRegion
*mr
)
2752 MemTxResult result
= MEMTX_OK
;
2753 bool release_lock
= false;
2754 const uint8_t *buf
= ptr
;
2757 if (!memory_access_is_direct(mr
, true)) {
2758 release_lock
|= prepare_mmio_access(mr
);
2759 l
= memory_access_size(mr
, l
, addr1
);
2760 /* XXX: could force current_cpu to NULL to avoid
2762 val
= ldn_he_p(buf
, l
);
2763 result
|= memory_region_dispatch_write(mr
, addr1
, val
,
2764 size_memop(l
), attrs
);
2767 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2768 memcpy(ram_ptr
, buf
, l
);
2769 invalidate_and_set_dirty(mr
, addr1
, l
);
2773 qemu_mutex_unlock_iothread();
2774 release_lock
= false;
2786 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2792 /* Called from RCU critical section. */
2793 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2794 const void *buf
, hwaddr len
)
2799 MemTxResult result
= MEMTX_OK
;
2802 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2803 result
= flatview_write_continue(fv
, addr
, attrs
, buf
, len
,
2809 /* Called within RCU critical section. */
2810 MemTxResult
flatview_read_continue(FlatView
*fv
, hwaddr addr
,
2811 MemTxAttrs attrs
, void *ptr
,
2812 hwaddr len
, hwaddr addr1
, hwaddr l
,
2817 MemTxResult result
= MEMTX_OK
;
2818 bool release_lock
= false;
2822 if (!memory_access_is_direct(mr
, false)) {
2824 release_lock
|= prepare_mmio_access(mr
);
2825 l
= memory_access_size(mr
, l
, addr1
);
2826 result
|= memory_region_dispatch_read(mr
, addr1
, &val
,
2827 size_memop(l
), attrs
);
2828 stn_he_p(buf
, l
, val
);
2831 fuzz_dma_read_cb(addr
, len
, mr
, false);
2832 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2833 memcpy(buf
, ram_ptr
, l
);
2837 qemu_mutex_unlock_iothread();
2838 release_lock
= false;
2850 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2856 /* Called from RCU critical section. */
2857 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2858 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2865 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2866 return flatview_read_continue(fv
, addr
, attrs
, buf
, len
,
2870 MemTxResult
address_space_read_full(AddressSpace
*as
, hwaddr addr
,
2871 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2873 MemTxResult result
= MEMTX_OK
;
2877 RCU_READ_LOCK_GUARD();
2878 fv
= address_space_to_flatview(as
);
2879 result
= flatview_read(fv
, addr
, attrs
, buf
, len
);
2885 MemTxResult
address_space_write(AddressSpace
*as
, hwaddr addr
,
2887 const void *buf
, hwaddr len
)
2889 MemTxResult result
= MEMTX_OK
;
2893 RCU_READ_LOCK_GUARD();
2894 fv
= address_space_to_flatview(as
);
2895 result
= flatview_write(fv
, addr
, attrs
, buf
, len
);
2901 MemTxResult
address_space_rw(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
,
2902 void *buf
, hwaddr len
, bool is_write
)
2905 return address_space_write(as
, addr
, attrs
, buf
, len
);
2907 return address_space_read_full(as
, addr
, attrs
, buf
, len
);
2911 void cpu_physical_memory_rw(hwaddr addr
, void *buf
,
2912 hwaddr len
, bool is_write
)
2914 address_space_rw(&address_space_memory
, addr
, MEMTXATTRS_UNSPECIFIED
,
2915 buf
, len
, is_write
);
2918 enum write_rom_type
{
2923 static inline MemTxResult
address_space_write_rom_internal(AddressSpace
*as
,
2928 enum write_rom_type type
)
2934 const uint8_t *buf
= ptr
;
2936 RCU_READ_LOCK_GUARD();
2939 mr
= address_space_translate(as
, addr
, &addr1
, &l
, true, attrs
);
2941 if (!(memory_region_is_ram(mr
) ||
2942 memory_region_is_romd(mr
))) {
2943 l
= memory_access_size(mr
, l
, addr1
);
2946 ram_ptr
= qemu_map_ram_ptr(mr
->ram_block
, addr1
);
2949 memcpy(ram_ptr
, buf
, l
);
2950 invalidate_and_set_dirty(mr
, addr1
, l
);
2953 flush_idcache_range((uintptr_t)ram_ptr
, (uintptr_t)ram_ptr
, l
);
2964 /* used for ROM loading : can write in RAM and ROM */
2965 MemTxResult
address_space_write_rom(AddressSpace
*as
, hwaddr addr
,
2967 const void *buf
, hwaddr len
)
2969 return address_space_write_rom_internal(as
, addr
, attrs
,
2970 buf
, len
, WRITE_DATA
);
2973 void cpu_flush_icache_range(hwaddr start
, hwaddr len
)
2976 * This function should do the same thing as an icache flush that was
2977 * triggered from within the guest. For TCG we are always cache coherent,
2978 * so there is no need to flush anything. For KVM / Xen we need to flush
2979 * the host's instruction cache at least.
2981 if (tcg_enabled()) {
2985 address_space_write_rom_internal(&address_space_memory
,
2986 start
, MEMTXATTRS_UNSPECIFIED
,
2987 NULL
, len
, FLUSH_CACHE
);
2998 static BounceBuffer bounce
;
3000 typedef struct MapClient
{
3002 QLIST_ENTRY(MapClient
) link
;
3005 QemuMutex map_client_list_lock
;
3006 static QLIST_HEAD(, MapClient
) map_client_list
3007 = QLIST_HEAD_INITIALIZER(map_client_list
);
3009 static void cpu_unregister_map_client_do(MapClient
*client
)
3011 QLIST_REMOVE(client
, link
);
3015 static void cpu_notify_map_clients_locked(void)
3019 while (!QLIST_EMPTY(&map_client_list
)) {
3020 client
= QLIST_FIRST(&map_client_list
);
3021 qemu_bh_schedule(client
->bh
);
3022 cpu_unregister_map_client_do(client
);
3026 void cpu_register_map_client(QEMUBH
*bh
)
3028 MapClient
*client
= g_malloc(sizeof(*client
));
3030 qemu_mutex_lock(&map_client_list_lock
);
3032 QLIST_INSERT_HEAD(&map_client_list
, client
, link
);
3033 if (!qatomic_read(&bounce
.in_use
)) {
3034 cpu_notify_map_clients_locked();
3036 qemu_mutex_unlock(&map_client_list_lock
);
3039 void cpu_exec_init_all(void)
3041 qemu_mutex_init(&ram_list
.mutex
);
3042 /* The data structures we set up here depend on knowing the page size,
3043 * so no more changes can be made after this point.
3044 * In an ideal world, nothing we did before we had finished the
3045 * machine setup would care about the target page size, and we could
3046 * do this much later, rather than requiring board models to state
3047 * up front what their requirements are.
3049 finalize_target_page_bits();
3052 qemu_mutex_init(&map_client_list_lock
);
3055 void cpu_unregister_map_client(QEMUBH
*bh
)
3059 qemu_mutex_lock(&map_client_list_lock
);
3060 QLIST_FOREACH(client
, &map_client_list
, link
) {
3061 if (client
->bh
== bh
) {
3062 cpu_unregister_map_client_do(client
);
3066 qemu_mutex_unlock(&map_client_list_lock
);
3069 static void cpu_notify_map_clients(void)
3071 qemu_mutex_lock(&map_client_list_lock
);
3072 cpu_notify_map_clients_locked();
3073 qemu_mutex_unlock(&map_client_list_lock
);
3076 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
3077 bool is_write
, MemTxAttrs attrs
)
3084 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3085 if (!memory_access_is_direct(mr
, is_write
)) {
3086 l
= memory_access_size(mr
, l
, addr
);
3087 if (!memory_region_access_valid(mr
, xlat
, l
, is_write
, attrs
)) {
3098 bool address_space_access_valid(AddressSpace
*as
, hwaddr addr
,
3099 hwaddr len
, bool is_write
,
3105 RCU_READ_LOCK_GUARD();
3106 fv
= address_space_to_flatview(as
);
3107 result
= flatview_access_valid(fv
, addr
, len
, is_write
, attrs
);
3112 flatview_extend_translation(FlatView
*fv
, hwaddr addr
,
3114 MemoryRegion
*mr
, hwaddr base
, hwaddr len
,
3115 bool is_write
, MemTxAttrs attrs
)
3119 MemoryRegion
*this_mr
;
3125 if (target_len
== 0) {
3130 this_mr
= flatview_translate(fv
, addr
, &xlat
,
3131 &len
, is_write
, attrs
);
3132 if (this_mr
!= mr
|| xlat
!= base
+ done
) {
3138 /* Map a physical memory region into a host virtual address.
3139 * May map a subset of the requested range, given by and returned in *plen.
3140 * May return NULL if resources needed to perform the mapping are exhausted.
3141 * Use only for reads OR writes - not for read-modify-write operations.
3142 * Use cpu_register_map_client() to know when retrying the map operation is
3143 * likely to succeed.
3145 void *address_space_map(AddressSpace
*as
,
3162 RCU_READ_LOCK_GUARD();
3163 fv
= address_space_to_flatview(as
);
3164 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3166 if (!memory_access_is_direct(mr
, is_write
)) {
3167 if (qatomic_xchg(&bounce
.in_use
, true)) {
3171 /* Avoid unbounded allocations */
3172 l
= MIN(l
, TARGET_PAGE_SIZE
);
3173 bounce
.buffer
= qemu_memalign(TARGET_PAGE_SIZE
, l
);
3177 memory_region_ref(mr
);
3180 flatview_read(fv
, addr
, MEMTXATTRS_UNSPECIFIED
,
3185 return bounce
.buffer
;
3189 memory_region_ref(mr
);
3190 *plen
= flatview_extend_translation(fv
, addr
, len
, mr
, xlat
,
3191 l
, is_write
, attrs
);
3192 fuzz_dma_read_cb(addr
, *plen
, mr
, is_write
);
3193 ptr
= qemu_ram_ptr_length(mr
->ram_block
, xlat
, plen
, true);
3198 /* Unmaps a memory region previously mapped by address_space_map().
3199 * Will also mark the memory as dirty if is_write is true. access_len gives
3200 * the amount of memory that was actually read or written by the caller.
3202 void address_space_unmap(AddressSpace
*as
, void *buffer
, hwaddr len
,
3203 bool is_write
, hwaddr access_len
)
3205 if (buffer
!= bounce
.buffer
) {
3209 mr
= memory_region_from_host(buffer
, &addr1
);
3212 invalidate_and_set_dirty(mr
, addr1
, access_len
);
3214 if (xen_enabled()) {
3215 xen_invalidate_map_cache_entry(buffer
);
3217 memory_region_unref(mr
);
3221 address_space_write(as
, bounce
.addr
, MEMTXATTRS_UNSPECIFIED
,
3222 bounce
.buffer
, access_len
);
3224 qemu_vfree(bounce
.buffer
);
3225 bounce
.buffer
= NULL
;
3226 memory_region_unref(bounce
.mr
);
3227 qatomic_mb_set(&bounce
.in_use
, false);
3228 cpu_notify_map_clients();
3231 void *cpu_physical_memory_map(hwaddr addr
,
3235 return address_space_map(&address_space_memory
, addr
, plen
, is_write
,
3236 MEMTXATTRS_UNSPECIFIED
);
3239 void cpu_physical_memory_unmap(void *buffer
, hwaddr len
,
3240 bool is_write
, hwaddr access_len
)
3242 return address_space_unmap(&address_space_memory
, buffer
, len
, is_write
, access_len
);
3245 #define ARG1_DECL AddressSpace *as
3248 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3249 #define RCU_READ_LOCK(...) rcu_read_lock()
3250 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3251 #include "memory_ldst.c.inc"
3253 int64_t address_space_cache_init(MemoryRegionCache
*cache
,
3259 AddressSpaceDispatch
*d
;
3267 cache
->fv
= address_space_get_flatview(as
);
3268 d
= flatview_to_dispatch(cache
->fv
);
3269 cache
->mrs
= *address_space_translate_internal(d
, addr
, &cache
->xlat
, &l
, true);
3272 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3273 * Take that into account to compute how many bytes are there between
3274 * cache->xlat and the end of the section.
3276 diff
= int128_sub(cache
->mrs
.size
,
3277 int128_make64(cache
->xlat
- cache
->mrs
.offset_within_region
));
3278 l
= int128_get64(int128_min(diff
, int128_make64(l
)));
3281 memory_region_ref(mr
);
3282 if (memory_access_is_direct(mr
, is_write
)) {
3283 /* We don't care about the memory attributes here as we're only
3284 * doing this if we found actual RAM, which behaves the same
3285 * regardless of attributes; so UNSPECIFIED is fine.
3287 l
= flatview_extend_translation(cache
->fv
, addr
, len
, mr
,
3288 cache
->xlat
, l
, is_write
,
3289 MEMTXATTRS_UNSPECIFIED
);
3290 cache
->ptr
= qemu_ram_ptr_length(mr
->ram_block
, cache
->xlat
, &l
, true);
3296 cache
->is_write
= is_write
;
3300 void address_space_cache_invalidate(MemoryRegionCache
*cache
,
3304 assert(cache
->is_write
);
3305 if (likely(cache
->ptr
)) {
3306 invalidate_and_set_dirty(cache
->mrs
.mr
, addr
+ cache
->xlat
, access_len
);
3310 void address_space_cache_destroy(MemoryRegionCache
*cache
)
3312 if (!cache
->mrs
.mr
) {
3316 if (xen_enabled()) {
3317 xen_invalidate_map_cache_entry(cache
->ptr
);
3319 memory_region_unref(cache
->mrs
.mr
);
3320 flatview_unref(cache
->fv
);
3321 cache
->mrs
.mr
= NULL
;
3325 /* Called from RCU critical section. This function has the same
3326 * semantics as address_space_translate, but it only works on a
3327 * predefined range of a MemoryRegion that was mapped with
3328 * address_space_cache_init.
3330 static inline MemoryRegion
*address_space_translate_cached(
3331 MemoryRegionCache
*cache
, hwaddr addr
, hwaddr
*xlat
,
3332 hwaddr
*plen
, bool is_write
, MemTxAttrs attrs
)
3334 MemoryRegionSection section
;
3336 IOMMUMemoryRegion
*iommu_mr
;
3337 AddressSpace
*target_as
;
3339 assert(!cache
->ptr
);
3340 *xlat
= addr
+ cache
->xlat
;
3343 iommu_mr
= memory_region_get_iommu(mr
);
3349 section
= address_space_translate_iommu(iommu_mr
, xlat
, plen
,
3350 NULL
, is_write
, true,
3355 /* Called from RCU critical section. address_space_read_cached uses this
3356 * out of line function when the target is an MMIO or IOMMU region.
3359 address_space_read_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3360 void *buf
, hwaddr len
)
3366 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, false,
3367 MEMTXATTRS_UNSPECIFIED
);
3368 return flatview_read_continue(cache
->fv
,
3369 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3373 /* Called from RCU critical section. address_space_write_cached uses this
3374 * out of line function when the target is an MMIO or IOMMU region.
3377 address_space_write_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3378 const void *buf
, hwaddr len
)
3384 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, true,
3385 MEMTXATTRS_UNSPECIFIED
);
3386 return flatview_write_continue(cache
->fv
,
3387 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3391 #define ARG1_DECL MemoryRegionCache *cache
3393 #define SUFFIX _cached_slow
3394 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3395 #define RCU_READ_LOCK() ((void)0)
3396 #define RCU_READ_UNLOCK() ((void)0)
3397 #include "memory_ldst.c.inc"
3399 /* virtual memory access for debug (includes writing to ROM) */
3400 int cpu_memory_rw_debug(CPUState
*cpu
, target_ulong addr
,
3401 void *ptr
, target_ulong len
, bool is_write
)
3404 target_ulong l
, page
;
3407 cpu_synchronize_state(cpu
);
3413 page
= addr
& TARGET_PAGE_MASK
;
3414 phys_addr
= cpu_get_phys_page_attrs_debug(cpu
, page
, &attrs
);
3415 asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
3416 /* if no physical page mapped, return an error */
3417 if (phys_addr
== -1)
3419 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3422 phys_addr
+= (addr
& ~TARGET_PAGE_MASK
);
3424 res
= address_space_write_rom(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3427 res
= address_space_read(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3430 if (res
!= MEMTX_OK
) {
3441 * Allows code that needs to deal with migration bitmaps etc to still be built
3442 * target independent.
3444 size_t qemu_target_page_size(void)
3446 return TARGET_PAGE_SIZE
;
3449 int qemu_target_page_bits(void)
3451 return TARGET_PAGE_BITS
;
3454 int qemu_target_page_bits_min(void)
3456 return TARGET_PAGE_BITS_MIN
;
3459 bool cpu_physical_memory_is_io(hwaddr phys_addr
)
3465 RCU_READ_LOCK_GUARD();
3466 mr
= address_space_translate(&address_space_memory
,
3467 phys_addr
, &phys_addr
, &l
, false,
3468 MEMTXATTRS_UNSPECIFIED
);
3470 res
= !(memory_region_is_ram(mr
) || memory_region_is_romd(mr
));
3474 int qemu_ram_foreach_block(RAMBlockIterFunc func
, void *opaque
)
3479 RCU_READ_LOCK_GUARD();
3480 RAMBLOCK_FOREACH(block
) {
3481 ret
= func(block
, opaque
);
3490 * Unmap pages of memory from start to start+length such that
3491 * they a) read as 0, b) Trigger whatever fault mechanism
3492 * the OS provides for postcopy.
3493 * The pages must be unmapped by the end of the function.
3494 * Returns: 0 on success, none-0 on failure
3497 int ram_block_discard_range(RAMBlock
*rb
, uint64_t start
, size_t length
)
3501 uint8_t *host_startaddr
= rb
->host
+ start
;
3503 if (!QEMU_PTR_IS_ALIGNED(host_startaddr
, rb
->page_size
)) {
3504 error_report("ram_block_discard_range: Unaligned start address: %p",
3509 if ((start
+ length
) <= rb
->used_length
) {
3510 bool need_madvise
, need_fallocate
;
3511 if (!QEMU_IS_ALIGNED(length
, rb
->page_size
)) {
3512 error_report("ram_block_discard_range: Unaligned length: %zx",
3517 errno
= ENOTSUP
; /* If we are missing MADVISE etc */
3519 /* The logic here is messy;
3520 * madvise DONTNEED fails for hugepages
3521 * fallocate works on hugepages and shmem
3523 need_madvise
= (rb
->page_size
== qemu_host_page_size
);
3524 need_fallocate
= rb
->fd
!= -1;
3525 if (need_fallocate
) {
3526 /* For a file, this causes the area of the file to be zero'd
3527 * if read, and for hugetlbfs also causes it to be unmapped
3528 * so a userfault will trigger.
3530 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3531 ret
= fallocate(rb
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3535 error_report("ram_block_discard_range: Failed to fallocate "
3536 "%s:%" PRIx64
" +%zx (%d)",
3537 rb
->idstr
, start
, length
, ret
);
3542 error_report("ram_block_discard_range: fallocate not available/file"
3543 "%s:%" PRIx64
" +%zx (%d)",
3544 rb
->idstr
, start
, length
, ret
);
3549 /* For normal RAM this causes it to be unmapped,
3550 * for shared memory it causes the local mapping to disappear
3551 * and to fall back on the file contents (which we just
3552 * fallocate'd away).
3554 #if defined(CONFIG_MADVISE)
3555 ret
= madvise(host_startaddr
, length
, MADV_DONTNEED
);
3558 error_report("ram_block_discard_range: Failed to discard range "
3559 "%s:%" PRIx64
" +%zx (%d)",
3560 rb
->idstr
, start
, length
, ret
);
3565 error_report("ram_block_discard_range: MADVISE not available"
3566 "%s:%" PRIx64
" +%zx (%d)",
3567 rb
->idstr
, start
, length
, ret
);
3571 trace_ram_block_discard_range(rb
->idstr
, host_startaddr
, length
,
3572 need_madvise
, need_fallocate
, ret
);
3574 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3575 "/%zx/" RAM_ADDR_FMT
")",
3576 rb
->idstr
, start
, length
, rb
->used_length
);
3583 bool ramblock_is_pmem(RAMBlock
*rb
)
3585 return rb
->flags
& RAM_PMEM
;
3588 static void mtree_print_phys_entries(int start
, int end
, int skip
, int ptr
)
3590 if (start
== end
- 1) {
3591 qemu_printf("\t%3d ", start
);
3593 qemu_printf("\t%3d..%-3d ", start
, end
- 1);
3595 qemu_printf(" skip=%d ", skip
);
3596 if (ptr
== PHYS_MAP_NODE_NIL
) {
3597 qemu_printf(" ptr=NIL");
3599 qemu_printf(" ptr=#%d", ptr
);
3601 qemu_printf(" ptr=[%d]", ptr
);
3606 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3607 int128_sub((size), int128_one())) : 0)
3609 void mtree_print_dispatch(AddressSpaceDispatch
*d
, MemoryRegion
*root
)
3613 qemu_printf(" Dispatch\n");
3614 qemu_printf(" Physical sections\n");
3616 for (i
= 0; i
< d
->map
.sections_nb
; ++i
) {
3617 MemoryRegionSection
*s
= d
->map
.sections
+ i
;
3618 const char *names
[] = { " [unassigned]", " [not dirty]",
3619 " [ROM]", " [watch]" };
3621 qemu_printf(" #%d @" TARGET_FMT_plx
".." TARGET_FMT_plx
3624 s
->offset_within_address_space
,
3625 s
->offset_within_address_space
+ MR_SIZE(s
->mr
->size
),
3626 s
->mr
->name
? s
->mr
->name
: "(noname)",
3627 i
< ARRAY_SIZE(names
) ? names
[i
] : "",
3628 s
->mr
== root
? " [ROOT]" : "",
3629 s
== d
->mru_section
? " [MRU]" : "",
3630 s
->mr
->is_iommu
? " [iommu]" : "");
3633 qemu_printf(" alias=%s", s
->mr
->alias
->name
?
3634 s
->mr
->alias
->name
: "noname");
3639 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3640 P_L2_BITS
, P_L2_LEVELS
, d
->phys_map
.ptr
, d
->phys_map
.skip
);
3641 for (i
= 0; i
< d
->map
.nodes_nb
; ++i
) {
3644 Node
*n
= d
->map
.nodes
+ i
;
3646 qemu_printf(" [%d]\n", i
);
3648 for (j
= 0, jprev
= 0, prev
= *n
[0]; j
< ARRAY_SIZE(*n
); ++j
) {
3649 PhysPageEntry
*pe
= *n
+ j
;
3651 if (pe
->ptr
== prev
.ptr
&& pe
->skip
== prev
.skip
) {
3655 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3661 if (jprev
!= ARRAY_SIZE(*n
)) {
3662 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3668 * If positive, discarding RAM is disabled. If negative, discarding RAM is
3669 * required to work and cannot be disabled.
3671 static int ram_block_discard_disabled
;
3673 int ram_block_discard_disable(bool state
)
3678 qatomic_dec(&ram_block_discard_disabled
);
3683 old
= qatomic_read(&ram_block_discard_disabled
);
3687 } while (qatomic_cmpxchg(&ram_block_discard_disabled
,
3688 old
, old
+ 1) != old
);
3692 int ram_block_discard_require(bool state
)
3697 qatomic_inc(&ram_block_discard_disabled
);
3702 old
= qatomic_read(&ram_block_discard_disabled
);
3706 } while (qatomic_cmpxchg(&ram_block_discard_disabled
,
3707 old
, old
- 1) != old
);
3711 bool ram_block_discard_is_disabled(void)
3713 return qatomic_read(&ram_block_discard_disabled
) > 0;
3716 bool ram_block_discard_is_required(void)
3718 return qatomic_read(&ram_block_discard_disabled
) < 0;