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 #if !defined(CONFIG_USER_ONLY)
32 #include "hw/boards.h"
33 #include "hw/xen/xen.h"
35 #include "sysemu/kvm.h"
36 #include "sysemu/sysemu.h"
37 #include "sysemu/tcg.h"
38 #include "sysemu/qtest.h"
39 #include "qemu/timer.h"
40 #include "qemu/config-file.h"
41 #include "qemu/error-report.h"
42 #include "qemu/qemu-print.h"
43 #if defined(CONFIG_USER_ONLY)
45 #else /* !CONFIG_USER_ONLY */
46 #include "exec/memory.h"
47 #include "exec/ioport.h"
48 #include "sysemu/dma.h"
49 #include "sysemu/hostmem.h"
50 #include "sysemu/hw_accel.h"
51 #include "exec/address-spaces.h"
52 #include "sysemu/xen-mapcache.h"
53 #include "trace/trace-root.h"
55 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
56 #include <linux/falloc.h>
60 #include "qemu/rcu_queue.h"
61 #include "qemu/main-loop.h"
62 #include "translate-all.h"
63 #include "sysemu/replay.h"
65 #include "exec/memory-internal.h"
66 #include "exec/ram_addr.h"
69 #include "qemu/pmem.h"
71 #include "migration/vmstate.h"
73 #include "qemu/range.h"
75 #include "qemu/mmap-alloc.h"
78 #include "monitor/monitor.h"
80 #ifdef CONFIG_LIBDAXCTL
81 #include <daxctl/libdaxctl.h>
84 //#define DEBUG_SUBPAGE
86 #if !defined(CONFIG_USER_ONLY)
87 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
88 * are protected by the ramlist lock.
90 RAMList ram_list
= { .blocks
= QLIST_HEAD_INITIALIZER(ram_list
.blocks
) };
92 static MemoryRegion
*system_memory
;
93 static MemoryRegion
*system_io
;
95 AddressSpace address_space_io
;
96 AddressSpace address_space_memory
;
98 static MemoryRegion io_mem_unassigned
;
101 uintptr_t qemu_host_page_size
;
102 intptr_t qemu_host_page_mask
;
104 #if !defined(CONFIG_USER_ONLY)
106 typedef struct PhysPageEntry PhysPageEntry
;
108 struct PhysPageEntry
{
109 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
111 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
115 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
117 /* Size of the L2 (and L3, etc) page tables. */
118 #define ADDR_SPACE_BITS 64
121 #define P_L2_SIZE (1 << P_L2_BITS)
123 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
125 typedef PhysPageEntry Node
[P_L2_SIZE
];
127 typedef struct PhysPageMap
{
130 unsigned sections_nb
;
131 unsigned sections_nb_alloc
;
133 unsigned nodes_nb_alloc
;
135 MemoryRegionSection
*sections
;
138 struct AddressSpaceDispatch
{
139 MemoryRegionSection
*mru_section
;
140 /* This is a multi-level map on the physical address space.
141 * The bottom level has pointers to MemoryRegionSections.
143 PhysPageEntry phys_map
;
147 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
148 typedef struct subpage_t
{
152 uint16_t sub_section
[];
155 #define PHYS_SECTION_UNASSIGNED 0
157 static void io_mem_init(void);
158 static void memory_map_init(void);
159 static void tcg_log_global_after_sync(MemoryListener
*listener
);
160 static void tcg_commit(MemoryListener
*listener
);
163 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
164 * @cpu: the CPU whose AddressSpace this is
165 * @as: the AddressSpace itself
166 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
167 * @tcg_as_listener: listener for tracking changes to the AddressSpace
169 struct CPUAddressSpace
{
172 struct AddressSpaceDispatch
*memory_dispatch
;
173 MemoryListener tcg_as_listener
;
176 struct DirtyBitmapSnapshot
{
179 unsigned long dirty
[];
184 #if !defined(CONFIG_USER_ONLY)
186 static void phys_map_node_reserve(PhysPageMap
*map
, unsigned nodes
)
188 static unsigned alloc_hint
= 16;
189 if (map
->nodes_nb
+ nodes
> map
->nodes_nb_alloc
) {
190 map
->nodes_nb_alloc
= MAX(alloc_hint
, map
->nodes_nb
+ nodes
);
191 map
->nodes
= g_renew(Node
, map
->nodes
, map
->nodes_nb_alloc
);
192 alloc_hint
= map
->nodes_nb_alloc
;
196 static uint32_t phys_map_node_alloc(PhysPageMap
*map
, bool leaf
)
203 ret
= map
->nodes_nb
++;
205 assert(ret
!= PHYS_MAP_NODE_NIL
);
206 assert(ret
!= map
->nodes_nb_alloc
);
208 e
.skip
= leaf
? 0 : 1;
209 e
.ptr
= leaf
? PHYS_SECTION_UNASSIGNED
: PHYS_MAP_NODE_NIL
;
210 for (i
= 0; i
< P_L2_SIZE
; ++i
) {
211 memcpy(&p
[i
], &e
, sizeof(e
));
216 static void phys_page_set_level(PhysPageMap
*map
, PhysPageEntry
*lp
,
217 hwaddr
*index
, uint64_t *nb
, uint16_t leaf
,
221 hwaddr step
= (hwaddr
)1 << (level
* P_L2_BITS
);
223 if (lp
->skip
&& lp
->ptr
== PHYS_MAP_NODE_NIL
) {
224 lp
->ptr
= phys_map_node_alloc(map
, level
== 0);
226 p
= map
->nodes
[lp
->ptr
];
227 lp
= &p
[(*index
>> (level
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
229 while (*nb
&& lp
< &p
[P_L2_SIZE
]) {
230 if ((*index
& (step
- 1)) == 0 && *nb
>= step
) {
236 phys_page_set_level(map
, lp
, index
, nb
, leaf
, level
- 1);
242 static void phys_page_set(AddressSpaceDispatch
*d
,
243 hwaddr index
, uint64_t nb
,
246 /* Wildly overreserve - it doesn't matter much. */
247 phys_map_node_reserve(&d
->map
, 3 * P_L2_LEVELS
);
249 phys_page_set_level(&d
->map
, &d
->phys_map
, &index
, &nb
, leaf
, P_L2_LEVELS
- 1);
252 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
253 * and update our entry so we can skip it and go directly to the destination.
255 static void phys_page_compact(PhysPageEntry
*lp
, Node
*nodes
)
257 unsigned valid_ptr
= P_L2_SIZE
;
262 if (lp
->ptr
== PHYS_MAP_NODE_NIL
) {
267 for (i
= 0; i
< P_L2_SIZE
; i
++) {
268 if (p
[i
].ptr
== PHYS_MAP_NODE_NIL
) {
275 phys_page_compact(&p
[i
], nodes
);
279 /* We can only compress if there's only one child. */
284 assert(valid_ptr
< P_L2_SIZE
);
286 /* Don't compress if it won't fit in the # of bits we have. */
287 if (P_L2_LEVELS
>= (1 << 6) &&
288 lp
->skip
+ p
[valid_ptr
].skip
>= (1 << 6)) {
292 lp
->ptr
= p
[valid_ptr
].ptr
;
293 if (!p
[valid_ptr
].skip
) {
294 /* If our only child is a leaf, make this a leaf. */
295 /* By design, we should have made this node a leaf to begin with so we
296 * should never reach here.
297 * But since it's so simple to handle this, let's do it just in case we
302 lp
->skip
+= p
[valid_ptr
].skip
;
306 void address_space_dispatch_compact(AddressSpaceDispatch
*d
)
308 if (d
->phys_map
.skip
) {
309 phys_page_compact(&d
->phys_map
, d
->map
.nodes
);
313 static inline bool section_covers_addr(const MemoryRegionSection
*section
,
316 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
317 * the section must cover the entire address space.
319 return int128_gethi(section
->size
) ||
320 range_covers_byte(section
->offset_within_address_space
,
321 int128_getlo(section
->size
), addr
);
324 static MemoryRegionSection
*phys_page_find(AddressSpaceDispatch
*d
, hwaddr addr
)
326 PhysPageEntry lp
= d
->phys_map
, *p
;
327 Node
*nodes
= d
->map
.nodes
;
328 MemoryRegionSection
*sections
= d
->map
.sections
;
329 hwaddr index
= addr
>> TARGET_PAGE_BITS
;
332 for (i
= P_L2_LEVELS
; lp
.skip
&& (i
-= lp
.skip
) >= 0;) {
333 if (lp
.ptr
== PHYS_MAP_NODE_NIL
) {
334 return §ions
[PHYS_SECTION_UNASSIGNED
];
337 lp
= p
[(index
>> (i
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
340 if (section_covers_addr(§ions
[lp
.ptr
], addr
)) {
341 return §ions
[lp
.ptr
];
343 return §ions
[PHYS_SECTION_UNASSIGNED
];
347 /* Called from RCU critical section */
348 static MemoryRegionSection
*address_space_lookup_region(AddressSpaceDispatch
*d
,
350 bool resolve_subpage
)
352 MemoryRegionSection
*section
= qatomic_read(&d
->mru_section
);
355 if (!section
|| section
== &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
] ||
356 !section_covers_addr(section
, addr
)) {
357 section
= phys_page_find(d
, addr
);
358 qatomic_set(&d
->mru_section
, section
);
360 if (resolve_subpage
&& section
->mr
->subpage
) {
361 subpage
= container_of(section
->mr
, subpage_t
, iomem
);
362 section
= &d
->map
.sections
[subpage
->sub_section
[SUBPAGE_IDX(addr
)]];
367 /* Called from RCU critical section */
368 static MemoryRegionSection
*
369 address_space_translate_internal(AddressSpaceDispatch
*d
, hwaddr addr
, hwaddr
*xlat
,
370 hwaddr
*plen
, bool resolve_subpage
)
372 MemoryRegionSection
*section
;
376 section
= address_space_lookup_region(d
, addr
, resolve_subpage
);
377 /* Compute offset within MemoryRegionSection */
378 addr
-= section
->offset_within_address_space
;
380 /* Compute offset within MemoryRegion */
381 *xlat
= addr
+ section
->offset_within_region
;
385 /* MMIO registers can be expected to perform full-width accesses based only
386 * on their address, without considering adjacent registers that could
387 * decode to completely different MemoryRegions. When such registers
388 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
389 * regions overlap wildly. For this reason we cannot clamp the accesses
392 * If the length is small (as is the case for address_space_ldl/stl),
393 * everything works fine. If the incoming length is large, however,
394 * the caller really has to do the clamping through memory_access_size.
396 if (memory_region_is_ram(mr
)) {
397 diff
= int128_sub(section
->size
, int128_make64(addr
));
398 *plen
= int128_get64(int128_min(diff
, int128_make64(*plen
)));
404 * address_space_translate_iommu - translate an address through an IOMMU
405 * memory region and then through the target address space.
407 * @iommu_mr: the IOMMU memory region that we start the translation from
408 * @addr: the address to be translated through the MMU
409 * @xlat: the translated address offset within the destination memory region.
410 * It cannot be %NULL.
411 * @plen_out: valid read/write length of the translated address. It
413 * @page_mask_out: page mask for the translated address. This
414 * should only be meaningful for IOMMU translated
415 * addresses, since there may be huge pages that this bit
416 * would tell. It can be %NULL if we don't care about it.
417 * @is_write: whether the translation operation is for write
418 * @is_mmio: whether this can be MMIO, set true if it can
419 * @target_as: the address space targeted by the IOMMU
420 * @attrs: transaction attributes
422 * This function is called from RCU critical section. It is the common
423 * part of flatview_do_translate and address_space_translate_cached.
425 static MemoryRegionSection
address_space_translate_iommu(IOMMUMemoryRegion
*iommu_mr
,
428 hwaddr
*page_mask_out
,
431 AddressSpace
**target_as
,
434 MemoryRegionSection
*section
;
435 hwaddr page_mask
= (hwaddr
)-1;
439 IOMMUMemoryRegionClass
*imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
443 if (imrc
->attrs_to_index
) {
444 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
447 iotlb
= imrc
->translate(iommu_mr
, addr
, is_write
?
448 IOMMU_WO
: IOMMU_RO
, iommu_idx
);
450 if (!(iotlb
.perm
& (1 << is_write
))) {
454 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
455 | (addr
& iotlb
.addr_mask
));
456 page_mask
&= iotlb
.addr_mask
;
457 *plen_out
= MIN(*plen_out
, (addr
| iotlb
.addr_mask
) - addr
+ 1);
458 *target_as
= iotlb
.target_as
;
460 section
= address_space_translate_internal(
461 address_space_to_dispatch(iotlb
.target_as
), addr
, xlat
,
464 iommu_mr
= memory_region_get_iommu(section
->mr
);
465 } while (unlikely(iommu_mr
));
468 *page_mask_out
= page_mask
;
473 return (MemoryRegionSection
) { .mr
= &io_mem_unassigned
};
477 * flatview_do_translate - translate an address in FlatView
479 * @fv: the flat view that we want to translate on
480 * @addr: the address to be translated in above address space
481 * @xlat: the translated address offset within memory region. It
483 * @plen_out: valid read/write length of the translated address. It
484 * can be @NULL when we don't care about it.
485 * @page_mask_out: page mask for the translated address. This
486 * should only be meaningful for IOMMU translated
487 * addresses, since there may be huge pages that this bit
488 * would tell. It can be @NULL if we don't care about it.
489 * @is_write: whether the translation operation is for write
490 * @is_mmio: whether this can be MMIO, set true if it can
491 * @target_as: the address space targeted by the IOMMU
492 * @attrs: memory transaction attributes
494 * This function is called from RCU critical section
496 static MemoryRegionSection
flatview_do_translate(FlatView
*fv
,
500 hwaddr
*page_mask_out
,
503 AddressSpace
**target_as
,
506 MemoryRegionSection
*section
;
507 IOMMUMemoryRegion
*iommu_mr
;
508 hwaddr plen
= (hwaddr
)(-1);
514 section
= address_space_translate_internal(
515 flatview_to_dispatch(fv
), addr
, xlat
,
518 iommu_mr
= memory_region_get_iommu(section
->mr
);
519 if (unlikely(iommu_mr
)) {
520 return address_space_translate_iommu(iommu_mr
, xlat
,
521 plen_out
, page_mask_out
,
526 /* Not behind an IOMMU, use default page size. */
527 *page_mask_out
= ~TARGET_PAGE_MASK
;
533 /* Called from RCU critical section */
534 IOMMUTLBEntry
address_space_get_iotlb_entry(AddressSpace
*as
, hwaddr addr
,
535 bool is_write
, MemTxAttrs attrs
)
537 MemoryRegionSection section
;
538 hwaddr xlat
, page_mask
;
541 * This can never be MMIO, and we don't really care about plen,
544 section
= flatview_do_translate(address_space_to_flatview(as
), addr
, &xlat
,
545 NULL
, &page_mask
, is_write
, false, &as
,
548 /* Illegal translation */
549 if (section
.mr
== &io_mem_unassigned
) {
553 /* Convert memory region offset into address space offset */
554 xlat
+= section
.offset_within_address_space
-
555 section
.offset_within_region
;
557 return (IOMMUTLBEntry
) {
559 .iova
= addr
& ~page_mask
,
560 .translated_addr
= xlat
& ~page_mask
,
561 .addr_mask
= page_mask
,
562 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
567 return (IOMMUTLBEntry
) {0};
570 /* Called from RCU critical section */
571 MemoryRegion
*flatview_translate(FlatView
*fv
, hwaddr addr
, hwaddr
*xlat
,
572 hwaddr
*plen
, bool is_write
,
576 MemoryRegionSection section
;
577 AddressSpace
*as
= NULL
;
579 /* This can be MMIO, so setup MMIO bit. */
580 section
= flatview_do_translate(fv
, addr
, xlat
, plen
, NULL
,
581 is_write
, true, &as
, attrs
);
584 if (xen_enabled() && memory_access_is_direct(mr
, is_write
)) {
585 hwaddr page
= ((addr
& TARGET_PAGE_MASK
) + TARGET_PAGE_SIZE
) - addr
;
586 *plen
= MIN(page
, *plen
);
592 typedef struct TCGIOMMUNotifier
{
600 static void tcg_iommu_unmap_notify(IOMMUNotifier
*n
, IOMMUTLBEntry
*iotlb
)
602 TCGIOMMUNotifier
*notifier
= container_of(n
, TCGIOMMUNotifier
, n
);
604 if (!notifier
->active
) {
607 tlb_flush(notifier
->cpu
);
608 notifier
->active
= false;
609 /* We leave the notifier struct on the list to avoid reallocating it later.
610 * Generally the number of IOMMUs a CPU deals with will be small.
611 * In any case we can't unregister the iommu notifier from a notify
616 static void tcg_register_iommu_notifier(CPUState
*cpu
,
617 IOMMUMemoryRegion
*iommu_mr
,
620 /* Make sure this CPU has an IOMMU notifier registered for this
621 * IOMMU/IOMMU index combination, so that we can flush its TLB
622 * when the IOMMU tells us the mappings we've cached have changed.
624 MemoryRegion
*mr
= MEMORY_REGION(iommu_mr
);
625 TCGIOMMUNotifier
*notifier
;
629 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
630 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
631 if (notifier
->mr
== mr
&& notifier
->iommu_idx
== iommu_idx
) {
635 if (i
== cpu
->iommu_notifiers
->len
) {
636 /* Not found, add a new entry at the end of the array */
637 cpu
->iommu_notifiers
= g_array_set_size(cpu
->iommu_notifiers
, i
+ 1);
638 notifier
= g_new0(TCGIOMMUNotifier
, 1);
639 g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
) = notifier
;
642 notifier
->iommu_idx
= iommu_idx
;
644 /* Rather than trying to register interest in the specific part
645 * of the iommu's address space that we've accessed and then
646 * expand it later as subsequent accesses touch more of it, we
647 * just register interest in the whole thing, on the assumption
648 * that iommu reconfiguration will be rare.
650 iommu_notifier_init(¬ifier
->n
,
651 tcg_iommu_unmap_notify
,
652 IOMMU_NOTIFIER_UNMAP
,
656 ret
= memory_region_register_iommu_notifier(notifier
->mr
, ¬ifier
->n
,
659 error_report_err(err
);
664 if (!notifier
->active
) {
665 notifier
->active
= true;
669 static void tcg_iommu_free_notifier_list(CPUState
*cpu
)
671 /* Destroy the CPU's notifier list */
673 TCGIOMMUNotifier
*notifier
;
675 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
676 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
677 memory_region_unregister_iommu_notifier(notifier
->mr
, ¬ifier
->n
);
680 g_array_free(cpu
->iommu_notifiers
, true);
683 /* Called from RCU critical section */
684 MemoryRegionSection
*
685 address_space_translate_for_iotlb(CPUState
*cpu
, int asidx
, hwaddr addr
,
686 hwaddr
*xlat
, hwaddr
*plen
,
687 MemTxAttrs attrs
, int *prot
)
689 MemoryRegionSection
*section
;
690 IOMMUMemoryRegion
*iommu_mr
;
691 IOMMUMemoryRegionClass
*imrc
;
694 AddressSpaceDispatch
*d
=
695 qatomic_rcu_read(&cpu
->cpu_ases
[asidx
].memory_dispatch
);
698 section
= address_space_translate_internal(d
, addr
, &addr
, plen
, false);
700 iommu_mr
= memory_region_get_iommu(section
->mr
);
705 imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
707 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
708 tcg_register_iommu_notifier(cpu
, iommu_mr
, iommu_idx
);
709 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
710 * doesn't short-cut its translation table walk.
712 iotlb
= imrc
->translate(iommu_mr
, addr
, IOMMU_NONE
, iommu_idx
);
713 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
714 | (addr
& iotlb
.addr_mask
));
715 /* Update the caller's prot bits to remove permissions the IOMMU
716 * is giving us a failure response for. If we get down to no
717 * permissions left at all we can give up now.
719 if (!(iotlb
.perm
& IOMMU_RO
)) {
720 *prot
&= ~(PAGE_READ
| PAGE_EXEC
);
722 if (!(iotlb
.perm
& IOMMU_WO
)) {
723 *prot
&= ~PAGE_WRITE
;
730 d
= flatview_to_dispatch(address_space_to_flatview(iotlb
.target_as
));
733 assert(!memory_region_is_iommu(section
->mr
));
738 return &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
];
742 #if !defined(CONFIG_USER_ONLY)
744 static int cpu_common_post_load(void *opaque
, int version_id
)
746 CPUState
*cpu
= opaque
;
748 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
749 version_id is increased. */
750 cpu
->interrupt_request
&= ~0x01;
753 /* loadvm has just updated the content of RAM, bypassing the
754 * usual mechanisms that ensure we flush TBs for writes to
755 * memory we've translated code from. So we must flush all TBs,
756 * which will now be stale.
763 static int cpu_common_pre_load(void *opaque
)
765 CPUState
*cpu
= opaque
;
767 cpu
->exception_index
= -1;
772 static bool cpu_common_exception_index_needed(void *opaque
)
774 CPUState
*cpu
= opaque
;
776 return tcg_enabled() && cpu
->exception_index
!= -1;
779 static const VMStateDescription vmstate_cpu_common_exception_index
= {
780 .name
= "cpu_common/exception_index",
782 .minimum_version_id
= 1,
783 .needed
= cpu_common_exception_index_needed
,
784 .fields
= (VMStateField
[]) {
785 VMSTATE_INT32(exception_index
, CPUState
),
786 VMSTATE_END_OF_LIST()
790 static bool cpu_common_crash_occurred_needed(void *opaque
)
792 CPUState
*cpu
= opaque
;
794 return cpu
->crash_occurred
;
797 static const VMStateDescription vmstate_cpu_common_crash_occurred
= {
798 .name
= "cpu_common/crash_occurred",
800 .minimum_version_id
= 1,
801 .needed
= cpu_common_crash_occurred_needed
,
802 .fields
= (VMStateField
[]) {
803 VMSTATE_BOOL(crash_occurred
, CPUState
),
804 VMSTATE_END_OF_LIST()
808 const VMStateDescription vmstate_cpu_common
= {
809 .name
= "cpu_common",
811 .minimum_version_id
= 1,
812 .pre_load
= cpu_common_pre_load
,
813 .post_load
= cpu_common_post_load
,
814 .fields
= (VMStateField
[]) {
815 VMSTATE_UINT32(halted
, CPUState
),
816 VMSTATE_UINT32(interrupt_request
, CPUState
),
817 VMSTATE_END_OF_LIST()
819 .subsections
= (const VMStateDescription
*[]) {
820 &vmstate_cpu_common_exception_index
,
821 &vmstate_cpu_common_crash_occurred
,
826 void cpu_address_space_init(CPUState
*cpu
, int asidx
,
827 const char *prefix
, MemoryRegion
*mr
)
829 CPUAddressSpace
*newas
;
830 AddressSpace
*as
= g_new0(AddressSpace
, 1);
834 as_name
= g_strdup_printf("%s-%d", prefix
, cpu
->cpu_index
);
835 address_space_init(as
, mr
, as_name
);
838 /* Target code should have set num_ases before calling us */
839 assert(asidx
< cpu
->num_ases
);
842 /* address space 0 gets the convenience alias */
846 /* KVM cannot currently support multiple address spaces. */
847 assert(asidx
== 0 || !kvm_enabled());
849 if (!cpu
->cpu_ases
) {
850 cpu
->cpu_ases
= g_new0(CPUAddressSpace
, cpu
->num_ases
);
853 newas
= &cpu
->cpu_ases
[asidx
];
857 newas
->tcg_as_listener
.log_global_after_sync
= tcg_log_global_after_sync
;
858 newas
->tcg_as_listener
.commit
= tcg_commit
;
859 memory_listener_register(&newas
->tcg_as_listener
, as
);
863 AddressSpace
*cpu_get_address_space(CPUState
*cpu
, int asidx
)
865 /* Return the AddressSpace corresponding to the specified index */
866 return cpu
->cpu_ases
[asidx
].as
;
870 void cpu_exec_unrealizefn(CPUState
*cpu
)
872 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
875 cpu_list_remove(cpu
);
877 if (cc
->vmsd
!= NULL
) {
878 vmstate_unregister(NULL
, cc
->vmsd
, cpu
);
880 if (qdev_get_vmsd(DEVICE(cpu
)) == NULL
) {
881 vmstate_unregister(NULL
, &vmstate_cpu_common
, cpu
);
883 #ifndef CONFIG_USER_ONLY
884 tcg_iommu_free_notifier_list(cpu
);
888 Property cpu_common_props
[] = {
889 #ifndef CONFIG_USER_ONLY
890 /* Create a memory property for softmmu CPU object,
891 * so users can wire up its memory. (This can't go in hw/core/cpu.c
892 * because that file is compiled only once for both user-mode
893 * and system builds.) The default if no link is set up is to use
894 * the system address space.
896 DEFINE_PROP_LINK("memory", CPUState
, memory
, TYPE_MEMORY_REGION
,
899 DEFINE_PROP_BOOL("start-powered-off", CPUState
, start_powered_off
, false),
900 DEFINE_PROP_END_OF_LIST(),
903 void cpu_exec_initfn(CPUState
*cpu
)
908 #ifndef CONFIG_USER_ONLY
909 cpu
->thread_id
= qemu_get_thread_id();
910 cpu
->memory
= system_memory
;
911 object_ref(OBJECT(cpu
->memory
));
915 void cpu_exec_realizefn(CPUState
*cpu
, Error
**errp
)
917 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
918 static bool tcg_target_initialized
;
922 if (tcg_enabled() && !tcg_target_initialized
) {
923 tcg_target_initialized
= true;
924 cc
->tcg_initialize();
928 qemu_plugin_vcpu_init_hook(cpu
);
930 #ifdef CONFIG_USER_ONLY
931 assert(cc
->vmsd
== NULL
);
932 #else /* !CONFIG_USER_ONLY */
933 if (qdev_get_vmsd(DEVICE(cpu
)) == NULL
) {
934 vmstate_register(NULL
, cpu
->cpu_index
, &vmstate_cpu_common
, cpu
);
936 if (cc
->vmsd
!= NULL
) {
937 vmstate_register(NULL
, cpu
->cpu_index
, cc
->vmsd
, cpu
);
940 cpu
->iommu_notifiers
= g_array_new(false, true, sizeof(TCGIOMMUNotifier
*));
944 const char *parse_cpu_option(const char *cpu_option
)
948 gchar
**model_pieces
;
949 const char *cpu_type
;
951 model_pieces
= g_strsplit(cpu_option
, ",", 2);
952 if (!model_pieces
[0]) {
953 error_report("-cpu option cannot be empty");
957 oc
= cpu_class_by_name(CPU_RESOLVING_TYPE
, model_pieces
[0]);
959 error_report("unable to find CPU model '%s'", model_pieces
[0]);
960 g_strfreev(model_pieces
);
964 cpu_type
= object_class_get_name(oc
);
966 cc
->parse_features(cpu_type
, model_pieces
[1], &error_fatal
);
967 g_strfreev(model_pieces
);
971 #if defined(CONFIG_USER_ONLY)
972 void tb_invalidate_phys_addr(target_ulong addr
)
975 tb_invalidate_phys_page_range(addr
, addr
+ 1);
979 static void breakpoint_invalidate(CPUState
*cpu
, target_ulong pc
)
981 tb_invalidate_phys_addr(pc
);
984 void tb_invalidate_phys_addr(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
)
990 if (!tcg_enabled()) {
994 RCU_READ_LOCK_GUARD();
995 mr
= address_space_translate(as
, addr
, &addr
, &l
, false, attrs
);
996 if (!(memory_region_is_ram(mr
)
997 || memory_region_is_romd(mr
))) {
1000 ram_addr
= memory_region_get_ram_addr(mr
) + addr
;
1001 tb_invalidate_phys_page_range(ram_addr
, ram_addr
+ 1);
1004 static void breakpoint_invalidate(CPUState
*cpu
, target_ulong pc
)
1007 * There may not be a virtual to physical translation for the pc
1008 * right now, but there may exist cached TB for this pc.
1009 * Flush the whole TB cache to force re-translation of such TBs.
1010 * This is heavyweight, but we're debugging anyway.
1016 #ifndef CONFIG_USER_ONLY
1017 /* Add a watchpoint. */
1018 int cpu_watchpoint_insert(CPUState
*cpu
, vaddr addr
, vaddr len
,
1019 int flags
, CPUWatchpoint
**watchpoint
)
1024 /* forbid ranges which are empty or run off the end of the address space */
1025 if (len
== 0 || (addr
+ len
- 1) < addr
) {
1026 error_report("tried to set invalid watchpoint at %"
1027 VADDR_PRIx
", len=%" VADDR_PRIu
, addr
, len
);
1030 wp
= g_malloc(sizeof(*wp
));
1036 /* keep all GDB-injected watchpoints in front */
1037 if (flags
& BP_GDB
) {
1038 QTAILQ_INSERT_HEAD(&cpu
->watchpoints
, wp
, entry
);
1040 QTAILQ_INSERT_TAIL(&cpu
->watchpoints
, wp
, entry
);
1043 in_page
= -(addr
| TARGET_PAGE_MASK
);
1044 if (len
<= in_page
) {
1045 tlb_flush_page(cpu
, addr
);
1055 /* Remove a specific watchpoint. */
1056 int cpu_watchpoint_remove(CPUState
*cpu
, vaddr addr
, vaddr len
,
1061 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
1062 if (addr
== wp
->vaddr
&& len
== wp
->len
1063 && flags
== (wp
->flags
& ~BP_WATCHPOINT_HIT
)) {
1064 cpu_watchpoint_remove_by_ref(cpu
, wp
);
1071 /* Remove a specific watchpoint by reference. */
1072 void cpu_watchpoint_remove_by_ref(CPUState
*cpu
, CPUWatchpoint
*watchpoint
)
1074 QTAILQ_REMOVE(&cpu
->watchpoints
, watchpoint
, entry
);
1076 tlb_flush_page(cpu
, watchpoint
->vaddr
);
1081 /* Remove all matching watchpoints. */
1082 void cpu_watchpoint_remove_all(CPUState
*cpu
, int mask
)
1084 CPUWatchpoint
*wp
, *next
;
1086 QTAILQ_FOREACH_SAFE(wp
, &cpu
->watchpoints
, entry
, next
) {
1087 if (wp
->flags
& mask
) {
1088 cpu_watchpoint_remove_by_ref(cpu
, wp
);
1093 /* Return true if this watchpoint address matches the specified
1094 * access (ie the address range covered by the watchpoint overlaps
1095 * partially or completely with the address range covered by the
1098 static inline bool watchpoint_address_matches(CPUWatchpoint
*wp
,
1099 vaddr addr
, vaddr len
)
1101 /* We know the lengths are non-zero, but a little caution is
1102 * required to avoid errors in the case where the range ends
1103 * exactly at the top of the address space and so addr + len
1104 * wraps round to zero.
1106 vaddr wpend
= wp
->vaddr
+ wp
->len
- 1;
1107 vaddr addrend
= addr
+ len
- 1;
1109 return !(addr
> wpend
|| wp
->vaddr
> addrend
);
1112 /* Return flags for watchpoints that match addr + prot. */
1113 int cpu_watchpoint_address_matches(CPUState
*cpu
, vaddr addr
, vaddr len
)
1118 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
1119 if (watchpoint_address_matches(wp
, addr
, len
)) {
1125 #endif /* !CONFIG_USER_ONLY */
1127 /* Add a breakpoint. */
1128 int cpu_breakpoint_insert(CPUState
*cpu
, vaddr pc
, int flags
,
1129 CPUBreakpoint
**breakpoint
)
1133 bp
= g_malloc(sizeof(*bp
));
1138 /* keep all GDB-injected breakpoints in front */
1139 if (flags
& BP_GDB
) {
1140 QTAILQ_INSERT_HEAD(&cpu
->breakpoints
, bp
, entry
);
1142 QTAILQ_INSERT_TAIL(&cpu
->breakpoints
, bp
, entry
);
1145 breakpoint_invalidate(cpu
, pc
);
1153 /* Remove a specific breakpoint. */
1154 int cpu_breakpoint_remove(CPUState
*cpu
, vaddr pc
, int flags
)
1158 QTAILQ_FOREACH(bp
, &cpu
->breakpoints
, entry
) {
1159 if (bp
->pc
== pc
&& bp
->flags
== flags
) {
1160 cpu_breakpoint_remove_by_ref(cpu
, bp
);
1167 /* Remove a specific breakpoint by reference. */
1168 void cpu_breakpoint_remove_by_ref(CPUState
*cpu
, CPUBreakpoint
*breakpoint
)
1170 QTAILQ_REMOVE(&cpu
->breakpoints
, breakpoint
, entry
);
1172 breakpoint_invalidate(cpu
, breakpoint
->pc
);
1177 /* Remove all matching breakpoints. */
1178 void cpu_breakpoint_remove_all(CPUState
*cpu
, int mask
)
1180 CPUBreakpoint
*bp
, *next
;
1182 QTAILQ_FOREACH_SAFE(bp
, &cpu
->breakpoints
, entry
, next
) {
1183 if (bp
->flags
& mask
) {
1184 cpu_breakpoint_remove_by_ref(cpu
, bp
);
1189 /* enable or disable single step mode. EXCP_DEBUG is returned by the
1190 CPU loop after each instruction */
1191 void cpu_single_step(CPUState
*cpu
, int enabled
)
1193 if (cpu
->singlestep_enabled
!= enabled
) {
1194 cpu
->singlestep_enabled
= enabled
;
1195 if (kvm_enabled()) {
1196 kvm_update_guest_debug(cpu
, 0);
1198 /* must flush all the translated code to avoid inconsistencies */
1199 /* XXX: only flush what is necessary */
1205 void cpu_abort(CPUState
*cpu
, const char *fmt
, ...)
1212 fprintf(stderr
, "qemu: fatal: ");
1213 vfprintf(stderr
, fmt
, ap
);
1214 fprintf(stderr
, "\n");
1215 cpu_dump_state(cpu
, stderr
, CPU_DUMP_FPU
| CPU_DUMP_CCOP
);
1216 if (qemu_log_separate()) {
1217 FILE *logfile
= qemu_log_lock();
1218 qemu_log("qemu: fatal: ");
1219 qemu_log_vprintf(fmt
, ap2
);
1221 log_cpu_state(cpu
, CPU_DUMP_FPU
| CPU_DUMP_CCOP
);
1223 qemu_log_unlock(logfile
);
1229 #if defined(CONFIG_USER_ONLY)
1231 struct sigaction act
;
1232 sigfillset(&act
.sa_mask
);
1233 act
.sa_handler
= SIG_DFL
;
1235 sigaction(SIGABRT
, &act
, NULL
);
1241 #if !defined(CONFIG_USER_ONLY)
1242 /* Called from RCU critical section */
1243 static RAMBlock
*qemu_get_ram_block(ram_addr_t addr
)
1247 block
= qatomic_rcu_read(&ram_list
.mru_block
);
1248 if (block
&& addr
- block
->offset
< block
->max_length
) {
1251 RAMBLOCK_FOREACH(block
) {
1252 if (addr
- block
->offset
< block
->max_length
) {
1257 fprintf(stderr
, "Bad ram offset %" PRIx64
"\n", (uint64_t)addr
);
1261 /* It is safe to write mru_block outside the iothread lock. This
1266 * xxx removed from list
1270 * call_rcu(reclaim_ramblock, xxx);
1273 * qatomic_rcu_set is not needed here. The block was already published
1274 * when it was placed into the list. Here we're just making an extra
1275 * copy of the pointer.
1277 ram_list
.mru_block
= block
;
1281 static void tlb_reset_dirty_range_all(ram_addr_t start
, ram_addr_t length
)
1288 assert(tcg_enabled());
1289 end
= TARGET_PAGE_ALIGN(start
+ length
);
1290 start
&= TARGET_PAGE_MASK
;
1292 RCU_READ_LOCK_GUARD();
1293 block
= qemu_get_ram_block(start
);
1294 assert(block
== qemu_get_ram_block(end
- 1));
1295 start1
= (uintptr_t)ramblock_ptr(block
, start
- block
->offset
);
1297 tlb_reset_dirty(cpu
, start1
, length
);
1301 /* Note: start and end must be within the same ram block. */
1302 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start
,
1306 DirtyMemoryBlocks
*blocks
;
1307 unsigned long end
, page
, start_page
;
1310 uint64_t mr_offset
, mr_size
;
1316 end
= TARGET_PAGE_ALIGN(start
+ length
) >> TARGET_PAGE_BITS
;
1317 start_page
= start
>> TARGET_PAGE_BITS
;
1320 WITH_RCU_READ_LOCK_GUARD() {
1321 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1322 ramblock
= qemu_get_ram_block(start
);
1323 /* Range sanity check on the ramblock */
1324 assert(start
>= ramblock
->offset
&&
1325 start
+ length
<= ramblock
->offset
+ ramblock
->used_length
);
1327 while (page
< end
) {
1328 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1329 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1330 unsigned long num
= MIN(end
- page
,
1331 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1333 dirty
|= bitmap_test_and_clear_atomic(blocks
->blocks
[idx
],
1338 mr_offset
= (ram_addr_t
)(start_page
<< TARGET_PAGE_BITS
) - ramblock
->offset
;
1339 mr_size
= (end
- start_page
) << TARGET_PAGE_BITS
;
1340 memory_region_clear_dirty_bitmap(ramblock
->mr
, mr_offset
, mr_size
);
1343 if (dirty
&& tcg_enabled()) {
1344 tlb_reset_dirty_range_all(start
, length
);
1350 DirtyBitmapSnapshot
*cpu_physical_memory_snapshot_and_clear_dirty
1351 (MemoryRegion
*mr
, hwaddr offset
, hwaddr length
, unsigned client
)
1353 DirtyMemoryBlocks
*blocks
;
1354 ram_addr_t start
= memory_region_get_ram_addr(mr
) + offset
;
1355 unsigned long align
= 1UL << (TARGET_PAGE_BITS
+ BITS_PER_LEVEL
);
1356 ram_addr_t first
= QEMU_ALIGN_DOWN(start
, align
);
1357 ram_addr_t last
= QEMU_ALIGN_UP(start
+ length
, align
);
1358 DirtyBitmapSnapshot
*snap
;
1359 unsigned long page
, end
, dest
;
1361 snap
= g_malloc0(sizeof(*snap
) +
1362 ((last
- first
) >> (TARGET_PAGE_BITS
+ 3)));
1363 snap
->start
= first
;
1366 page
= first
>> TARGET_PAGE_BITS
;
1367 end
= last
>> TARGET_PAGE_BITS
;
1370 WITH_RCU_READ_LOCK_GUARD() {
1371 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1373 while (page
< end
) {
1374 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1375 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1376 unsigned long num
= MIN(end
- page
,
1377 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1379 assert(QEMU_IS_ALIGNED(offset
, (1 << BITS_PER_LEVEL
)));
1380 assert(QEMU_IS_ALIGNED(num
, (1 << BITS_PER_LEVEL
)));
1381 offset
>>= BITS_PER_LEVEL
;
1383 bitmap_copy_and_clear_atomic(snap
->dirty
+ dest
,
1384 blocks
->blocks
[idx
] + offset
,
1387 dest
+= num
>> BITS_PER_LEVEL
;
1391 if (tcg_enabled()) {
1392 tlb_reset_dirty_range_all(start
, length
);
1395 memory_region_clear_dirty_bitmap(mr
, offset
, length
);
1400 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot
*snap
,
1404 unsigned long page
, end
;
1406 assert(start
>= snap
->start
);
1407 assert(start
+ length
<= snap
->end
);
1409 end
= TARGET_PAGE_ALIGN(start
+ length
- snap
->start
) >> TARGET_PAGE_BITS
;
1410 page
= (start
- snap
->start
) >> TARGET_PAGE_BITS
;
1412 while (page
< end
) {
1413 if (test_bit(page
, snap
->dirty
)) {
1421 /* Called from RCU critical section */
1422 hwaddr
memory_region_section_get_iotlb(CPUState
*cpu
,
1423 MemoryRegionSection
*section
)
1425 AddressSpaceDispatch
*d
= flatview_to_dispatch(section
->fv
);
1426 return section
- d
->map
.sections
;
1428 #endif /* defined(CONFIG_USER_ONLY) */
1430 #if !defined(CONFIG_USER_ONLY)
1432 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
1434 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
);
1436 static void *(*phys_mem_alloc
)(size_t size
, uint64_t *align
, bool shared
) =
1437 qemu_anon_ram_alloc
;
1440 * Set a custom physical guest memory alloator.
1441 * Accelerators with unusual needs may need this. Hopefully, we can
1442 * get rid of it eventually.
1444 void phys_mem_set_alloc(void *(*alloc
)(size_t, uint64_t *align
, bool shared
))
1446 phys_mem_alloc
= alloc
;
1449 static uint16_t phys_section_add(PhysPageMap
*map
,
1450 MemoryRegionSection
*section
)
1452 /* The physical section number is ORed with a page-aligned
1453 * pointer to produce the iotlb entries. Thus it should
1454 * never overflow into the page-aligned value.
1456 assert(map
->sections_nb
< TARGET_PAGE_SIZE
);
1458 if (map
->sections_nb
== map
->sections_nb_alloc
) {
1459 map
->sections_nb_alloc
= MAX(map
->sections_nb_alloc
* 2, 16);
1460 map
->sections
= g_renew(MemoryRegionSection
, map
->sections
,
1461 map
->sections_nb_alloc
);
1463 map
->sections
[map
->sections_nb
] = *section
;
1464 memory_region_ref(section
->mr
);
1465 return map
->sections_nb
++;
1468 static void phys_section_destroy(MemoryRegion
*mr
)
1470 bool have_sub_page
= mr
->subpage
;
1472 memory_region_unref(mr
);
1474 if (have_sub_page
) {
1475 subpage_t
*subpage
= container_of(mr
, subpage_t
, iomem
);
1476 object_unref(OBJECT(&subpage
->iomem
));
1481 static void phys_sections_free(PhysPageMap
*map
)
1483 while (map
->sections_nb
> 0) {
1484 MemoryRegionSection
*section
= &map
->sections
[--map
->sections_nb
];
1485 phys_section_destroy(section
->mr
);
1487 g_free(map
->sections
);
1491 static void register_subpage(FlatView
*fv
, MemoryRegionSection
*section
)
1493 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1495 hwaddr base
= section
->offset_within_address_space
1497 MemoryRegionSection
*existing
= phys_page_find(d
, base
);
1498 MemoryRegionSection subsection
= {
1499 .offset_within_address_space
= base
,
1500 .size
= int128_make64(TARGET_PAGE_SIZE
),
1504 assert(existing
->mr
->subpage
|| existing
->mr
== &io_mem_unassigned
);
1506 if (!(existing
->mr
->subpage
)) {
1507 subpage
= subpage_init(fv
, base
);
1509 subsection
.mr
= &subpage
->iomem
;
1510 phys_page_set(d
, base
>> TARGET_PAGE_BITS
, 1,
1511 phys_section_add(&d
->map
, &subsection
));
1513 subpage
= container_of(existing
->mr
, subpage_t
, iomem
);
1515 start
= section
->offset_within_address_space
& ~TARGET_PAGE_MASK
;
1516 end
= start
+ int128_get64(section
->size
) - 1;
1517 subpage_register(subpage
, start
, end
,
1518 phys_section_add(&d
->map
, section
));
1522 static void register_multipage(FlatView
*fv
,
1523 MemoryRegionSection
*section
)
1525 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1526 hwaddr start_addr
= section
->offset_within_address_space
;
1527 uint16_t section_index
= phys_section_add(&d
->map
, section
);
1528 uint64_t num_pages
= int128_get64(int128_rshift(section
->size
,
1532 phys_page_set(d
, start_addr
>> TARGET_PAGE_BITS
, num_pages
, section_index
);
1536 * The range in *section* may look like this:
1540 * where s stands for subpage and P for page.
1542 void flatview_add_to_dispatch(FlatView
*fv
, MemoryRegionSection
*section
)
1544 MemoryRegionSection remain
= *section
;
1545 Int128 page_size
= int128_make64(TARGET_PAGE_SIZE
);
1547 /* register first subpage */
1548 if (remain
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1549 uint64_t left
= TARGET_PAGE_ALIGN(remain
.offset_within_address_space
)
1550 - remain
.offset_within_address_space
;
1552 MemoryRegionSection now
= remain
;
1553 now
.size
= int128_min(int128_make64(left
), now
.size
);
1554 register_subpage(fv
, &now
);
1555 if (int128_eq(remain
.size
, now
.size
)) {
1558 remain
.size
= int128_sub(remain
.size
, now
.size
);
1559 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1560 remain
.offset_within_region
+= int128_get64(now
.size
);
1563 /* register whole pages */
1564 if (int128_ge(remain
.size
, page_size
)) {
1565 MemoryRegionSection now
= remain
;
1566 now
.size
= int128_and(now
.size
, int128_neg(page_size
));
1567 register_multipage(fv
, &now
);
1568 if (int128_eq(remain
.size
, now
.size
)) {
1571 remain
.size
= int128_sub(remain
.size
, now
.size
);
1572 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1573 remain
.offset_within_region
+= int128_get64(now
.size
);
1576 /* register last subpage */
1577 register_subpage(fv
, &remain
);
1580 void qemu_flush_coalesced_mmio_buffer(void)
1583 kvm_flush_coalesced_mmio_buffer();
1586 void qemu_mutex_lock_ramlist(void)
1588 qemu_mutex_lock(&ram_list
.mutex
);
1591 void qemu_mutex_unlock_ramlist(void)
1593 qemu_mutex_unlock(&ram_list
.mutex
);
1596 void ram_block_dump(Monitor
*mon
)
1601 RCU_READ_LOCK_GUARD();
1602 monitor_printf(mon
, "%24s %8s %18s %18s %18s\n",
1603 "Block Name", "PSize", "Offset", "Used", "Total");
1604 RAMBLOCK_FOREACH(block
) {
1605 psize
= size_to_str(block
->page_size
);
1606 monitor_printf(mon
, "%24s %8s 0x%016" PRIx64
" 0x%016" PRIx64
1607 " 0x%016" PRIx64
"\n", block
->idstr
, psize
,
1608 (uint64_t)block
->offset
,
1609 (uint64_t)block
->used_length
,
1610 (uint64_t)block
->max_length
);
1617 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1618 * may or may not name the same files / on the same filesystem now as
1619 * when we actually open and map them. Iterate over the file
1620 * descriptors instead, and use qemu_fd_getpagesize().
1622 static int find_min_backend_pagesize(Object
*obj
, void *opaque
)
1624 long *hpsize_min
= opaque
;
1626 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1627 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1628 long hpsize
= host_memory_backend_pagesize(backend
);
1630 if (host_memory_backend_is_mapped(backend
) && (hpsize
< *hpsize_min
)) {
1631 *hpsize_min
= hpsize
;
1638 static int find_max_backend_pagesize(Object
*obj
, void *opaque
)
1640 long *hpsize_max
= opaque
;
1642 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1643 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1644 long hpsize
= host_memory_backend_pagesize(backend
);
1646 if (host_memory_backend_is_mapped(backend
) && (hpsize
> *hpsize_max
)) {
1647 *hpsize_max
= hpsize
;
1655 * TODO: We assume right now that all mapped host memory backends are
1656 * used as RAM, however some might be used for different purposes.
1658 long qemu_minrampagesize(void)
1660 long hpsize
= LONG_MAX
;
1661 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1663 object_child_foreach(memdev_root
, find_min_backend_pagesize
, &hpsize
);
1667 long qemu_maxrampagesize(void)
1670 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1672 object_child_foreach(memdev_root
, find_max_backend_pagesize
, &pagesize
);
1676 long qemu_minrampagesize(void)
1678 return qemu_real_host_page_size
;
1680 long qemu_maxrampagesize(void)
1682 return qemu_real_host_page_size
;
1687 static int64_t get_file_size(int fd
)
1690 #if defined(__linux__)
1693 if (fstat(fd
, &st
) < 0) {
1697 /* Special handling for devdax character devices */
1698 if (S_ISCHR(st
.st_mode
)) {
1699 g_autofree
char *subsystem_path
= NULL
;
1700 g_autofree
char *subsystem
= NULL
;
1702 subsystem_path
= g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1703 major(st
.st_rdev
), minor(st
.st_rdev
));
1704 subsystem
= g_file_read_link(subsystem_path
, NULL
);
1706 if (subsystem
&& g_str_has_suffix(subsystem
, "/dax")) {
1707 g_autofree
char *size_path
= NULL
;
1708 g_autofree
char *size_str
= NULL
;
1710 size_path
= g_strdup_printf("/sys/dev/char/%d:%d/size",
1711 major(st
.st_rdev
), minor(st
.st_rdev
));
1713 if (g_file_get_contents(size_path
, &size_str
, NULL
, NULL
)) {
1714 return g_ascii_strtoll(size_str
, NULL
, 0);
1718 #endif /* defined(__linux__) */
1720 /* st.st_size may be zero for special files yet lseek(2) works */
1721 size
= lseek(fd
, 0, SEEK_END
);
1728 static int64_t get_file_align(int fd
)
1731 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1734 if (fstat(fd
, &st
) < 0) {
1738 /* Special handling for devdax character devices */
1739 if (S_ISCHR(st
.st_mode
)) {
1740 g_autofree
char *path
= NULL
;
1741 g_autofree
char *rpath
= NULL
;
1742 struct daxctl_ctx
*ctx
;
1743 struct daxctl_region
*region
;
1746 path
= g_strdup_printf("/sys/dev/char/%d:%d",
1747 major(st
.st_rdev
), minor(st
.st_rdev
));
1748 rpath
= realpath(path
, NULL
);
1750 rc
= daxctl_new(&ctx
);
1755 daxctl_region_foreach(ctx
, region
) {
1756 if (strstr(rpath
, daxctl_region_get_path(region
))) {
1757 align
= daxctl_region_get_align(region
);
1763 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1768 static int file_ram_open(const char *path
,
1769 const char *region_name
,
1774 char *sanitized_name
;
1780 fd
= open(path
, O_RDWR
);
1782 /* @path names an existing file, use it */
1785 if (errno
== ENOENT
) {
1786 /* @path names a file that doesn't exist, create it */
1787 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0644);
1792 } else if (errno
== EISDIR
) {
1793 /* @path names a directory, create a file there */
1794 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1795 sanitized_name
= g_strdup(region_name
);
1796 for (c
= sanitized_name
; *c
!= '\0'; c
++) {
1802 filename
= g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path
,
1804 g_free(sanitized_name
);
1806 fd
= mkstemp(filename
);
1814 if (errno
!= EEXIST
&& errno
!= EINTR
) {
1815 error_setg_errno(errp
, errno
,
1816 "can't open backing store %s for guest RAM",
1821 * Try again on EINTR and EEXIST. The latter happens when
1822 * something else creates the file between our two open().
1829 static void *file_ram_alloc(RAMBlock
*block
,
1837 block
->page_size
= qemu_fd_getpagesize(fd
);
1838 if (block
->mr
->align
% block
->page_size
) {
1839 error_setg(errp
, "alignment 0x%" PRIx64
1840 " must be multiples of page size 0x%zx",
1841 block
->mr
->align
, block
->page_size
);
1843 } else if (block
->mr
->align
&& !is_power_of_2(block
->mr
->align
)) {
1844 error_setg(errp
, "alignment 0x%" PRIx64
1845 " must be a power of two", block
->mr
->align
);
1848 block
->mr
->align
= MAX(block
->page_size
, block
->mr
->align
);
1849 #if defined(__s390x__)
1850 if (kvm_enabled()) {
1851 block
->mr
->align
= MAX(block
->mr
->align
, QEMU_VMALLOC_ALIGN
);
1855 if (memory
< block
->page_size
) {
1856 error_setg(errp
, "memory size 0x" RAM_ADDR_FMT
" must be equal to "
1857 "or larger than page size 0x%zx",
1858 memory
, block
->page_size
);
1862 memory
= ROUND_UP(memory
, block
->page_size
);
1865 * ftruncate is not supported by hugetlbfs in older
1866 * hosts, so don't bother bailing out on errors.
1867 * If anything goes wrong with it under other filesystems,
1870 * Do not truncate the non-empty backend file to avoid corrupting
1871 * the existing data in the file. Disabling shrinking is not
1872 * enough. For example, the current vNVDIMM implementation stores
1873 * the guest NVDIMM labels at the end of the backend file. If the
1874 * backend file is later extended, QEMU will not be able to find
1875 * those labels. Therefore, extending the non-empty backend file
1876 * is disabled as well.
1878 if (truncate
&& ftruncate(fd
, memory
)) {
1879 perror("ftruncate");
1882 area
= qemu_ram_mmap(fd
, memory
, block
->mr
->align
,
1883 block
->flags
& RAM_SHARED
, block
->flags
& RAM_PMEM
);
1884 if (area
== MAP_FAILED
) {
1885 error_setg_errno(errp
, errno
,
1886 "unable to map backing store for guest RAM");
1895 /* Allocate space within the ram_addr_t space that governs the
1897 * Called with the ramlist lock held.
1899 static ram_addr_t
find_ram_offset(ram_addr_t size
)
1901 RAMBlock
*block
, *next_block
;
1902 ram_addr_t offset
= RAM_ADDR_MAX
, mingap
= RAM_ADDR_MAX
;
1904 assert(size
!= 0); /* it would hand out same offset multiple times */
1906 if (QLIST_EMPTY_RCU(&ram_list
.blocks
)) {
1910 RAMBLOCK_FOREACH(block
) {
1911 ram_addr_t candidate
, next
= RAM_ADDR_MAX
;
1913 /* Align blocks to start on a 'long' in the bitmap
1914 * which makes the bitmap sync'ing take the fast path.
1916 candidate
= block
->offset
+ block
->max_length
;
1917 candidate
= ROUND_UP(candidate
, BITS_PER_LONG
<< TARGET_PAGE_BITS
);
1919 /* Search for the closest following block
1922 RAMBLOCK_FOREACH(next_block
) {
1923 if (next_block
->offset
>= candidate
) {
1924 next
= MIN(next
, next_block
->offset
);
1928 /* If it fits remember our place and remember the size
1929 * of gap, but keep going so that we might find a smaller
1930 * gap to fill so avoiding fragmentation.
1932 if (next
- candidate
>= size
&& next
- candidate
< mingap
) {
1934 mingap
= next
- candidate
;
1937 trace_find_ram_offset_loop(size
, candidate
, offset
, next
, mingap
);
1940 if (offset
== RAM_ADDR_MAX
) {
1941 fprintf(stderr
, "Failed to find gap of requested size: %" PRIu64
"\n",
1946 trace_find_ram_offset(size
, offset
);
1951 static unsigned long last_ram_page(void)
1954 ram_addr_t last
= 0;
1956 RCU_READ_LOCK_GUARD();
1957 RAMBLOCK_FOREACH(block
) {
1958 last
= MAX(last
, block
->offset
+ block
->max_length
);
1960 return last
>> TARGET_PAGE_BITS
;
1963 static void qemu_ram_setup_dump(void *addr
, ram_addr_t size
)
1967 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1968 if (!machine_dump_guest_core(current_machine
)) {
1969 ret
= qemu_madvise(addr
, size
, QEMU_MADV_DONTDUMP
);
1971 perror("qemu_madvise");
1972 fprintf(stderr
, "madvise doesn't support MADV_DONTDUMP, "
1973 "but dump_guest_core=off specified\n");
1978 const char *qemu_ram_get_idstr(RAMBlock
*rb
)
1983 void *qemu_ram_get_host_addr(RAMBlock
*rb
)
1988 ram_addr_t
qemu_ram_get_offset(RAMBlock
*rb
)
1993 ram_addr_t
qemu_ram_get_used_length(RAMBlock
*rb
)
1995 return rb
->used_length
;
1998 bool qemu_ram_is_shared(RAMBlock
*rb
)
2000 return rb
->flags
& RAM_SHARED
;
2003 /* Note: Only set at the start of postcopy */
2004 bool qemu_ram_is_uf_zeroable(RAMBlock
*rb
)
2006 return rb
->flags
& RAM_UF_ZEROPAGE
;
2009 void qemu_ram_set_uf_zeroable(RAMBlock
*rb
)
2011 rb
->flags
|= RAM_UF_ZEROPAGE
;
2014 bool qemu_ram_is_migratable(RAMBlock
*rb
)
2016 return rb
->flags
& RAM_MIGRATABLE
;
2019 void qemu_ram_set_migratable(RAMBlock
*rb
)
2021 rb
->flags
|= RAM_MIGRATABLE
;
2024 void qemu_ram_unset_migratable(RAMBlock
*rb
)
2026 rb
->flags
&= ~RAM_MIGRATABLE
;
2029 /* Called with iothread lock held. */
2030 void qemu_ram_set_idstr(RAMBlock
*new_block
, const char *name
, DeviceState
*dev
)
2035 assert(!new_block
->idstr
[0]);
2038 char *id
= qdev_get_dev_path(dev
);
2040 snprintf(new_block
->idstr
, sizeof(new_block
->idstr
), "%s/", id
);
2044 pstrcat(new_block
->idstr
, sizeof(new_block
->idstr
), name
);
2046 RCU_READ_LOCK_GUARD();
2047 RAMBLOCK_FOREACH(block
) {
2048 if (block
!= new_block
&&
2049 !strcmp(block
->idstr
, new_block
->idstr
)) {
2050 fprintf(stderr
, "RAMBlock \"%s\" already registered, abort!\n",
2057 /* Called with iothread lock held. */
2058 void qemu_ram_unset_idstr(RAMBlock
*block
)
2060 /* FIXME: arch_init.c assumes that this is not called throughout
2061 * migration. Ignore the problem since hot-unplug during migration
2062 * does not work anyway.
2065 memset(block
->idstr
, 0, sizeof(block
->idstr
));
2069 size_t qemu_ram_pagesize(RAMBlock
*rb
)
2071 return rb
->page_size
;
2074 /* Returns the largest size of page in use */
2075 size_t qemu_ram_pagesize_largest(void)
2080 RAMBLOCK_FOREACH(block
) {
2081 largest
= MAX(largest
, qemu_ram_pagesize(block
));
2087 static int memory_try_enable_merging(void *addr
, size_t len
)
2089 if (!machine_mem_merge(current_machine
)) {
2090 /* disabled by the user */
2094 return qemu_madvise(addr
, len
, QEMU_MADV_MERGEABLE
);
2097 /* Only legal before guest might have detected the memory size: e.g. on
2098 * incoming migration, or right after reset.
2100 * As memory core doesn't know how is memory accessed, it is up to
2101 * resize callback to update device state and/or add assertions to detect
2102 * misuse, if necessary.
2104 int qemu_ram_resize(RAMBlock
*block
, ram_addr_t newsize
, Error
**errp
)
2106 const ram_addr_t unaligned_size
= newsize
;
2110 newsize
= HOST_PAGE_ALIGN(newsize
);
2112 if (block
->used_length
== newsize
) {
2114 * We don't have to resize the ram block (which only knows aligned
2115 * sizes), however, we have to notify if the unaligned size changed.
2117 if (unaligned_size
!= memory_region_size(block
->mr
)) {
2118 memory_region_set_size(block
->mr
, unaligned_size
);
2119 if (block
->resized
) {
2120 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
2126 if (!(block
->flags
& RAM_RESIZEABLE
)) {
2127 error_setg_errno(errp
, EINVAL
,
2128 "Length mismatch: %s: 0x" RAM_ADDR_FMT
2129 " in != 0x" RAM_ADDR_FMT
, block
->idstr
,
2130 newsize
, block
->used_length
);
2134 if (block
->max_length
< newsize
) {
2135 error_setg_errno(errp
, EINVAL
,
2136 "Length too large: %s: 0x" RAM_ADDR_FMT
2137 " > 0x" RAM_ADDR_FMT
, block
->idstr
,
2138 newsize
, block
->max_length
);
2142 cpu_physical_memory_clear_dirty_range(block
->offset
, block
->used_length
);
2143 block
->used_length
= newsize
;
2144 cpu_physical_memory_set_dirty_range(block
->offset
, block
->used_length
,
2146 memory_region_set_size(block
->mr
, unaligned_size
);
2147 if (block
->resized
) {
2148 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
2154 * Trigger sync on the given ram block for range [start, start + length]
2155 * with the backing store if one is available.
2157 * @Note: this is supposed to be a synchronous op.
2159 void qemu_ram_msync(RAMBlock
*block
, ram_addr_t start
, ram_addr_t length
)
2161 /* The requested range should fit in within the block range */
2162 g_assert((start
+ length
) <= block
->used_length
);
2164 #ifdef CONFIG_LIBPMEM
2165 /* The lack of support for pmem should not block the sync */
2166 if (ramblock_is_pmem(block
)) {
2167 void *addr
= ramblock_ptr(block
, start
);
2168 pmem_persist(addr
, length
);
2172 if (block
->fd
>= 0) {
2174 * Case there is no support for PMEM or the memory has not been
2175 * specified as persistent (or is not one) - use the msync.
2176 * Less optimal but still achieves the same goal
2178 void *addr
= ramblock_ptr(block
, start
);
2179 if (qemu_msync(addr
, length
, block
->fd
)) {
2180 warn_report("%s: failed to sync memory range: start: "
2181 RAM_ADDR_FMT
" length: " RAM_ADDR_FMT
,
2182 __func__
, start
, length
);
2187 /* Called with ram_list.mutex held */
2188 static void dirty_memory_extend(ram_addr_t old_ram_size
,
2189 ram_addr_t new_ram_size
)
2191 ram_addr_t old_num_blocks
= DIV_ROUND_UP(old_ram_size
,
2192 DIRTY_MEMORY_BLOCK_SIZE
);
2193 ram_addr_t new_num_blocks
= DIV_ROUND_UP(new_ram_size
,
2194 DIRTY_MEMORY_BLOCK_SIZE
);
2197 /* Only need to extend if block count increased */
2198 if (new_num_blocks
<= old_num_blocks
) {
2202 for (i
= 0; i
< DIRTY_MEMORY_NUM
; i
++) {
2203 DirtyMemoryBlocks
*old_blocks
;
2204 DirtyMemoryBlocks
*new_blocks
;
2207 old_blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[i
]);
2208 new_blocks
= g_malloc(sizeof(*new_blocks
) +
2209 sizeof(new_blocks
->blocks
[0]) * new_num_blocks
);
2211 if (old_num_blocks
) {
2212 memcpy(new_blocks
->blocks
, old_blocks
->blocks
,
2213 old_num_blocks
* sizeof(old_blocks
->blocks
[0]));
2216 for (j
= old_num_blocks
; j
< new_num_blocks
; j
++) {
2217 new_blocks
->blocks
[j
] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE
);
2220 qatomic_rcu_set(&ram_list
.dirty_memory
[i
], new_blocks
);
2223 g_free_rcu(old_blocks
, rcu
);
2228 static void ram_block_add(RAMBlock
*new_block
, Error
**errp
, bool shared
)
2231 RAMBlock
*last_block
= NULL
;
2232 ram_addr_t old_ram_size
, new_ram_size
;
2235 old_ram_size
= last_ram_page();
2237 qemu_mutex_lock_ramlist();
2238 new_block
->offset
= find_ram_offset(new_block
->max_length
);
2240 if (!new_block
->host
) {
2241 if (xen_enabled()) {
2242 xen_ram_alloc(new_block
->offset
, new_block
->max_length
,
2243 new_block
->mr
, &err
);
2245 error_propagate(errp
, err
);
2246 qemu_mutex_unlock_ramlist();
2250 new_block
->host
= phys_mem_alloc(new_block
->max_length
,
2251 &new_block
->mr
->align
, shared
);
2252 if (!new_block
->host
) {
2253 error_setg_errno(errp
, errno
,
2254 "cannot set up guest memory '%s'",
2255 memory_region_name(new_block
->mr
));
2256 qemu_mutex_unlock_ramlist();
2259 memory_try_enable_merging(new_block
->host
, new_block
->max_length
);
2263 new_ram_size
= MAX(old_ram_size
,
2264 (new_block
->offset
+ new_block
->max_length
) >> TARGET_PAGE_BITS
);
2265 if (new_ram_size
> old_ram_size
) {
2266 dirty_memory_extend(old_ram_size
, new_ram_size
);
2268 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2269 * QLIST (which has an RCU-friendly variant) does not have insertion at
2270 * tail, so save the last element in last_block.
2272 RAMBLOCK_FOREACH(block
) {
2274 if (block
->max_length
< new_block
->max_length
) {
2279 QLIST_INSERT_BEFORE_RCU(block
, new_block
, next
);
2280 } else if (last_block
) {
2281 QLIST_INSERT_AFTER_RCU(last_block
, new_block
, next
);
2282 } else { /* list is empty */
2283 QLIST_INSERT_HEAD_RCU(&ram_list
.blocks
, new_block
, next
);
2285 ram_list
.mru_block
= NULL
;
2287 /* Write list before version */
2290 qemu_mutex_unlock_ramlist();
2292 cpu_physical_memory_set_dirty_range(new_block
->offset
,
2293 new_block
->used_length
,
2296 if (new_block
->host
) {
2297 qemu_ram_setup_dump(new_block
->host
, new_block
->max_length
);
2298 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_HUGEPAGE
);
2300 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
2301 * Configure it unless the machine is a qtest server, in which case
2302 * KVM is not used and it may be forked (eg for fuzzing purposes).
2304 if (!qtest_enabled()) {
2305 qemu_madvise(new_block
->host
, new_block
->max_length
,
2306 QEMU_MADV_DONTFORK
);
2308 ram_block_notify_add(new_block
->host
, new_block
->max_length
);
2313 RAMBlock
*qemu_ram_alloc_from_fd(ram_addr_t size
, MemoryRegion
*mr
,
2314 uint32_t ram_flags
, int fd
,
2317 RAMBlock
*new_block
;
2318 Error
*local_err
= NULL
;
2319 int64_t file_size
, file_align
;
2321 /* Just support these ram flags by now. */
2322 assert((ram_flags
& ~(RAM_SHARED
| RAM_PMEM
)) == 0);
2324 if (xen_enabled()) {
2325 error_setg(errp
, "-mem-path not supported with Xen");
2329 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2331 "host lacks kvm mmu notifiers, -mem-path unsupported");
2335 if (phys_mem_alloc
!= qemu_anon_ram_alloc
) {
2337 * file_ram_alloc() needs to allocate just like
2338 * phys_mem_alloc, but we haven't bothered to provide
2342 "-mem-path not supported with this accelerator");
2346 size
= HOST_PAGE_ALIGN(size
);
2347 file_size
= get_file_size(fd
);
2348 if (file_size
> 0 && file_size
< size
) {
2349 error_setg(errp
, "backing store size 0x%" PRIx64
2350 " does not match 'size' option 0x" RAM_ADDR_FMT
,
2355 file_align
= get_file_align(fd
);
2356 if (file_align
> 0 && mr
&& file_align
> mr
->align
) {
2357 error_setg(errp
, "backing store align 0x%" PRIx64
2358 " is larger than 'align' option 0x%" PRIx64
,
2359 file_align
, mr
->align
);
2363 new_block
= g_malloc0(sizeof(*new_block
));
2365 new_block
->used_length
= size
;
2366 new_block
->max_length
= size
;
2367 new_block
->flags
= ram_flags
;
2368 new_block
->host
= file_ram_alloc(new_block
, size
, fd
, !file_size
, errp
);
2369 if (!new_block
->host
) {
2374 ram_block_add(new_block
, &local_err
, ram_flags
& RAM_SHARED
);
2377 error_propagate(errp
, local_err
);
2385 RAMBlock
*qemu_ram_alloc_from_file(ram_addr_t size
, MemoryRegion
*mr
,
2386 uint32_t ram_flags
, const char *mem_path
,
2393 fd
= file_ram_open(mem_path
, memory_region_name(mr
), &created
, errp
);
2398 block
= qemu_ram_alloc_from_fd(size
, mr
, ram_flags
, fd
, errp
);
2412 RAMBlock
*qemu_ram_alloc_internal(ram_addr_t size
, ram_addr_t max_size
,
2413 void (*resized
)(const char*,
2416 void *host
, bool resizeable
, bool share
,
2417 MemoryRegion
*mr
, Error
**errp
)
2419 RAMBlock
*new_block
;
2420 Error
*local_err
= NULL
;
2422 size
= HOST_PAGE_ALIGN(size
);
2423 max_size
= HOST_PAGE_ALIGN(max_size
);
2424 new_block
= g_malloc0(sizeof(*new_block
));
2426 new_block
->resized
= resized
;
2427 new_block
->used_length
= size
;
2428 new_block
->max_length
= max_size
;
2429 assert(max_size
>= size
);
2431 new_block
->page_size
= qemu_real_host_page_size
;
2432 new_block
->host
= host
;
2434 new_block
->flags
|= RAM_PREALLOC
;
2437 new_block
->flags
|= RAM_RESIZEABLE
;
2439 ram_block_add(new_block
, &local_err
, share
);
2442 error_propagate(errp
, local_err
);
2448 RAMBlock
*qemu_ram_alloc_from_ptr(ram_addr_t size
, void *host
,
2449 MemoryRegion
*mr
, Error
**errp
)
2451 return qemu_ram_alloc_internal(size
, size
, NULL
, host
, false,
2455 RAMBlock
*qemu_ram_alloc(ram_addr_t size
, bool share
,
2456 MemoryRegion
*mr
, Error
**errp
)
2458 return qemu_ram_alloc_internal(size
, size
, NULL
, NULL
, false,
2462 RAMBlock
*qemu_ram_alloc_resizeable(ram_addr_t size
, ram_addr_t maxsz
,
2463 void (*resized
)(const char*,
2466 MemoryRegion
*mr
, Error
**errp
)
2468 return qemu_ram_alloc_internal(size
, maxsz
, resized
, NULL
, true,
2472 static void reclaim_ramblock(RAMBlock
*block
)
2474 if (block
->flags
& RAM_PREALLOC
) {
2476 } else if (xen_enabled()) {
2477 xen_invalidate_map_cache_entry(block
->host
);
2479 } else if (block
->fd
>= 0) {
2480 qemu_ram_munmap(block
->fd
, block
->host
, block
->max_length
);
2484 qemu_anon_ram_free(block
->host
, block
->max_length
);
2489 void qemu_ram_free(RAMBlock
*block
)
2496 ram_block_notify_remove(block
->host
, block
->max_length
);
2499 qemu_mutex_lock_ramlist();
2500 QLIST_REMOVE_RCU(block
, next
);
2501 ram_list
.mru_block
= NULL
;
2502 /* Write list before version */
2505 call_rcu(block
, reclaim_ramblock
, rcu
);
2506 qemu_mutex_unlock_ramlist();
2510 void qemu_ram_remap(ram_addr_t addr
, ram_addr_t length
)
2517 RAMBLOCK_FOREACH(block
) {
2518 offset
= addr
- block
->offset
;
2519 if (offset
< block
->max_length
) {
2520 vaddr
= ramblock_ptr(block
, offset
);
2521 if (block
->flags
& RAM_PREALLOC
) {
2523 } else if (xen_enabled()) {
2527 if (block
->fd
>= 0) {
2528 flags
|= (block
->flags
& RAM_SHARED
?
2529 MAP_SHARED
: MAP_PRIVATE
);
2530 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2531 flags
, block
->fd
, offset
);
2534 * Remap needs to match alloc. Accelerators that
2535 * set phys_mem_alloc never remap. If they did,
2536 * we'd need a remap hook here.
2538 assert(phys_mem_alloc
== qemu_anon_ram_alloc
);
2540 flags
|= MAP_PRIVATE
| MAP_ANONYMOUS
;
2541 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2544 if (area
!= vaddr
) {
2545 error_report("Could not remap addr: "
2546 RAM_ADDR_FMT
"@" RAM_ADDR_FMT
"",
2550 memory_try_enable_merging(vaddr
, length
);
2551 qemu_ram_setup_dump(vaddr
, length
);
2556 #endif /* !_WIN32 */
2558 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2559 * This should not be used for general purpose DMA. Use address_space_map
2560 * or address_space_rw instead. For local memory (e.g. video ram) that the
2561 * device owns, use memory_region_get_ram_ptr.
2563 * Called within RCU critical section.
2565 void *qemu_map_ram_ptr(RAMBlock
*ram_block
, ram_addr_t addr
)
2567 RAMBlock
*block
= ram_block
;
2569 if (block
== NULL
) {
2570 block
= qemu_get_ram_block(addr
);
2571 addr
-= block
->offset
;
2574 if (xen_enabled() && block
->host
== NULL
) {
2575 /* We need to check if the requested address is in the RAM
2576 * because we don't want to map the entire memory in QEMU.
2577 * In that case just map until the end of the page.
2579 if (block
->offset
== 0) {
2580 return xen_map_cache(addr
, 0, 0, false);
2583 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, false);
2585 return ramblock_ptr(block
, addr
);
2588 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2589 * but takes a size argument.
2591 * Called within RCU critical section.
2593 static void *qemu_ram_ptr_length(RAMBlock
*ram_block
, ram_addr_t addr
,
2594 hwaddr
*size
, bool lock
)
2596 RAMBlock
*block
= ram_block
;
2601 if (block
== NULL
) {
2602 block
= qemu_get_ram_block(addr
);
2603 addr
-= block
->offset
;
2605 *size
= MIN(*size
, block
->max_length
- addr
);
2607 if (xen_enabled() && block
->host
== NULL
) {
2608 /* We need to check if the requested address is in the RAM
2609 * because we don't want to map the entire memory in QEMU.
2610 * In that case just map the requested area.
2612 if (block
->offset
== 0) {
2613 return xen_map_cache(addr
, *size
, lock
, lock
);
2616 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, lock
);
2619 return ramblock_ptr(block
, addr
);
2622 /* Return the offset of a hostpointer within a ramblock */
2623 ram_addr_t
qemu_ram_block_host_offset(RAMBlock
*rb
, void *host
)
2625 ram_addr_t res
= (uint8_t *)host
- (uint8_t *)rb
->host
;
2626 assert((uintptr_t)host
>= (uintptr_t)rb
->host
);
2627 assert(res
< rb
->max_length
);
2633 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2636 * ptr: Host pointer to look up
2637 * round_offset: If true round the result offset down to a page boundary
2638 * *ram_addr: set to result ram_addr
2639 * *offset: set to result offset within the RAMBlock
2641 * Returns: RAMBlock (or NULL if not found)
2643 * By the time this function returns, the returned pointer is not protected
2644 * by RCU anymore. If the caller is not within an RCU critical section and
2645 * does not hold the iothread lock, it must have other means of protecting the
2646 * pointer, such as a reference to the region that includes the incoming
2649 RAMBlock
*qemu_ram_block_from_host(void *ptr
, bool round_offset
,
2653 uint8_t *host
= ptr
;
2655 if (xen_enabled()) {
2656 ram_addr_t ram_addr
;
2657 RCU_READ_LOCK_GUARD();
2658 ram_addr
= xen_ram_addr_from_mapcache(ptr
);
2659 block
= qemu_get_ram_block(ram_addr
);
2661 *offset
= ram_addr
- block
->offset
;
2666 RCU_READ_LOCK_GUARD();
2667 block
= qatomic_rcu_read(&ram_list
.mru_block
);
2668 if (block
&& block
->host
&& host
- block
->host
< block
->max_length
) {
2672 RAMBLOCK_FOREACH(block
) {
2673 /* This case append when the block is not mapped. */
2674 if (block
->host
== NULL
) {
2677 if (host
- block
->host
< block
->max_length
) {
2685 *offset
= (host
- block
->host
);
2687 *offset
&= TARGET_PAGE_MASK
;
2693 * Finds the named RAMBlock
2695 * name: The name of RAMBlock to find
2697 * Returns: RAMBlock (or NULL if not found)
2699 RAMBlock
*qemu_ram_block_by_name(const char *name
)
2703 RAMBLOCK_FOREACH(block
) {
2704 if (!strcmp(name
, block
->idstr
)) {
2712 /* Some of the softmmu routines need to translate from a host pointer
2713 (typically a TLB entry) back to a ram offset. */
2714 ram_addr_t
qemu_ram_addr_from_host(void *ptr
)
2719 block
= qemu_ram_block_from_host(ptr
, false, &offset
);
2721 return RAM_ADDR_INVALID
;
2724 return block
->offset
+ offset
;
2727 /* Generate a debug exception if a watchpoint has been hit. */
2728 void cpu_check_watchpoint(CPUState
*cpu
, vaddr addr
, vaddr len
,
2729 MemTxAttrs attrs
, int flags
, uintptr_t ra
)
2731 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
2734 assert(tcg_enabled());
2735 if (cpu
->watchpoint_hit
) {
2737 * We re-entered the check after replacing the TB.
2738 * Now raise the debug interrupt so that it will
2739 * trigger after the current instruction.
2741 qemu_mutex_lock_iothread();
2742 cpu_interrupt(cpu
, CPU_INTERRUPT_DEBUG
);
2743 qemu_mutex_unlock_iothread();
2747 addr
= cc
->adjust_watchpoint_address(cpu
, addr
, len
);
2748 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
2749 if (watchpoint_address_matches(wp
, addr
, len
)
2750 && (wp
->flags
& flags
)) {
2751 if (replay_running_debug()) {
2753 * Don't process the watchpoints when we are
2754 * in a reverse debugging operation.
2756 replay_breakpoint();
2759 if (flags
== BP_MEM_READ
) {
2760 wp
->flags
|= BP_WATCHPOINT_HIT_READ
;
2762 wp
->flags
|= BP_WATCHPOINT_HIT_WRITE
;
2764 wp
->hitaddr
= MAX(addr
, wp
->vaddr
);
2765 wp
->hitattrs
= attrs
;
2766 if (!cpu
->watchpoint_hit
) {
2767 if (wp
->flags
& BP_CPU
&&
2768 !cc
->debug_check_watchpoint(cpu
, wp
)) {
2769 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
2772 cpu
->watchpoint_hit
= wp
;
2775 tb_check_watchpoint(cpu
, ra
);
2776 if (wp
->flags
& BP_STOP_BEFORE_ACCESS
) {
2777 cpu
->exception_index
= EXCP_DEBUG
;
2779 cpu_loop_exit_restore(cpu
, ra
);
2781 /* Force execution of one insn next time. */
2782 cpu
->cflags_next_tb
= 1 | curr_cflags();
2785 cpu_restore_state(cpu
, ra
, true);
2787 cpu_loop_exit_noexc(cpu
);
2791 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
2796 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2797 MemTxAttrs attrs
, void *buf
, hwaddr len
);
2798 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2799 const void *buf
, hwaddr len
);
2800 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
2801 bool is_write
, MemTxAttrs attrs
);
2803 static MemTxResult
subpage_read(void *opaque
, hwaddr addr
, uint64_t *data
,
2804 unsigned len
, MemTxAttrs attrs
)
2806 subpage_t
*subpage
= opaque
;
2810 #if defined(DEBUG_SUBPAGE)
2811 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
"\n", __func__
,
2812 subpage
, len
, addr
);
2814 res
= flatview_read(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2818 *data
= ldn_p(buf
, len
);
2822 static MemTxResult
subpage_write(void *opaque
, hwaddr addr
,
2823 uint64_t value
, unsigned len
, MemTxAttrs attrs
)
2825 subpage_t
*subpage
= opaque
;
2828 #if defined(DEBUG_SUBPAGE)
2829 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2830 " value %"PRIx64
"\n",
2831 __func__
, subpage
, len
, addr
, value
);
2833 stn_p(buf
, len
, value
);
2834 return flatview_write(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2837 static bool subpage_accepts(void *opaque
, hwaddr addr
,
2838 unsigned len
, bool is_write
,
2841 subpage_t
*subpage
= opaque
;
2842 #if defined(DEBUG_SUBPAGE)
2843 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx
"\n",
2844 __func__
, subpage
, is_write
? 'w' : 'r', len
, addr
);
2847 return flatview_access_valid(subpage
->fv
, addr
+ subpage
->base
,
2848 len
, is_write
, attrs
);
2851 static const MemoryRegionOps subpage_ops
= {
2852 .read_with_attrs
= subpage_read
,
2853 .write_with_attrs
= subpage_write
,
2854 .impl
.min_access_size
= 1,
2855 .impl
.max_access_size
= 8,
2856 .valid
.min_access_size
= 1,
2857 .valid
.max_access_size
= 8,
2858 .valid
.accepts
= subpage_accepts
,
2859 .endianness
= DEVICE_NATIVE_ENDIAN
,
2862 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
2867 if (start
>= TARGET_PAGE_SIZE
|| end
>= TARGET_PAGE_SIZE
)
2869 idx
= SUBPAGE_IDX(start
);
2870 eidx
= SUBPAGE_IDX(end
);
2871 #if defined(DEBUG_SUBPAGE)
2872 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2873 __func__
, mmio
, start
, end
, idx
, eidx
, section
);
2875 for (; idx
<= eidx
; idx
++) {
2876 mmio
->sub_section
[idx
] = section
;
2882 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
)
2886 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2887 mmio
= g_malloc0(sizeof(subpage_t
) + TARGET_PAGE_SIZE
* sizeof(uint16_t));
2890 memory_region_init_io(&mmio
->iomem
, NULL
, &subpage_ops
, mmio
,
2891 NULL
, TARGET_PAGE_SIZE
);
2892 mmio
->iomem
.subpage
= true;
2893 #if defined(DEBUG_SUBPAGE)
2894 printf("%s: %p base " TARGET_FMT_plx
" len %08x\n", __func__
,
2895 mmio
, base
, TARGET_PAGE_SIZE
);
2901 static uint16_t dummy_section(PhysPageMap
*map
, FlatView
*fv
, MemoryRegion
*mr
)
2904 MemoryRegionSection section
= {
2907 .offset_within_address_space
= 0,
2908 .offset_within_region
= 0,
2909 .size
= int128_2_64(),
2912 return phys_section_add(map
, §ion
);
2915 MemoryRegionSection
*iotlb_to_section(CPUState
*cpu
,
2916 hwaddr index
, MemTxAttrs attrs
)
2918 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
2919 CPUAddressSpace
*cpuas
= &cpu
->cpu_ases
[asidx
];
2920 AddressSpaceDispatch
*d
= qatomic_rcu_read(&cpuas
->memory_dispatch
);
2921 MemoryRegionSection
*sections
= d
->map
.sections
;
2923 return §ions
[index
& ~TARGET_PAGE_MASK
];
2926 static void io_mem_init(void)
2928 memory_region_init_io(&io_mem_unassigned
, NULL
, &unassigned_mem_ops
, NULL
,
2932 AddressSpaceDispatch
*address_space_dispatch_new(FlatView
*fv
)
2934 AddressSpaceDispatch
*d
= g_new0(AddressSpaceDispatch
, 1);
2937 n
= dummy_section(&d
->map
, fv
, &io_mem_unassigned
);
2938 assert(n
== PHYS_SECTION_UNASSIGNED
);
2940 d
->phys_map
= (PhysPageEntry
) { .ptr
= PHYS_MAP_NODE_NIL
, .skip
= 1 };
2945 void address_space_dispatch_free(AddressSpaceDispatch
*d
)
2947 phys_sections_free(&d
->map
);
2951 static void do_nothing(CPUState
*cpu
, run_on_cpu_data d
)
2955 static void tcg_log_global_after_sync(MemoryListener
*listener
)
2957 CPUAddressSpace
*cpuas
;
2959 /* Wait for the CPU to end the current TB. This avoids the following
2963 * ---------------------- -------------------------
2964 * TLB check -> slow path
2965 * notdirty_mem_write
2969 * TLB check -> fast path
2973 * by pushing the migration thread's memory read after the vCPU thread has
2974 * written the memory.
2976 if (replay_mode
== REPLAY_MODE_NONE
) {
2978 * VGA can make calls to this function while updating the screen.
2979 * In record/replay mode this causes a deadlock, because
2980 * run_on_cpu waits for rr mutex. Therefore no races are possible
2981 * in this case and no need for making run_on_cpu when
2982 * record/replay is not enabled.
2984 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2985 run_on_cpu(cpuas
->cpu
, do_nothing
, RUN_ON_CPU_NULL
);
2989 static void tcg_commit(MemoryListener
*listener
)
2991 CPUAddressSpace
*cpuas
;
2992 AddressSpaceDispatch
*d
;
2994 assert(tcg_enabled());
2995 /* since each CPU stores ram addresses in its TLB cache, we must
2996 reset the modified entries */
2997 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2998 cpu_reloading_memory_map();
2999 /* The CPU and TLB are protected by the iothread lock.
3000 * We reload the dispatch pointer now because cpu_reloading_memory_map()
3001 * may have split the RCU critical section.
3003 d
= address_space_to_dispatch(cpuas
->as
);
3004 qatomic_rcu_set(&cpuas
->memory_dispatch
, d
);
3005 tlb_flush(cpuas
->cpu
);
3008 static void memory_map_init(void)
3010 system_memory
= g_malloc(sizeof(*system_memory
));
3012 memory_region_init(system_memory
, NULL
, "system", UINT64_MAX
);
3013 address_space_init(&address_space_memory
, system_memory
, "memory");
3015 system_io
= g_malloc(sizeof(*system_io
));
3016 memory_region_init_io(system_io
, NULL
, &unassigned_io_ops
, NULL
, "io",
3018 address_space_init(&address_space_io
, system_io
, "I/O");
3021 MemoryRegion
*get_system_memory(void)
3023 return system_memory
;
3026 MemoryRegion
*get_system_io(void)
3031 #endif /* !defined(CONFIG_USER_ONLY) */
3033 /* physical memory access (slow version, mainly for debug) */
3034 #if defined(CONFIG_USER_ONLY)
3035 int cpu_memory_rw_debug(CPUState
*cpu
, target_ulong addr
,
3036 void *ptr
, target_ulong len
, bool is_write
)
3039 target_ulong l
, page
;
3044 page
= addr
& TARGET_PAGE_MASK
;
3045 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3048 flags
= page_get_flags(page
);
3049 if (!(flags
& PAGE_VALID
))
3052 if (!(flags
& PAGE_WRITE
))
3054 /* XXX: this code should not depend on lock_user */
3055 if (!(p
= lock_user(VERIFY_WRITE
, addr
, l
, 0)))
3058 unlock_user(p
, addr
, l
);
3060 if (!(flags
& PAGE_READ
))
3062 /* XXX: this code should not depend on lock_user */
3063 if (!(p
= lock_user(VERIFY_READ
, addr
, l
, 1)))
3066 unlock_user(p
, addr
, 0);
3077 static void invalidate_and_set_dirty(MemoryRegion
*mr
, hwaddr addr
,
3080 uint8_t dirty_log_mask
= memory_region_get_dirty_log_mask(mr
);
3081 addr
+= memory_region_get_ram_addr(mr
);
3083 /* No early return if dirty_log_mask is or becomes 0, because
3084 * cpu_physical_memory_set_dirty_range will still call
3085 * xen_modified_memory.
3087 if (dirty_log_mask
) {
3089 cpu_physical_memory_range_includes_clean(addr
, length
, dirty_log_mask
);
3091 if (dirty_log_mask
& (1 << DIRTY_MEMORY_CODE
)) {
3092 assert(tcg_enabled());
3093 tb_invalidate_phys_range(addr
, addr
+ length
);
3094 dirty_log_mask
&= ~(1 << DIRTY_MEMORY_CODE
);
3096 cpu_physical_memory_set_dirty_range(addr
, length
, dirty_log_mask
);
3099 void memory_region_flush_rom_device(MemoryRegion
*mr
, hwaddr addr
, hwaddr size
)
3102 * In principle this function would work on other memory region types too,
3103 * but the ROM device use case is the only one where this operation is
3104 * necessary. Other memory regions should use the
3105 * address_space_read/write() APIs.
3107 assert(memory_region_is_romd(mr
));
3109 invalidate_and_set_dirty(mr
, addr
, size
);
3112 static int memory_access_size(MemoryRegion
*mr
, unsigned l
, hwaddr addr
)
3114 unsigned access_size_max
= mr
->ops
->valid
.max_access_size
;
3116 /* Regions are assumed to support 1-4 byte accesses unless
3117 otherwise specified. */
3118 if (access_size_max
== 0) {
3119 access_size_max
= 4;
3122 /* Bound the maximum access by the alignment of the address. */
3123 if (!mr
->ops
->impl
.unaligned
) {
3124 unsigned align_size_max
= addr
& -addr
;
3125 if (align_size_max
!= 0 && align_size_max
< access_size_max
) {
3126 access_size_max
= align_size_max
;
3130 /* Don't attempt accesses larger than the maximum. */
3131 if (l
> access_size_max
) {
3132 l
= access_size_max
;
3139 static bool prepare_mmio_access(MemoryRegion
*mr
)
3141 bool unlocked
= !qemu_mutex_iothread_locked();
3142 bool release_lock
= false;
3145 qemu_mutex_lock_iothread();
3147 release_lock
= true;
3149 if (mr
->flush_coalesced_mmio
) {
3151 qemu_mutex_lock_iothread();
3153 qemu_flush_coalesced_mmio_buffer();
3155 qemu_mutex_unlock_iothread();
3159 return release_lock
;
3162 /* Called within RCU critical section. */
3163 static MemTxResult
flatview_write_continue(FlatView
*fv
, hwaddr addr
,
3166 hwaddr len
, hwaddr addr1
,
3167 hwaddr l
, MemoryRegion
*mr
)
3171 MemTxResult result
= MEMTX_OK
;
3172 bool release_lock
= false;
3173 const uint8_t *buf
= ptr
;
3176 if (!memory_access_is_direct(mr
, true)) {
3177 release_lock
|= prepare_mmio_access(mr
);
3178 l
= memory_access_size(mr
, l
, addr1
);
3179 /* XXX: could force current_cpu to NULL to avoid
3181 val
= ldn_he_p(buf
, l
);
3182 result
|= memory_region_dispatch_write(mr
, addr1
, val
,
3183 size_memop(l
), attrs
);
3186 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
3187 memcpy(ram_ptr
, buf
, l
);
3188 invalidate_and_set_dirty(mr
, addr1
, l
);
3192 qemu_mutex_unlock_iothread();
3193 release_lock
= false;
3205 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
3211 /* Called from RCU critical section. */
3212 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
3213 const void *buf
, hwaddr len
)
3218 MemTxResult result
= MEMTX_OK
;
3221 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
3222 result
= flatview_write_continue(fv
, addr
, attrs
, buf
, len
,
3228 /* Called within RCU critical section. */
3229 MemTxResult
flatview_read_continue(FlatView
*fv
, hwaddr addr
,
3230 MemTxAttrs attrs
, void *ptr
,
3231 hwaddr len
, hwaddr addr1
, hwaddr l
,
3236 MemTxResult result
= MEMTX_OK
;
3237 bool release_lock
= false;
3241 if (!memory_access_is_direct(mr
, false)) {
3243 release_lock
|= prepare_mmio_access(mr
);
3244 l
= memory_access_size(mr
, l
, addr1
);
3245 result
|= memory_region_dispatch_read(mr
, addr1
, &val
,
3246 size_memop(l
), attrs
);
3247 stn_he_p(buf
, l
, val
);
3250 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
3251 memcpy(buf
, ram_ptr
, l
);
3255 qemu_mutex_unlock_iothread();
3256 release_lock
= false;
3268 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
3274 /* Called from RCU critical section. */
3275 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
3276 MemTxAttrs attrs
, void *buf
, hwaddr len
)
3283 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
3284 return flatview_read_continue(fv
, addr
, attrs
, buf
, len
,
3288 MemTxResult
address_space_read_full(AddressSpace
*as
, hwaddr addr
,
3289 MemTxAttrs attrs
, void *buf
, hwaddr len
)
3291 MemTxResult result
= MEMTX_OK
;
3295 RCU_READ_LOCK_GUARD();
3296 fv
= address_space_to_flatview(as
);
3297 result
= flatview_read(fv
, addr
, attrs
, buf
, len
);
3303 MemTxResult
address_space_write(AddressSpace
*as
, hwaddr addr
,
3305 const void *buf
, hwaddr len
)
3307 MemTxResult result
= MEMTX_OK
;
3311 RCU_READ_LOCK_GUARD();
3312 fv
= address_space_to_flatview(as
);
3313 result
= flatview_write(fv
, addr
, attrs
, buf
, len
);
3319 MemTxResult
address_space_rw(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
,
3320 void *buf
, hwaddr len
, bool is_write
)
3323 return address_space_write(as
, addr
, attrs
, buf
, len
);
3325 return address_space_read_full(as
, addr
, attrs
, buf
, len
);
3329 void cpu_physical_memory_rw(hwaddr addr
, void *buf
,
3330 hwaddr len
, bool is_write
)
3332 address_space_rw(&address_space_memory
, addr
, MEMTXATTRS_UNSPECIFIED
,
3333 buf
, len
, is_write
);
3336 enum write_rom_type
{
3341 static inline MemTxResult
address_space_write_rom_internal(AddressSpace
*as
,
3346 enum write_rom_type type
)
3352 const uint8_t *buf
= ptr
;
3354 RCU_READ_LOCK_GUARD();
3357 mr
= address_space_translate(as
, addr
, &addr1
, &l
, true, attrs
);
3359 if (!(memory_region_is_ram(mr
) ||
3360 memory_region_is_romd(mr
))) {
3361 l
= memory_access_size(mr
, l
, addr1
);
3364 ram_ptr
= qemu_map_ram_ptr(mr
->ram_block
, addr1
);
3367 memcpy(ram_ptr
, buf
, l
);
3368 invalidate_and_set_dirty(mr
, addr1
, l
);
3371 flush_icache_range((uintptr_t)ram_ptr
, (uintptr_t)ram_ptr
+ l
);
3382 /* used for ROM loading : can write in RAM and ROM */
3383 MemTxResult
address_space_write_rom(AddressSpace
*as
, hwaddr addr
,
3385 const void *buf
, hwaddr len
)
3387 return address_space_write_rom_internal(as
, addr
, attrs
,
3388 buf
, len
, WRITE_DATA
);
3391 void cpu_flush_icache_range(hwaddr start
, hwaddr len
)
3394 * This function should do the same thing as an icache flush that was
3395 * triggered from within the guest. For TCG we are always cache coherent,
3396 * so there is no need to flush anything. For KVM / Xen we need to flush
3397 * the host's instruction cache at least.
3399 if (tcg_enabled()) {
3403 address_space_write_rom_internal(&address_space_memory
,
3404 start
, MEMTXATTRS_UNSPECIFIED
,
3405 NULL
, len
, FLUSH_CACHE
);
3416 static BounceBuffer bounce
;
3418 typedef struct MapClient
{
3420 QLIST_ENTRY(MapClient
) link
;
3423 QemuMutex map_client_list_lock
;
3424 static QLIST_HEAD(, MapClient
) map_client_list
3425 = QLIST_HEAD_INITIALIZER(map_client_list
);
3427 static void cpu_unregister_map_client_do(MapClient
*client
)
3429 QLIST_REMOVE(client
, link
);
3433 static void cpu_notify_map_clients_locked(void)
3437 while (!QLIST_EMPTY(&map_client_list
)) {
3438 client
= QLIST_FIRST(&map_client_list
);
3439 qemu_bh_schedule(client
->bh
);
3440 cpu_unregister_map_client_do(client
);
3444 void cpu_register_map_client(QEMUBH
*bh
)
3446 MapClient
*client
= g_malloc(sizeof(*client
));
3448 qemu_mutex_lock(&map_client_list_lock
);
3450 QLIST_INSERT_HEAD(&map_client_list
, client
, link
);
3451 if (!qatomic_read(&bounce
.in_use
)) {
3452 cpu_notify_map_clients_locked();
3454 qemu_mutex_unlock(&map_client_list_lock
);
3457 void cpu_exec_init_all(void)
3459 qemu_mutex_init(&ram_list
.mutex
);
3460 /* The data structures we set up here depend on knowing the page size,
3461 * so no more changes can be made after this point.
3462 * In an ideal world, nothing we did before we had finished the
3463 * machine setup would care about the target page size, and we could
3464 * do this much later, rather than requiring board models to state
3465 * up front what their requirements are.
3467 finalize_target_page_bits();
3470 qemu_mutex_init(&map_client_list_lock
);
3473 void cpu_unregister_map_client(QEMUBH
*bh
)
3477 qemu_mutex_lock(&map_client_list_lock
);
3478 QLIST_FOREACH(client
, &map_client_list
, link
) {
3479 if (client
->bh
== bh
) {
3480 cpu_unregister_map_client_do(client
);
3484 qemu_mutex_unlock(&map_client_list_lock
);
3487 static void cpu_notify_map_clients(void)
3489 qemu_mutex_lock(&map_client_list_lock
);
3490 cpu_notify_map_clients_locked();
3491 qemu_mutex_unlock(&map_client_list_lock
);
3494 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
3495 bool is_write
, MemTxAttrs attrs
)
3502 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3503 if (!memory_access_is_direct(mr
, is_write
)) {
3504 l
= memory_access_size(mr
, l
, addr
);
3505 if (!memory_region_access_valid(mr
, xlat
, l
, is_write
, attrs
)) {
3516 bool address_space_access_valid(AddressSpace
*as
, hwaddr addr
,
3517 hwaddr len
, bool is_write
,
3523 RCU_READ_LOCK_GUARD();
3524 fv
= address_space_to_flatview(as
);
3525 result
= flatview_access_valid(fv
, addr
, len
, is_write
, attrs
);
3530 flatview_extend_translation(FlatView
*fv
, hwaddr addr
,
3532 MemoryRegion
*mr
, hwaddr base
, hwaddr len
,
3533 bool is_write
, MemTxAttrs attrs
)
3537 MemoryRegion
*this_mr
;
3543 if (target_len
== 0) {
3548 this_mr
= flatview_translate(fv
, addr
, &xlat
,
3549 &len
, is_write
, attrs
);
3550 if (this_mr
!= mr
|| xlat
!= base
+ done
) {
3556 /* Map a physical memory region into a host virtual address.
3557 * May map a subset of the requested range, given by and returned in *plen.
3558 * May return NULL if resources needed to perform the mapping are exhausted.
3559 * Use only for reads OR writes - not for read-modify-write operations.
3560 * Use cpu_register_map_client() to know when retrying the map operation is
3561 * likely to succeed.
3563 void *address_space_map(AddressSpace
*as
,
3580 RCU_READ_LOCK_GUARD();
3581 fv
= address_space_to_flatview(as
);
3582 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3584 if (!memory_access_is_direct(mr
, is_write
)) {
3585 if (qatomic_xchg(&bounce
.in_use
, true)) {
3589 /* Avoid unbounded allocations */
3590 l
= MIN(l
, TARGET_PAGE_SIZE
);
3591 bounce
.buffer
= qemu_memalign(TARGET_PAGE_SIZE
, l
);
3595 memory_region_ref(mr
);
3598 flatview_read(fv
, addr
, MEMTXATTRS_UNSPECIFIED
,
3603 return bounce
.buffer
;
3607 memory_region_ref(mr
);
3608 *plen
= flatview_extend_translation(fv
, addr
, len
, mr
, xlat
,
3609 l
, is_write
, attrs
);
3610 ptr
= qemu_ram_ptr_length(mr
->ram_block
, xlat
, plen
, true);
3615 /* Unmaps a memory region previously mapped by address_space_map().
3616 * Will also mark the memory as dirty if is_write is true. access_len gives
3617 * the amount of memory that was actually read or written by the caller.
3619 void address_space_unmap(AddressSpace
*as
, void *buffer
, hwaddr len
,
3620 bool is_write
, hwaddr access_len
)
3622 if (buffer
!= bounce
.buffer
) {
3626 mr
= memory_region_from_host(buffer
, &addr1
);
3629 invalidate_and_set_dirty(mr
, addr1
, access_len
);
3631 if (xen_enabled()) {
3632 xen_invalidate_map_cache_entry(buffer
);
3634 memory_region_unref(mr
);
3638 address_space_write(as
, bounce
.addr
, MEMTXATTRS_UNSPECIFIED
,
3639 bounce
.buffer
, access_len
);
3641 qemu_vfree(bounce
.buffer
);
3642 bounce
.buffer
= NULL
;
3643 memory_region_unref(bounce
.mr
);
3644 qatomic_mb_set(&bounce
.in_use
, false);
3645 cpu_notify_map_clients();
3648 void *cpu_physical_memory_map(hwaddr addr
,
3652 return address_space_map(&address_space_memory
, addr
, plen
, is_write
,
3653 MEMTXATTRS_UNSPECIFIED
);
3656 void cpu_physical_memory_unmap(void *buffer
, hwaddr len
,
3657 bool is_write
, hwaddr access_len
)
3659 return address_space_unmap(&address_space_memory
, buffer
, len
, is_write
, access_len
);
3662 #define ARG1_DECL AddressSpace *as
3665 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3666 #define RCU_READ_LOCK(...) rcu_read_lock()
3667 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3668 #include "memory_ldst.c.inc"
3670 int64_t address_space_cache_init(MemoryRegionCache
*cache
,
3676 AddressSpaceDispatch
*d
;
3683 cache
->fv
= address_space_get_flatview(as
);
3684 d
= flatview_to_dispatch(cache
->fv
);
3685 cache
->mrs
= *address_space_translate_internal(d
, addr
, &cache
->xlat
, &l
, true);
3688 memory_region_ref(mr
);
3689 if (memory_access_is_direct(mr
, is_write
)) {
3690 /* We don't care about the memory attributes here as we're only
3691 * doing this if we found actual RAM, which behaves the same
3692 * regardless of attributes; so UNSPECIFIED is fine.
3694 l
= flatview_extend_translation(cache
->fv
, addr
, len
, mr
,
3695 cache
->xlat
, l
, is_write
,
3696 MEMTXATTRS_UNSPECIFIED
);
3697 cache
->ptr
= qemu_ram_ptr_length(mr
->ram_block
, cache
->xlat
, &l
, true);
3703 cache
->is_write
= is_write
;
3707 void address_space_cache_invalidate(MemoryRegionCache
*cache
,
3711 assert(cache
->is_write
);
3712 if (likely(cache
->ptr
)) {
3713 invalidate_and_set_dirty(cache
->mrs
.mr
, addr
+ cache
->xlat
, access_len
);
3717 void address_space_cache_destroy(MemoryRegionCache
*cache
)
3719 if (!cache
->mrs
.mr
) {
3723 if (xen_enabled()) {
3724 xen_invalidate_map_cache_entry(cache
->ptr
);
3726 memory_region_unref(cache
->mrs
.mr
);
3727 flatview_unref(cache
->fv
);
3728 cache
->mrs
.mr
= NULL
;
3732 /* Called from RCU critical section. This function has the same
3733 * semantics as address_space_translate, but it only works on a
3734 * predefined range of a MemoryRegion that was mapped with
3735 * address_space_cache_init.
3737 static inline MemoryRegion
*address_space_translate_cached(
3738 MemoryRegionCache
*cache
, hwaddr addr
, hwaddr
*xlat
,
3739 hwaddr
*plen
, bool is_write
, MemTxAttrs attrs
)
3741 MemoryRegionSection section
;
3743 IOMMUMemoryRegion
*iommu_mr
;
3744 AddressSpace
*target_as
;
3746 assert(!cache
->ptr
);
3747 *xlat
= addr
+ cache
->xlat
;
3750 iommu_mr
= memory_region_get_iommu(mr
);
3756 section
= address_space_translate_iommu(iommu_mr
, xlat
, plen
,
3757 NULL
, is_write
, true,
3762 /* Called from RCU critical section. address_space_read_cached uses this
3763 * out of line function when the target is an MMIO or IOMMU region.
3766 address_space_read_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3767 void *buf
, hwaddr len
)
3773 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, false,
3774 MEMTXATTRS_UNSPECIFIED
);
3775 return flatview_read_continue(cache
->fv
,
3776 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3780 /* Called from RCU critical section. address_space_write_cached uses this
3781 * out of line function when the target is an MMIO or IOMMU region.
3784 address_space_write_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3785 const void *buf
, hwaddr len
)
3791 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, true,
3792 MEMTXATTRS_UNSPECIFIED
);
3793 return flatview_write_continue(cache
->fv
,
3794 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3798 #define ARG1_DECL MemoryRegionCache *cache
3800 #define SUFFIX _cached_slow
3801 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3802 #define RCU_READ_LOCK() ((void)0)
3803 #define RCU_READ_UNLOCK() ((void)0)
3804 #include "memory_ldst.c.inc"
3806 /* virtual memory access for debug (includes writing to ROM) */
3807 int cpu_memory_rw_debug(CPUState
*cpu
, target_ulong addr
,
3808 void *ptr
, target_ulong len
, bool is_write
)
3811 target_ulong l
, page
;
3814 cpu_synchronize_state(cpu
);
3820 page
= addr
& TARGET_PAGE_MASK
;
3821 phys_addr
= cpu_get_phys_page_attrs_debug(cpu
, page
, &attrs
);
3822 asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
3823 /* if no physical page mapped, return an error */
3824 if (phys_addr
== -1)
3826 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3829 phys_addr
+= (addr
& ~TARGET_PAGE_MASK
);
3831 res
= address_space_write_rom(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3834 res
= address_space_read(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3837 if (res
!= MEMTX_OK
) {
3848 * Allows code that needs to deal with migration bitmaps etc to still be built
3849 * target independent.
3851 size_t qemu_target_page_size(void)
3853 return TARGET_PAGE_SIZE
;
3856 int qemu_target_page_bits(void)
3858 return TARGET_PAGE_BITS
;
3861 int qemu_target_page_bits_min(void)
3863 return TARGET_PAGE_BITS_MIN
;
3867 bool target_words_bigendian(void)
3869 #if defined(TARGET_WORDS_BIGENDIAN)
3876 #ifndef CONFIG_USER_ONLY
3877 bool cpu_physical_memory_is_io(hwaddr phys_addr
)
3883 RCU_READ_LOCK_GUARD();
3884 mr
= address_space_translate(&address_space_memory
,
3885 phys_addr
, &phys_addr
, &l
, false,
3886 MEMTXATTRS_UNSPECIFIED
);
3888 res
= !(memory_region_is_ram(mr
) || memory_region_is_romd(mr
));
3892 int qemu_ram_foreach_block(RAMBlockIterFunc func
, void *opaque
)
3897 RCU_READ_LOCK_GUARD();
3898 RAMBLOCK_FOREACH(block
) {
3899 ret
= func(block
, opaque
);
3908 * Unmap pages of memory from start to start+length such that
3909 * they a) read as 0, b) Trigger whatever fault mechanism
3910 * the OS provides for postcopy.
3911 * The pages must be unmapped by the end of the function.
3912 * Returns: 0 on success, none-0 on failure
3915 int ram_block_discard_range(RAMBlock
*rb
, uint64_t start
, size_t length
)
3919 uint8_t *host_startaddr
= rb
->host
+ start
;
3921 if (!QEMU_PTR_IS_ALIGNED(host_startaddr
, rb
->page_size
)) {
3922 error_report("ram_block_discard_range: Unaligned start address: %p",
3927 if ((start
+ length
) <= rb
->used_length
) {
3928 bool need_madvise
, need_fallocate
;
3929 if (!QEMU_IS_ALIGNED(length
, rb
->page_size
)) {
3930 error_report("ram_block_discard_range: Unaligned length: %zx",
3935 errno
= ENOTSUP
; /* If we are missing MADVISE etc */
3937 /* The logic here is messy;
3938 * madvise DONTNEED fails for hugepages
3939 * fallocate works on hugepages and shmem
3941 need_madvise
= (rb
->page_size
== qemu_host_page_size
);
3942 need_fallocate
= rb
->fd
!= -1;
3943 if (need_fallocate
) {
3944 /* For a file, this causes the area of the file to be zero'd
3945 * if read, and for hugetlbfs also causes it to be unmapped
3946 * so a userfault will trigger.
3948 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3949 ret
= fallocate(rb
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3953 error_report("ram_block_discard_range: Failed to fallocate "
3954 "%s:%" PRIx64
" +%zx (%d)",
3955 rb
->idstr
, start
, length
, ret
);
3960 error_report("ram_block_discard_range: fallocate not available/file"
3961 "%s:%" PRIx64
" +%zx (%d)",
3962 rb
->idstr
, start
, length
, ret
);
3967 /* For normal RAM this causes it to be unmapped,
3968 * for shared memory it causes the local mapping to disappear
3969 * and to fall back on the file contents (which we just
3970 * fallocate'd away).
3972 #if defined(CONFIG_MADVISE)
3973 ret
= madvise(host_startaddr
, length
, MADV_DONTNEED
);
3976 error_report("ram_block_discard_range: Failed to discard range "
3977 "%s:%" PRIx64
" +%zx (%d)",
3978 rb
->idstr
, start
, length
, ret
);
3983 error_report("ram_block_discard_range: MADVISE not available"
3984 "%s:%" PRIx64
" +%zx (%d)",
3985 rb
->idstr
, start
, length
, ret
);
3989 trace_ram_block_discard_range(rb
->idstr
, host_startaddr
, length
,
3990 need_madvise
, need_fallocate
, ret
);
3992 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3993 "/%zx/" RAM_ADDR_FMT
")",
3994 rb
->idstr
, start
, length
, rb
->used_length
);
4001 bool ramblock_is_pmem(RAMBlock
*rb
)
4003 return rb
->flags
& RAM_PMEM
;
4008 void page_size_init(void)
4010 /* NOTE: we can always suppose that qemu_host_page_size >=
4012 if (qemu_host_page_size
== 0) {
4013 qemu_host_page_size
= qemu_real_host_page_size
;
4015 if (qemu_host_page_size
< TARGET_PAGE_SIZE
) {
4016 qemu_host_page_size
= TARGET_PAGE_SIZE
;
4018 qemu_host_page_mask
= -(intptr_t)qemu_host_page_size
;
4021 #if !defined(CONFIG_USER_ONLY)
4023 static void mtree_print_phys_entries(int start
, int end
, int skip
, int ptr
)
4025 if (start
== end
- 1) {
4026 qemu_printf("\t%3d ", start
);
4028 qemu_printf("\t%3d..%-3d ", start
, end
- 1);
4030 qemu_printf(" skip=%d ", skip
);
4031 if (ptr
== PHYS_MAP_NODE_NIL
) {
4032 qemu_printf(" ptr=NIL");
4034 qemu_printf(" ptr=#%d", ptr
);
4036 qemu_printf(" ptr=[%d]", ptr
);
4041 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
4042 int128_sub((size), int128_one())) : 0)
4044 void mtree_print_dispatch(AddressSpaceDispatch
*d
, MemoryRegion
*root
)
4048 qemu_printf(" Dispatch\n");
4049 qemu_printf(" Physical sections\n");
4051 for (i
= 0; i
< d
->map
.sections_nb
; ++i
) {
4052 MemoryRegionSection
*s
= d
->map
.sections
+ i
;
4053 const char *names
[] = { " [unassigned]", " [not dirty]",
4054 " [ROM]", " [watch]" };
4056 qemu_printf(" #%d @" TARGET_FMT_plx
".." TARGET_FMT_plx
4059 s
->offset_within_address_space
,
4060 s
->offset_within_address_space
+ MR_SIZE(s
->mr
->size
),
4061 s
->mr
->name
? s
->mr
->name
: "(noname)",
4062 i
< ARRAY_SIZE(names
) ? names
[i
] : "",
4063 s
->mr
== root
? " [ROOT]" : "",
4064 s
== d
->mru_section
? " [MRU]" : "",
4065 s
->mr
->is_iommu
? " [iommu]" : "");
4068 qemu_printf(" alias=%s", s
->mr
->alias
->name
?
4069 s
->mr
->alias
->name
: "noname");
4074 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
4075 P_L2_BITS
, P_L2_LEVELS
, d
->phys_map
.ptr
, d
->phys_map
.skip
);
4076 for (i
= 0; i
< d
->map
.nodes_nb
; ++i
) {
4079 Node
*n
= d
->map
.nodes
+ i
;
4081 qemu_printf(" [%d]\n", i
);
4083 for (j
= 0, jprev
= 0, prev
= *n
[0]; j
< ARRAY_SIZE(*n
); ++j
) {
4084 PhysPageEntry
*pe
= *n
+ j
;
4086 if (pe
->ptr
== prev
.ptr
&& pe
->skip
== prev
.skip
) {
4090 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
4096 if (jprev
!= ARRAY_SIZE(*n
)) {
4097 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
4103 * If positive, discarding RAM is disabled. If negative, discarding RAM is
4104 * required to work and cannot be disabled.
4106 static int ram_block_discard_disabled
;
4108 int ram_block_discard_disable(bool state
)
4113 qatomic_dec(&ram_block_discard_disabled
);
4118 old
= qatomic_read(&ram_block_discard_disabled
);
4122 } while (qatomic_cmpxchg(&ram_block_discard_disabled
,
4123 old
, old
+ 1) != old
);
4127 int ram_block_discard_require(bool state
)
4132 qatomic_inc(&ram_block_discard_disabled
);
4137 old
= qatomic_read(&ram_block_discard_disabled
);
4141 } while (qatomic_cmpxchg(&ram_block_discard_disabled
,
4142 old
, old
- 1) != old
);
4146 bool ram_block_discard_is_disabled(void)
4148 return qatomic_read(&ram_block_discard_disabled
) > 0;
4151 bool ram_block_discard_is_required(void)
4153 return qatomic_read(&ram_block_discard_disabled
) < 0;