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/>.
19 #include "qemu/osdep.h"
20 #include "qapi/error.h"
22 #include "qemu/cutils.h"
24 #include "exec/exec-all.h"
25 #include "exec/target_page.h"
27 #include "hw/qdev-core.h"
28 #include "hw/qdev-properties.h"
29 #if !defined(CONFIG_USER_ONLY)
30 #include "hw/boards.h"
31 #include "hw/xen/xen.h"
33 #include "sysemu/kvm.h"
34 #include "sysemu/sysemu.h"
35 #include "qemu/timer.h"
36 #include "qemu/config-file.h"
37 #include "qemu/error-report.h"
38 #if defined(CONFIG_USER_ONLY)
40 #else /* !CONFIG_USER_ONLY */
42 #include "exec/memory.h"
43 #include "exec/ioport.h"
44 #include "sysemu/dma.h"
45 #include "sysemu/numa.h"
46 #include "sysemu/hw_accel.h"
47 #include "exec/address-spaces.h"
48 #include "sysemu/xen-mapcache.h"
49 #include "trace-root.h"
51 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
52 #include <linux/falloc.h>
56 #include "qemu/rcu_queue.h"
57 #include "qemu/main-loop.h"
58 #include "translate-all.h"
59 #include "sysemu/replay.h"
61 #include "exec/memory-internal.h"
62 #include "exec/ram_addr.h"
65 #include "migration/vmstate.h"
67 #include "qemu/range.h"
69 #include "qemu/mmap-alloc.h"
72 #include "monitor/monitor.h"
74 //#define DEBUG_SUBPAGE
76 #if !defined(CONFIG_USER_ONLY)
77 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
78 * are protected by the ramlist lock.
80 RAMList ram_list
= { .blocks
= QLIST_HEAD_INITIALIZER(ram_list
.blocks
) };
82 static MemoryRegion
*system_memory
;
83 static MemoryRegion
*system_io
;
85 AddressSpace address_space_io
;
86 AddressSpace address_space_memory
;
88 MemoryRegion io_mem_rom
, io_mem_notdirty
;
89 static MemoryRegion io_mem_unassigned
;
91 /* RAM is pre-allocated and passed into qemu_ram_alloc_from_ptr */
92 #define RAM_PREALLOC (1 << 0)
94 /* RAM is mmap-ed with MAP_SHARED */
95 #define RAM_SHARED (1 << 1)
97 /* Only a portion of RAM (used_length) is actually used, and migrated.
98 * This used_length size can change across reboots.
100 #define RAM_RESIZEABLE (1 << 2)
102 /* UFFDIO_ZEROPAGE is available on this RAMBlock to atomically
103 * zero the page and wake waiting processes.
104 * (Set during postcopy)
106 #define RAM_UF_ZEROPAGE (1 << 3)
109 #ifdef TARGET_PAGE_BITS_VARY
110 int target_page_bits
;
111 bool target_page_bits_decided
;
114 struct CPUTailQ cpus
= QTAILQ_HEAD_INITIALIZER(cpus
);
115 /* current CPU in the current thread. It is only valid inside
117 __thread CPUState
*current_cpu
;
118 /* 0 = Do not count executed instructions.
119 1 = Precise instruction counting.
120 2 = Adaptive rate instruction counting. */
123 uintptr_t qemu_host_page_size
;
124 intptr_t qemu_host_page_mask
;
126 bool set_preferred_target_page_bits(int bits
)
128 /* The target page size is the lowest common denominator for all
129 * the CPUs in the system, so we can only make it smaller, never
130 * larger. And we can't make it smaller once we've committed to
133 #ifdef TARGET_PAGE_BITS_VARY
134 assert(bits
>= TARGET_PAGE_BITS_MIN
);
135 if (target_page_bits
== 0 || target_page_bits
> bits
) {
136 if (target_page_bits_decided
) {
139 target_page_bits
= bits
;
145 #if !defined(CONFIG_USER_ONLY)
147 static void finalize_target_page_bits(void)
149 #ifdef TARGET_PAGE_BITS_VARY
150 if (target_page_bits
== 0) {
151 target_page_bits
= TARGET_PAGE_BITS_MIN
;
153 target_page_bits_decided
= true;
157 typedef struct PhysPageEntry PhysPageEntry
;
159 struct PhysPageEntry
{
160 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
162 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
166 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
168 /* Size of the L2 (and L3, etc) page tables. */
169 #define ADDR_SPACE_BITS 64
172 #define P_L2_SIZE (1 << P_L2_BITS)
174 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
176 typedef PhysPageEntry Node
[P_L2_SIZE
];
178 typedef struct PhysPageMap
{
181 unsigned sections_nb
;
182 unsigned sections_nb_alloc
;
184 unsigned nodes_nb_alloc
;
186 MemoryRegionSection
*sections
;
189 struct AddressSpaceDispatch
{
190 MemoryRegionSection
*mru_section
;
191 /* This is a multi-level map on the physical address space.
192 * The bottom level has pointers to MemoryRegionSections.
194 PhysPageEntry phys_map
;
198 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
199 typedef struct subpage_t
{
203 uint16_t sub_section
[];
206 #define PHYS_SECTION_UNASSIGNED 0
207 #define PHYS_SECTION_NOTDIRTY 1
208 #define PHYS_SECTION_ROM 2
209 #define PHYS_SECTION_WATCH 3
211 static void io_mem_init(void);
212 static void memory_map_init(void);
213 static void tcg_commit(MemoryListener
*listener
);
215 static MemoryRegion io_mem_watch
;
218 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
219 * @cpu: the CPU whose AddressSpace this is
220 * @as: the AddressSpace itself
221 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
222 * @tcg_as_listener: listener for tracking changes to the AddressSpace
224 struct CPUAddressSpace
{
227 struct AddressSpaceDispatch
*memory_dispatch
;
228 MemoryListener tcg_as_listener
;
231 struct DirtyBitmapSnapshot
{
234 unsigned long dirty
[];
239 #if !defined(CONFIG_USER_ONLY)
241 static void phys_map_node_reserve(PhysPageMap
*map
, unsigned nodes
)
243 static unsigned alloc_hint
= 16;
244 if (map
->nodes_nb
+ nodes
> map
->nodes_nb_alloc
) {
245 map
->nodes_nb_alloc
= MAX(map
->nodes_nb_alloc
, alloc_hint
);
246 map
->nodes_nb_alloc
= MAX(map
->nodes_nb_alloc
, map
->nodes_nb
+ nodes
);
247 map
->nodes
= g_renew(Node
, map
->nodes
, map
->nodes_nb_alloc
);
248 alloc_hint
= map
->nodes_nb_alloc
;
252 static uint32_t phys_map_node_alloc(PhysPageMap
*map
, bool leaf
)
259 ret
= map
->nodes_nb
++;
261 assert(ret
!= PHYS_MAP_NODE_NIL
);
262 assert(ret
!= map
->nodes_nb_alloc
);
264 e
.skip
= leaf
? 0 : 1;
265 e
.ptr
= leaf
? PHYS_SECTION_UNASSIGNED
: PHYS_MAP_NODE_NIL
;
266 for (i
= 0; i
< P_L2_SIZE
; ++i
) {
267 memcpy(&p
[i
], &e
, sizeof(e
));
272 static void phys_page_set_level(PhysPageMap
*map
, PhysPageEntry
*lp
,
273 hwaddr
*index
, hwaddr
*nb
, uint16_t leaf
,
277 hwaddr step
= (hwaddr
)1 << (level
* P_L2_BITS
);
279 if (lp
->skip
&& lp
->ptr
== PHYS_MAP_NODE_NIL
) {
280 lp
->ptr
= phys_map_node_alloc(map
, level
== 0);
282 p
= map
->nodes
[lp
->ptr
];
283 lp
= &p
[(*index
>> (level
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
285 while (*nb
&& lp
< &p
[P_L2_SIZE
]) {
286 if ((*index
& (step
- 1)) == 0 && *nb
>= step
) {
292 phys_page_set_level(map
, lp
, index
, nb
, leaf
, level
- 1);
298 static void phys_page_set(AddressSpaceDispatch
*d
,
299 hwaddr index
, hwaddr nb
,
302 /* Wildly overreserve - it doesn't matter much. */
303 phys_map_node_reserve(&d
->map
, 3 * P_L2_LEVELS
);
305 phys_page_set_level(&d
->map
, &d
->phys_map
, &index
, &nb
, leaf
, P_L2_LEVELS
- 1);
308 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
309 * and update our entry so we can skip it and go directly to the destination.
311 static void phys_page_compact(PhysPageEntry
*lp
, Node
*nodes
)
313 unsigned valid_ptr
= P_L2_SIZE
;
318 if (lp
->ptr
== PHYS_MAP_NODE_NIL
) {
323 for (i
= 0; i
< P_L2_SIZE
; i
++) {
324 if (p
[i
].ptr
== PHYS_MAP_NODE_NIL
) {
331 phys_page_compact(&p
[i
], nodes
);
335 /* We can only compress if there's only one child. */
340 assert(valid_ptr
< P_L2_SIZE
);
342 /* Don't compress if it won't fit in the # of bits we have. */
343 if (lp
->skip
+ p
[valid_ptr
].skip
>= (1 << 3)) {
347 lp
->ptr
= p
[valid_ptr
].ptr
;
348 if (!p
[valid_ptr
].skip
) {
349 /* If our only child is a leaf, make this a leaf. */
350 /* By design, we should have made this node a leaf to begin with so we
351 * should never reach here.
352 * But since it's so simple to handle this, let's do it just in case we
357 lp
->skip
+= p
[valid_ptr
].skip
;
361 void address_space_dispatch_compact(AddressSpaceDispatch
*d
)
363 if (d
->phys_map
.skip
) {
364 phys_page_compact(&d
->phys_map
, d
->map
.nodes
);
368 static inline bool section_covers_addr(const MemoryRegionSection
*section
,
371 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
372 * the section must cover the entire address space.
374 return int128_gethi(section
->size
) ||
375 range_covers_byte(section
->offset_within_address_space
,
376 int128_getlo(section
->size
), addr
);
379 static MemoryRegionSection
*phys_page_find(AddressSpaceDispatch
*d
, hwaddr addr
)
381 PhysPageEntry lp
= d
->phys_map
, *p
;
382 Node
*nodes
= d
->map
.nodes
;
383 MemoryRegionSection
*sections
= d
->map
.sections
;
384 hwaddr index
= addr
>> TARGET_PAGE_BITS
;
387 for (i
= P_L2_LEVELS
; lp
.skip
&& (i
-= lp
.skip
) >= 0;) {
388 if (lp
.ptr
== PHYS_MAP_NODE_NIL
) {
389 return §ions
[PHYS_SECTION_UNASSIGNED
];
392 lp
= p
[(index
>> (i
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
395 if (section_covers_addr(§ions
[lp
.ptr
], addr
)) {
396 return §ions
[lp
.ptr
];
398 return §ions
[PHYS_SECTION_UNASSIGNED
];
402 bool memory_region_is_unassigned(MemoryRegion
*mr
)
404 return mr
!= &io_mem_rom
&& mr
!= &io_mem_notdirty
&& !mr
->rom_device
405 && mr
!= &io_mem_watch
;
408 /* Called from RCU critical section */
409 static MemoryRegionSection
*address_space_lookup_region(AddressSpaceDispatch
*d
,
411 bool resolve_subpage
)
413 MemoryRegionSection
*section
= atomic_read(&d
->mru_section
);
416 if (!section
|| section
== &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
] ||
417 !section_covers_addr(section
, addr
)) {
418 section
= phys_page_find(d
, addr
);
419 atomic_set(&d
->mru_section
, section
);
421 if (resolve_subpage
&& section
->mr
->subpage
) {
422 subpage
= container_of(section
->mr
, subpage_t
, iomem
);
423 section
= &d
->map
.sections
[subpage
->sub_section
[SUBPAGE_IDX(addr
)]];
428 /* Called from RCU critical section */
429 static MemoryRegionSection
*
430 address_space_translate_internal(AddressSpaceDispatch
*d
, hwaddr addr
, hwaddr
*xlat
,
431 hwaddr
*plen
, bool resolve_subpage
)
433 MemoryRegionSection
*section
;
437 section
= address_space_lookup_region(d
, addr
, resolve_subpage
);
438 /* Compute offset within MemoryRegionSection */
439 addr
-= section
->offset_within_address_space
;
441 /* Compute offset within MemoryRegion */
442 *xlat
= addr
+ section
->offset_within_region
;
446 /* MMIO registers can be expected to perform full-width accesses based only
447 * on their address, without considering adjacent registers that could
448 * decode to completely different MemoryRegions. When such registers
449 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
450 * regions overlap wildly. For this reason we cannot clamp the accesses
453 * If the length is small (as is the case for address_space_ldl/stl),
454 * everything works fine. If the incoming length is large, however,
455 * the caller really has to do the clamping through memory_access_size.
457 if (memory_region_is_ram(mr
)) {
458 diff
= int128_sub(section
->size
, int128_make64(addr
));
459 *plen
= int128_get64(int128_min(diff
, int128_make64(*plen
)));
465 * flatview_do_translate - translate an address in FlatView
467 * @fv: the flat view that we want to translate on
468 * @addr: the address to be translated in above address space
469 * @xlat: the translated address offset within memory region. It
471 * @plen_out: valid read/write length of the translated address. It
472 * can be @NULL when we don't care about it.
473 * @page_mask_out: page mask for the translated address. This
474 * should only be meaningful for IOMMU translated
475 * addresses, since there may be huge pages that this bit
476 * would tell. It can be @NULL if we don't care about it.
477 * @is_write: whether the translation operation is for write
478 * @is_mmio: whether this can be MMIO, set true if it can
480 * This function is called from RCU critical section
482 static MemoryRegionSection
flatview_do_translate(FlatView
*fv
,
486 hwaddr
*page_mask_out
,
489 AddressSpace
**target_as
)
492 MemoryRegionSection
*section
;
493 IOMMUMemoryRegion
*iommu_mr
;
494 IOMMUMemoryRegionClass
*imrc
;
495 hwaddr page_mask
= (hwaddr
)(-1);
496 hwaddr plen
= (hwaddr
)(-1);
503 section
= address_space_translate_internal(
504 flatview_to_dispatch(fv
), addr
, &addr
,
507 iommu_mr
= memory_region_get_iommu(section
->mr
);
511 imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
513 iotlb
= imrc
->translate(iommu_mr
, addr
, is_write
?
514 IOMMU_WO
: IOMMU_RO
);
515 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
516 | (addr
& iotlb
.addr_mask
));
517 page_mask
&= iotlb
.addr_mask
;
518 plen
= MIN(plen
, (addr
| iotlb
.addr_mask
) - addr
+ 1);
519 if (!(iotlb
.perm
& (1 << is_write
))) {
523 fv
= address_space_to_flatview(iotlb
.target_as
);
524 *target_as
= iotlb
.target_as
;
529 if (page_mask
== (hwaddr
)(-1)) {
530 /* Not behind an IOMMU, use default page size. */
531 page_mask
= ~TARGET_PAGE_MASK
;
535 *page_mask_out
= page_mask
;
545 return (MemoryRegionSection
) { .mr
= &io_mem_unassigned
};
548 /* Called from RCU critical section */
549 IOMMUTLBEntry
address_space_get_iotlb_entry(AddressSpace
*as
, hwaddr addr
,
552 MemoryRegionSection section
;
553 hwaddr xlat
, page_mask
;
556 * This can never be MMIO, and we don't really care about plen,
559 section
= flatview_do_translate(address_space_to_flatview(as
), addr
, &xlat
,
560 NULL
, &page_mask
, is_write
, false, &as
);
562 /* Illegal translation */
563 if (section
.mr
== &io_mem_unassigned
) {
567 /* Convert memory region offset into address space offset */
568 xlat
+= section
.offset_within_address_space
-
569 section
.offset_within_region
;
571 return (IOMMUTLBEntry
) {
573 .iova
= addr
& ~page_mask
,
574 .translated_addr
= xlat
& ~page_mask
,
575 .addr_mask
= page_mask
,
576 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
581 return (IOMMUTLBEntry
) {0};
584 /* Called from RCU critical section */
585 MemoryRegion
*flatview_translate(FlatView
*fv
, hwaddr addr
, hwaddr
*xlat
,
586 hwaddr
*plen
, bool is_write
)
589 MemoryRegionSection section
;
590 AddressSpace
*as
= NULL
;
592 /* This can be MMIO, so setup MMIO bit. */
593 section
= flatview_do_translate(fv
, addr
, xlat
, plen
, NULL
,
594 is_write
, true, &as
);
597 if (xen_enabled() && memory_access_is_direct(mr
, is_write
)) {
598 hwaddr page
= ((addr
& TARGET_PAGE_MASK
) + TARGET_PAGE_SIZE
) - addr
;
599 *plen
= MIN(page
, *plen
);
605 /* Called from RCU critical section */
606 MemoryRegionSection
*
607 address_space_translate_for_iotlb(CPUState
*cpu
, int asidx
, hwaddr addr
,
608 hwaddr
*xlat
, hwaddr
*plen
)
610 MemoryRegionSection
*section
;
611 AddressSpaceDispatch
*d
= atomic_rcu_read(&cpu
->cpu_ases
[asidx
].memory_dispatch
);
613 section
= address_space_translate_internal(d
, addr
, xlat
, plen
, false);
615 assert(!memory_region_is_iommu(section
->mr
));
620 #if !defined(CONFIG_USER_ONLY)
622 static int cpu_common_post_load(void *opaque
, int version_id
)
624 CPUState
*cpu
= opaque
;
626 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
627 version_id is increased. */
628 cpu
->interrupt_request
&= ~0x01;
631 /* loadvm has just updated the content of RAM, bypassing the
632 * usual mechanisms that ensure we flush TBs for writes to
633 * memory we've translated code from. So we must flush all TBs,
634 * which will now be stale.
641 static int cpu_common_pre_load(void *opaque
)
643 CPUState
*cpu
= opaque
;
645 cpu
->exception_index
= -1;
650 static bool cpu_common_exception_index_needed(void *opaque
)
652 CPUState
*cpu
= opaque
;
654 return tcg_enabled() && cpu
->exception_index
!= -1;
657 static const VMStateDescription vmstate_cpu_common_exception_index
= {
658 .name
= "cpu_common/exception_index",
660 .minimum_version_id
= 1,
661 .needed
= cpu_common_exception_index_needed
,
662 .fields
= (VMStateField
[]) {
663 VMSTATE_INT32(exception_index
, CPUState
),
664 VMSTATE_END_OF_LIST()
668 static bool cpu_common_crash_occurred_needed(void *opaque
)
670 CPUState
*cpu
= opaque
;
672 return cpu
->crash_occurred
;
675 static const VMStateDescription vmstate_cpu_common_crash_occurred
= {
676 .name
= "cpu_common/crash_occurred",
678 .minimum_version_id
= 1,
679 .needed
= cpu_common_crash_occurred_needed
,
680 .fields
= (VMStateField
[]) {
681 VMSTATE_BOOL(crash_occurred
, CPUState
),
682 VMSTATE_END_OF_LIST()
686 const VMStateDescription vmstate_cpu_common
= {
687 .name
= "cpu_common",
689 .minimum_version_id
= 1,
690 .pre_load
= cpu_common_pre_load
,
691 .post_load
= cpu_common_post_load
,
692 .fields
= (VMStateField
[]) {
693 VMSTATE_UINT32(halted
, CPUState
),
694 VMSTATE_UINT32(interrupt_request
, CPUState
),
695 VMSTATE_END_OF_LIST()
697 .subsections
= (const VMStateDescription
*[]) {
698 &vmstate_cpu_common_exception_index
,
699 &vmstate_cpu_common_crash_occurred
,
706 CPUState
*qemu_get_cpu(int index
)
711 if (cpu
->cpu_index
== index
) {
719 #if !defined(CONFIG_USER_ONLY)
720 void cpu_address_space_init(CPUState
*cpu
, int asidx
,
721 const char *prefix
, MemoryRegion
*mr
)
723 CPUAddressSpace
*newas
;
724 AddressSpace
*as
= g_new0(AddressSpace
, 1);
728 as_name
= g_strdup_printf("%s-%d", prefix
, cpu
->cpu_index
);
729 address_space_init(as
, mr
, as_name
);
732 /* Target code should have set num_ases before calling us */
733 assert(asidx
< cpu
->num_ases
);
736 /* address space 0 gets the convenience alias */
740 /* KVM cannot currently support multiple address spaces. */
741 assert(asidx
== 0 || !kvm_enabled());
743 if (!cpu
->cpu_ases
) {
744 cpu
->cpu_ases
= g_new0(CPUAddressSpace
, cpu
->num_ases
);
747 newas
= &cpu
->cpu_ases
[asidx
];
751 newas
->tcg_as_listener
.commit
= tcg_commit
;
752 memory_listener_register(&newas
->tcg_as_listener
, as
);
756 AddressSpace
*cpu_get_address_space(CPUState
*cpu
, int asidx
)
758 /* Return the AddressSpace corresponding to the specified index */
759 return cpu
->cpu_ases
[asidx
].as
;
763 void cpu_exec_unrealizefn(CPUState
*cpu
)
765 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
767 cpu_list_remove(cpu
);
769 if (cc
->vmsd
!= NULL
) {
770 vmstate_unregister(NULL
, cc
->vmsd
, cpu
);
772 if (qdev_get_vmsd(DEVICE(cpu
)) == NULL
) {
773 vmstate_unregister(NULL
, &vmstate_cpu_common
, cpu
);
777 Property cpu_common_props
[] = {
778 #ifndef CONFIG_USER_ONLY
779 /* Create a memory property for softmmu CPU object,
780 * so users can wire up its memory. (This can't go in qom/cpu.c
781 * because that file is compiled only once for both user-mode
782 * and system builds.) The default if no link is set up is to use
783 * the system address space.
785 DEFINE_PROP_LINK("memory", CPUState
, memory
, TYPE_MEMORY_REGION
,
788 DEFINE_PROP_END_OF_LIST(),
791 void cpu_exec_initfn(CPUState
*cpu
)
796 #ifndef CONFIG_USER_ONLY
797 cpu
->thread_id
= qemu_get_thread_id();
798 cpu
->memory
= system_memory
;
799 object_ref(OBJECT(cpu
->memory
));
803 void cpu_exec_realizefn(CPUState
*cpu
, Error
**errp
)
805 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
806 static bool tcg_target_initialized
;
810 if (tcg_enabled() && !tcg_target_initialized
) {
811 tcg_target_initialized
= true;
812 cc
->tcg_initialize();
815 #ifndef CONFIG_USER_ONLY
816 if (qdev_get_vmsd(DEVICE(cpu
)) == NULL
) {
817 vmstate_register(NULL
, cpu
->cpu_index
, &vmstate_cpu_common
, cpu
);
819 if (cc
->vmsd
!= NULL
) {
820 vmstate_register(NULL
, cpu
->cpu_index
, cc
->vmsd
, cpu
);
825 #if defined(CONFIG_USER_ONLY)
826 static void breakpoint_invalidate(CPUState
*cpu
, target_ulong pc
)
830 tb_invalidate_phys_page_range(pc
, pc
+ 1, 0);
835 static void breakpoint_invalidate(CPUState
*cpu
, target_ulong pc
)
838 hwaddr phys
= cpu_get_phys_page_attrs_debug(cpu
, pc
, &attrs
);
839 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
841 /* Locks grabbed by tb_invalidate_phys_addr */
842 tb_invalidate_phys_addr(cpu
->cpu_ases
[asidx
].as
,
843 phys
| (pc
& ~TARGET_PAGE_MASK
));
848 #if defined(CONFIG_USER_ONLY)
849 void cpu_watchpoint_remove_all(CPUState
*cpu
, int mask
)
854 int cpu_watchpoint_remove(CPUState
*cpu
, vaddr addr
, vaddr len
,
860 void cpu_watchpoint_remove_by_ref(CPUState
*cpu
, CPUWatchpoint
*watchpoint
)
864 int cpu_watchpoint_insert(CPUState
*cpu
, vaddr addr
, vaddr len
,
865 int flags
, CPUWatchpoint
**watchpoint
)
870 /* Add a watchpoint. */
871 int cpu_watchpoint_insert(CPUState
*cpu
, vaddr addr
, vaddr len
,
872 int flags
, CPUWatchpoint
**watchpoint
)
876 /* forbid ranges which are empty or run off the end of the address space */
877 if (len
== 0 || (addr
+ len
- 1) < addr
) {
878 error_report("tried to set invalid watchpoint at %"
879 VADDR_PRIx
", len=%" VADDR_PRIu
, addr
, len
);
882 wp
= g_malloc(sizeof(*wp
));
888 /* keep all GDB-injected watchpoints in front */
889 if (flags
& BP_GDB
) {
890 QTAILQ_INSERT_HEAD(&cpu
->watchpoints
, wp
, entry
);
892 QTAILQ_INSERT_TAIL(&cpu
->watchpoints
, wp
, entry
);
895 tlb_flush_page(cpu
, addr
);
902 /* Remove a specific watchpoint. */
903 int cpu_watchpoint_remove(CPUState
*cpu
, vaddr addr
, vaddr len
,
908 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
909 if (addr
== wp
->vaddr
&& len
== wp
->len
910 && flags
== (wp
->flags
& ~BP_WATCHPOINT_HIT
)) {
911 cpu_watchpoint_remove_by_ref(cpu
, wp
);
918 /* Remove a specific watchpoint by reference. */
919 void cpu_watchpoint_remove_by_ref(CPUState
*cpu
, CPUWatchpoint
*watchpoint
)
921 QTAILQ_REMOVE(&cpu
->watchpoints
, watchpoint
, entry
);
923 tlb_flush_page(cpu
, watchpoint
->vaddr
);
928 /* Remove all matching watchpoints. */
929 void cpu_watchpoint_remove_all(CPUState
*cpu
, int mask
)
931 CPUWatchpoint
*wp
, *next
;
933 QTAILQ_FOREACH_SAFE(wp
, &cpu
->watchpoints
, entry
, next
) {
934 if (wp
->flags
& mask
) {
935 cpu_watchpoint_remove_by_ref(cpu
, wp
);
940 /* Return true if this watchpoint address matches the specified
941 * access (ie the address range covered by the watchpoint overlaps
942 * partially or completely with the address range covered by the
945 static inline bool cpu_watchpoint_address_matches(CPUWatchpoint
*wp
,
949 /* We know the lengths are non-zero, but a little caution is
950 * required to avoid errors in the case where the range ends
951 * exactly at the top of the address space and so addr + len
952 * wraps round to zero.
954 vaddr wpend
= wp
->vaddr
+ wp
->len
- 1;
955 vaddr addrend
= addr
+ len
- 1;
957 return !(addr
> wpend
|| wp
->vaddr
> addrend
);
962 /* Add a breakpoint. */
963 int cpu_breakpoint_insert(CPUState
*cpu
, vaddr pc
, int flags
,
964 CPUBreakpoint
**breakpoint
)
968 bp
= g_malloc(sizeof(*bp
));
973 /* keep all GDB-injected breakpoints in front */
974 if (flags
& BP_GDB
) {
975 QTAILQ_INSERT_HEAD(&cpu
->breakpoints
, bp
, entry
);
977 QTAILQ_INSERT_TAIL(&cpu
->breakpoints
, bp
, entry
);
980 breakpoint_invalidate(cpu
, pc
);
988 /* Remove a specific breakpoint. */
989 int cpu_breakpoint_remove(CPUState
*cpu
, vaddr pc
, int flags
)
993 QTAILQ_FOREACH(bp
, &cpu
->breakpoints
, entry
) {
994 if (bp
->pc
== pc
&& bp
->flags
== flags
) {
995 cpu_breakpoint_remove_by_ref(cpu
, bp
);
1002 /* Remove a specific breakpoint by reference. */
1003 void cpu_breakpoint_remove_by_ref(CPUState
*cpu
, CPUBreakpoint
*breakpoint
)
1005 QTAILQ_REMOVE(&cpu
->breakpoints
, breakpoint
, entry
);
1007 breakpoint_invalidate(cpu
, breakpoint
->pc
);
1012 /* Remove all matching breakpoints. */
1013 void cpu_breakpoint_remove_all(CPUState
*cpu
, int mask
)
1015 CPUBreakpoint
*bp
, *next
;
1017 QTAILQ_FOREACH_SAFE(bp
, &cpu
->breakpoints
, entry
, next
) {
1018 if (bp
->flags
& mask
) {
1019 cpu_breakpoint_remove_by_ref(cpu
, bp
);
1024 /* enable or disable single step mode. EXCP_DEBUG is returned by the
1025 CPU loop after each instruction */
1026 void cpu_single_step(CPUState
*cpu
, int enabled
)
1028 if (cpu
->singlestep_enabled
!= enabled
) {
1029 cpu
->singlestep_enabled
= enabled
;
1030 if (kvm_enabled()) {
1031 kvm_update_guest_debug(cpu
, 0);
1033 /* must flush all the translated code to avoid inconsistencies */
1034 /* XXX: only flush what is necessary */
1040 void cpu_abort(CPUState
*cpu
, const char *fmt
, ...)
1047 fprintf(stderr
, "qemu: fatal: ");
1048 vfprintf(stderr
, fmt
, ap
);
1049 fprintf(stderr
, "\n");
1050 cpu_dump_state(cpu
, stderr
, fprintf
, CPU_DUMP_FPU
| CPU_DUMP_CCOP
);
1051 if (qemu_log_separate()) {
1053 qemu_log("qemu: fatal: ");
1054 qemu_log_vprintf(fmt
, ap2
);
1056 log_cpu_state(cpu
, CPU_DUMP_FPU
| CPU_DUMP_CCOP
);
1064 #if defined(CONFIG_USER_ONLY)
1066 struct sigaction act
;
1067 sigfillset(&act
.sa_mask
);
1068 act
.sa_handler
= SIG_DFL
;
1069 sigaction(SIGABRT
, &act
, NULL
);
1075 #if !defined(CONFIG_USER_ONLY)
1076 /* Called from RCU critical section */
1077 static RAMBlock
*qemu_get_ram_block(ram_addr_t addr
)
1081 block
= atomic_rcu_read(&ram_list
.mru_block
);
1082 if (block
&& addr
- block
->offset
< block
->max_length
) {
1085 RAMBLOCK_FOREACH(block
) {
1086 if (addr
- block
->offset
< block
->max_length
) {
1091 fprintf(stderr
, "Bad ram offset %" PRIx64
"\n", (uint64_t)addr
);
1095 /* It is safe to write mru_block outside the iothread lock. This
1100 * xxx removed from list
1104 * call_rcu(reclaim_ramblock, xxx);
1107 * atomic_rcu_set is not needed here. The block was already published
1108 * when it was placed into the list. Here we're just making an extra
1109 * copy of the pointer.
1111 ram_list
.mru_block
= block
;
1115 static void tlb_reset_dirty_range_all(ram_addr_t start
, ram_addr_t length
)
1122 end
= TARGET_PAGE_ALIGN(start
+ length
);
1123 start
&= TARGET_PAGE_MASK
;
1126 block
= qemu_get_ram_block(start
);
1127 assert(block
== qemu_get_ram_block(end
- 1));
1128 start1
= (uintptr_t)ramblock_ptr(block
, start
- block
->offset
);
1130 tlb_reset_dirty(cpu
, start1
, length
);
1135 /* Note: start and end must be within the same ram block. */
1136 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start
,
1140 DirtyMemoryBlocks
*blocks
;
1141 unsigned long end
, page
;
1148 end
= TARGET_PAGE_ALIGN(start
+ length
) >> TARGET_PAGE_BITS
;
1149 page
= start
>> TARGET_PAGE_BITS
;
1153 blocks
= atomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1155 while (page
< end
) {
1156 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1157 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1158 unsigned long num
= MIN(end
- page
, DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1160 dirty
|= bitmap_test_and_clear_atomic(blocks
->blocks
[idx
],
1167 if (dirty
&& tcg_enabled()) {
1168 tlb_reset_dirty_range_all(start
, length
);
1174 DirtyBitmapSnapshot
*cpu_physical_memory_snapshot_and_clear_dirty
1175 (ram_addr_t start
, ram_addr_t length
, unsigned client
)
1177 DirtyMemoryBlocks
*blocks
;
1178 unsigned long align
= 1UL << (TARGET_PAGE_BITS
+ BITS_PER_LEVEL
);
1179 ram_addr_t first
= QEMU_ALIGN_DOWN(start
, align
);
1180 ram_addr_t last
= QEMU_ALIGN_UP(start
+ length
, align
);
1181 DirtyBitmapSnapshot
*snap
;
1182 unsigned long page
, end
, dest
;
1184 snap
= g_malloc0(sizeof(*snap
) +
1185 ((last
- first
) >> (TARGET_PAGE_BITS
+ 3)));
1186 snap
->start
= first
;
1189 page
= first
>> TARGET_PAGE_BITS
;
1190 end
= last
>> TARGET_PAGE_BITS
;
1195 blocks
= atomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1197 while (page
< end
) {
1198 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1199 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1200 unsigned long num
= MIN(end
- page
, DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1202 assert(QEMU_IS_ALIGNED(offset
, (1 << BITS_PER_LEVEL
)));
1203 assert(QEMU_IS_ALIGNED(num
, (1 << BITS_PER_LEVEL
)));
1204 offset
>>= BITS_PER_LEVEL
;
1206 bitmap_copy_and_clear_atomic(snap
->dirty
+ dest
,
1207 blocks
->blocks
[idx
] + offset
,
1210 dest
+= num
>> BITS_PER_LEVEL
;
1215 if (tcg_enabled()) {
1216 tlb_reset_dirty_range_all(start
, length
);
1222 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot
*snap
,
1226 unsigned long page
, end
;
1228 assert(start
>= snap
->start
);
1229 assert(start
+ length
<= snap
->end
);
1231 end
= TARGET_PAGE_ALIGN(start
+ length
- snap
->start
) >> TARGET_PAGE_BITS
;
1232 page
= (start
- snap
->start
) >> TARGET_PAGE_BITS
;
1234 while (page
< end
) {
1235 if (test_bit(page
, snap
->dirty
)) {
1243 /* Called from RCU critical section */
1244 hwaddr
memory_region_section_get_iotlb(CPUState
*cpu
,
1245 MemoryRegionSection
*section
,
1247 hwaddr paddr
, hwaddr xlat
,
1249 target_ulong
*address
)
1254 if (memory_region_is_ram(section
->mr
)) {
1256 iotlb
= memory_region_get_ram_addr(section
->mr
) + xlat
;
1257 if (!section
->readonly
) {
1258 iotlb
|= PHYS_SECTION_NOTDIRTY
;
1260 iotlb
|= PHYS_SECTION_ROM
;
1263 AddressSpaceDispatch
*d
;
1265 d
= flatview_to_dispatch(section
->fv
);
1266 iotlb
= section
- d
->map
.sections
;
1270 /* Make accesses to pages with watchpoints go via the
1271 watchpoint trap routines. */
1272 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
1273 if (cpu_watchpoint_address_matches(wp
, vaddr
, TARGET_PAGE_SIZE
)) {
1274 /* Avoid trapping reads of pages with a write breakpoint. */
1275 if ((prot
& PAGE_WRITE
) || (wp
->flags
& BP_MEM_READ
)) {
1276 iotlb
= PHYS_SECTION_WATCH
+ paddr
;
1277 *address
|= TLB_MMIO
;
1285 #endif /* defined(CONFIG_USER_ONLY) */
1287 #if !defined(CONFIG_USER_ONLY)
1289 static int subpage_register (subpage_t
*mmio
, uint32_t start
, uint32_t end
,
1291 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
);
1293 static void *(*phys_mem_alloc
)(size_t size
, uint64_t *align
, bool shared
) =
1294 qemu_anon_ram_alloc
;
1297 * Set a custom physical guest memory alloator.
1298 * Accelerators with unusual needs may need this. Hopefully, we can
1299 * get rid of it eventually.
1301 void phys_mem_set_alloc(void *(*alloc
)(size_t, uint64_t *align
, bool shared
))
1303 phys_mem_alloc
= alloc
;
1306 static uint16_t phys_section_add(PhysPageMap
*map
,
1307 MemoryRegionSection
*section
)
1309 /* The physical section number is ORed with a page-aligned
1310 * pointer to produce the iotlb entries. Thus it should
1311 * never overflow into the page-aligned value.
1313 assert(map
->sections_nb
< TARGET_PAGE_SIZE
);
1315 if (map
->sections_nb
== map
->sections_nb_alloc
) {
1316 map
->sections_nb_alloc
= MAX(map
->sections_nb_alloc
* 2, 16);
1317 map
->sections
= g_renew(MemoryRegionSection
, map
->sections
,
1318 map
->sections_nb_alloc
);
1320 map
->sections
[map
->sections_nb
] = *section
;
1321 memory_region_ref(section
->mr
);
1322 return map
->sections_nb
++;
1325 static void phys_section_destroy(MemoryRegion
*mr
)
1327 bool have_sub_page
= mr
->subpage
;
1329 memory_region_unref(mr
);
1331 if (have_sub_page
) {
1332 subpage_t
*subpage
= container_of(mr
, subpage_t
, iomem
);
1333 object_unref(OBJECT(&subpage
->iomem
));
1338 static void phys_sections_free(PhysPageMap
*map
)
1340 while (map
->sections_nb
> 0) {
1341 MemoryRegionSection
*section
= &map
->sections
[--map
->sections_nb
];
1342 phys_section_destroy(section
->mr
);
1344 g_free(map
->sections
);
1348 static void register_subpage(FlatView
*fv
, MemoryRegionSection
*section
)
1350 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1352 hwaddr base
= section
->offset_within_address_space
1354 MemoryRegionSection
*existing
= phys_page_find(d
, base
);
1355 MemoryRegionSection subsection
= {
1356 .offset_within_address_space
= base
,
1357 .size
= int128_make64(TARGET_PAGE_SIZE
),
1361 assert(existing
->mr
->subpage
|| existing
->mr
== &io_mem_unassigned
);
1363 if (!(existing
->mr
->subpage
)) {
1364 subpage
= subpage_init(fv
, base
);
1366 subsection
.mr
= &subpage
->iomem
;
1367 phys_page_set(d
, base
>> TARGET_PAGE_BITS
, 1,
1368 phys_section_add(&d
->map
, &subsection
));
1370 subpage
= container_of(existing
->mr
, subpage_t
, iomem
);
1372 start
= section
->offset_within_address_space
& ~TARGET_PAGE_MASK
;
1373 end
= start
+ int128_get64(section
->size
) - 1;
1374 subpage_register(subpage
, start
, end
,
1375 phys_section_add(&d
->map
, section
));
1379 static void register_multipage(FlatView
*fv
,
1380 MemoryRegionSection
*section
)
1382 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1383 hwaddr start_addr
= section
->offset_within_address_space
;
1384 uint16_t section_index
= phys_section_add(&d
->map
, section
);
1385 uint64_t num_pages
= int128_get64(int128_rshift(section
->size
,
1389 phys_page_set(d
, start_addr
>> TARGET_PAGE_BITS
, num_pages
, section_index
);
1392 void flatview_add_to_dispatch(FlatView
*fv
, MemoryRegionSection
*section
)
1394 MemoryRegionSection now
= *section
, remain
= *section
;
1395 Int128 page_size
= int128_make64(TARGET_PAGE_SIZE
);
1397 if (now
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1398 uint64_t left
= TARGET_PAGE_ALIGN(now
.offset_within_address_space
)
1399 - now
.offset_within_address_space
;
1401 now
.size
= int128_min(int128_make64(left
), now
.size
);
1402 register_subpage(fv
, &now
);
1404 now
.size
= int128_zero();
1406 while (int128_ne(remain
.size
, now
.size
)) {
1407 remain
.size
= int128_sub(remain
.size
, now
.size
);
1408 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1409 remain
.offset_within_region
+= int128_get64(now
.size
);
1411 if (int128_lt(remain
.size
, page_size
)) {
1412 register_subpage(fv
, &now
);
1413 } else if (remain
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1414 now
.size
= page_size
;
1415 register_subpage(fv
, &now
);
1417 now
.size
= int128_and(now
.size
, int128_neg(page_size
));
1418 register_multipage(fv
, &now
);
1423 void qemu_flush_coalesced_mmio_buffer(void)
1426 kvm_flush_coalesced_mmio_buffer();
1429 void qemu_mutex_lock_ramlist(void)
1431 qemu_mutex_lock(&ram_list
.mutex
);
1434 void qemu_mutex_unlock_ramlist(void)
1436 qemu_mutex_unlock(&ram_list
.mutex
);
1439 void ram_block_dump(Monitor
*mon
)
1445 monitor_printf(mon
, "%24s %8s %18s %18s %18s\n",
1446 "Block Name", "PSize", "Offset", "Used", "Total");
1447 RAMBLOCK_FOREACH(block
) {
1448 psize
= size_to_str(block
->page_size
);
1449 monitor_printf(mon
, "%24s %8s 0x%016" PRIx64
" 0x%016" PRIx64
1450 " 0x%016" PRIx64
"\n", block
->idstr
, psize
,
1451 (uint64_t)block
->offset
,
1452 (uint64_t)block
->used_length
,
1453 (uint64_t)block
->max_length
);
1461 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1462 * may or may not name the same files / on the same filesystem now as
1463 * when we actually open and map them. Iterate over the file
1464 * descriptors instead, and use qemu_fd_getpagesize().
1466 static int find_max_supported_pagesize(Object
*obj
, void *opaque
)
1469 long *hpsize_min
= opaque
;
1471 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1472 mem_path
= object_property_get_str(obj
, "mem-path", NULL
);
1474 long hpsize
= qemu_mempath_getpagesize(mem_path
);
1475 if (hpsize
< *hpsize_min
) {
1476 *hpsize_min
= hpsize
;
1479 *hpsize_min
= getpagesize();
1486 long qemu_getrampagesize(void)
1488 long hpsize
= LONG_MAX
;
1489 long mainrampagesize
;
1490 Object
*memdev_root
;
1493 mainrampagesize
= qemu_mempath_getpagesize(mem_path
);
1495 mainrampagesize
= getpagesize();
1498 /* it's possible we have memory-backend objects with
1499 * hugepage-backed RAM. these may get mapped into system
1500 * address space via -numa parameters or memory hotplug
1501 * hooks. we want to take these into account, but we
1502 * also want to make sure these supported hugepage
1503 * sizes are applicable across the entire range of memory
1504 * we may boot from, so we take the min across all
1505 * backends, and assume normal pages in cases where a
1506 * backend isn't backed by hugepages.
1508 memdev_root
= object_resolve_path("/objects", NULL
);
1510 object_child_foreach(memdev_root
, find_max_supported_pagesize
, &hpsize
);
1512 if (hpsize
== LONG_MAX
) {
1513 /* No additional memory regions found ==> Report main RAM page size */
1514 return mainrampagesize
;
1517 /* If NUMA is disabled or the NUMA nodes are not backed with a
1518 * memory-backend, then there is at least one node using "normal" RAM,
1519 * so if its page size is smaller we have got to report that size instead.
1521 if (hpsize
> mainrampagesize
&&
1522 (nb_numa_nodes
== 0 || numa_info
[0].node_memdev
== NULL
)) {
1525 error_report("Huge page support disabled (n/a for main memory).");
1528 return mainrampagesize
;
1534 long qemu_getrampagesize(void)
1536 return getpagesize();
1541 static int64_t get_file_size(int fd
)
1543 int64_t size
= lseek(fd
, 0, SEEK_END
);
1550 static int file_ram_open(const char *path
,
1551 const char *region_name
,
1556 char *sanitized_name
;
1562 fd
= open(path
, O_RDWR
);
1564 /* @path names an existing file, use it */
1567 if (errno
== ENOENT
) {
1568 /* @path names a file that doesn't exist, create it */
1569 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0644);
1574 } else if (errno
== EISDIR
) {
1575 /* @path names a directory, create a file there */
1576 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1577 sanitized_name
= g_strdup(region_name
);
1578 for (c
= sanitized_name
; *c
!= '\0'; c
++) {
1584 filename
= g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path
,
1586 g_free(sanitized_name
);
1588 fd
= mkstemp(filename
);
1596 if (errno
!= EEXIST
&& errno
!= EINTR
) {
1597 error_setg_errno(errp
, errno
,
1598 "can't open backing store %s for guest RAM",
1603 * Try again on EINTR and EEXIST. The latter happens when
1604 * something else creates the file between our two open().
1611 static void *file_ram_alloc(RAMBlock
*block
,
1619 block
->page_size
= qemu_fd_getpagesize(fd
);
1620 if (block
->mr
->align
% block
->page_size
) {
1621 error_setg(errp
, "alignment 0x%" PRIx64
1622 " must be multiples of page size 0x%zx",
1623 block
->mr
->align
, block
->page_size
);
1626 block
->mr
->align
= MAX(block
->page_size
, block
->mr
->align
);
1627 #if defined(__s390x__)
1628 if (kvm_enabled()) {
1629 block
->mr
->align
= MAX(block
->mr
->align
, QEMU_VMALLOC_ALIGN
);
1633 if (memory
< block
->page_size
) {
1634 error_setg(errp
, "memory size 0x" RAM_ADDR_FMT
" must be equal to "
1635 "or larger than page size 0x%zx",
1636 memory
, block
->page_size
);
1640 memory
= ROUND_UP(memory
, block
->page_size
);
1643 * ftruncate is not supported by hugetlbfs in older
1644 * hosts, so don't bother bailing out on errors.
1645 * If anything goes wrong with it under other filesystems,
1648 * Do not truncate the non-empty backend file to avoid corrupting
1649 * the existing data in the file. Disabling shrinking is not
1650 * enough. For example, the current vNVDIMM implementation stores
1651 * the guest NVDIMM labels at the end of the backend file. If the
1652 * backend file is later extended, QEMU will not be able to find
1653 * those labels. Therefore, extending the non-empty backend file
1654 * is disabled as well.
1656 if (truncate
&& ftruncate(fd
, memory
)) {
1657 perror("ftruncate");
1660 area
= qemu_ram_mmap(fd
, memory
, block
->mr
->align
,
1661 block
->flags
& RAM_SHARED
);
1662 if (area
== MAP_FAILED
) {
1663 error_setg_errno(errp
, errno
,
1664 "unable to map backing store for guest RAM");
1669 os_mem_prealloc(fd
, area
, memory
, smp_cpus
, errp
);
1670 if (errp
&& *errp
) {
1671 qemu_ram_munmap(area
, memory
);
1681 /* Allocate space within the ram_addr_t space that governs the
1683 * Called with the ramlist lock held.
1685 static ram_addr_t
find_ram_offset(ram_addr_t size
)
1687 RAMBlock
*block
, *next_block
;
1688 ram_addr_t offset
= RAM_ADDR_MAX
, mingap
= RAM_ADDR_MAX
;
1690 assert(size
!= 0); /* it would hand out same offset multiple times */
1692 if (QLIST_EMPTY_RCU(&ram_list
.blocks
)) {
1696 RAMBLOCK_FOREACH(block
) {
1697 ram_addr_t candidate
, next
= RAM_ADDR_MAX
;
1699 /* Align blocks to start on a 'long' in the bitmap
1700 * which makes the bitmap sync'ing take the fast path.
1702 candidate
= block
->offset
+ block
->max_length
;
1703 candidate
= ROUND_UP(candidate
, BITS_PER_LONG
<< TARGET_PAGE_BITS
);
1705 /* Search for the closest following block
1708 RAMBLOCK_FOREACH(next_block
) {
1709 if (next_block
->offset
>= candidate
) {
1710 next
= MIN(next
, next_block
->offset
);
1714 /* If it fits remember our place and remember the size
1715 * of gap, but keep going so that we might find a smaller
1716 * gap to fill so avoiding fragmentation.
1718 if (next
- candidate
>= size
&& next
- candidate
< mingap
) {
1720 mingap
= next
- candidate
;
1723 trace_find_ram_offset_loop(size
, candidate
, offset
, next
, mingap
);
1726 if (offset
== RAM_ADDR_MAX
) {
1727 fprintf(stderr
, "Failed to find gap of requested size: %" PRIu64
"\n",
1732 trace_find_ram_offset(size
, offset
);
1737 unsigned long last_ram_page(void)
1740 ram_addr_t last
= 0;
1743 RAMBLOCK_FOREACH(block
) {
1744 last
= MAX(last
, block
->offset
+ block
->max_length
);
1747 return last
>> TARGET_PAGE_BITS
;
1750 static void qemu_ram_setup_dump(void *addr
, ram_addr_t size
)
1754 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1755 if (!machine_dump_guest_core(current_machine
)) {
1756 ret
= qemu_madvise(addr
, size
, QEMU_MADV_DONTDUMP
);
1758 perror("qemu_madvise");
1759 fprintf(stderr
, "madvise doesn't support MADV_DONTDUMP, "
1760 "but dump_guest_core=off specified\n");
1765 const char *qemu_ram_get_idstr(RAMBlock
*rb
)
1770 bool qemu_ram_is_shared(RAMBlock
*rb
)
1772 return rb
->flags
& RAM_SHARED
;
1775 /* Note: Only set at the start of postcopy */
1776 bool qemu_ram_is_uf_zeroable(RAMBlock
*rb
)
1778 return rb
->flags
& RAM_UF_ZEROPAGE
;
1781 void qemu_ram_set_uf_zeroable(RAMBlock
*rb
)
1783 rb
->flags
|= RAM_UF_ZEROPAGE
;
1786 /* Called with iothread lock held. */
1787 void qemu_ram_set_idstr(RAMBlock
*new_block
, const char *name
, DeviceState
*dev
)
1792 assert(!new_block
->idstr
[0]);
1795 char *id
= qdev_get_dev_path(dev
);
1797 snprintf(new_block
->idstr
, sizeof(new_block
->idstr
), "%s/", id
);
1801 pstrcat(new_block
->idstr
, sizeof(new_block
->idstr
), name
);
1804 RAMBLOCK_FOREACH(block
) {
1805 if (block
!= new_block
&&
1806 !strcmp(block
->idstr
, new_block
->idstr
)) {
1807 fprintf(stderr
, "RAMBlock \"%s\" already registered, abort!\n",
1815 /* Called with iothread lock held. */
1816 void qemu_ram_unset_idstr(RAMBlock
*block
)
1818 /* FIXME: arch_init.c assumes that this is not called throughout
1819 * migration. Ignore the problem since hot-unplug during migration
1820 * does not work anyway.
1823 memset(block
->idstr
, 0, sizeof(block
->idstr
));
1827 size_t qemu_ram_pagesize(RAMBlock
*rb
)
1829 return rb
->page_size
;
1832 /* Returns the largest size of page in use */
1833 size_t qemu_ram_pagesize_largest(void)
1838 RAMBLOCK_FOREACH(block
) {
1839 largest
= MAX(largest
, qemu_ram_pagesize(block
));
1845 static int memory_try_enable_merging(void *addr
, size_t len
)
1847 if (!machine_mem_merge(current_machine
)) {
1848 /* disabled by the user */
1852 return qemu_madvise(addr
, len
, QEMU_MADV_MERGEABLE
);
1855 /* Only legal before guest might have detected the memory size: e.g. on
1856 * incoming migration, or right after reset.
1858 * As memory core doesn't know how is memory accessed, it is up to
1859 * resize callback to update device state and/or add assertions to detect
1860 * misuse, if necessary.
1862 int qemu_ram_resize(RAMBlock
*block
, ram_addr_t newsize
, Error
**errp
)
1866 newsize
= HOST_PAGE_ALIGN(newsize
);
1868 if (block
->used_length
== newsize
) {
1872 if (!(block
->flags
& RAM_RESIZEABLE
)) {
1873 error_setg_errno(errp
, EINVAL
,
1874 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1875 " in != 0x" RAM_ADDR_FMT
, block
->idstr
,
1876 newsize
, block
->used_length
);
1880 if (block
->max_length
< newsize
) {
1881 error_setg_errno(errp
, EINVAL
,
1882 "Length too large: %s: 0x" RAM_ADDR_FMT
1883 " > 0x" RAM_ADDR_FMT
, block
->idstr
,
1884 newsize
, block
->max_length
);
1888 cpu_physical_memory_clear_dirty_range(block
->offset
, block
->used_length
);
1889 block
->used_length
= newsize
;
1890 cpu_physical_memory_set_dirty_range(block
->offset
, block
->used_length
,
1892 memory_region_set_size(block
->mr
, newsize
);
1893 if (block
->resized
) {
1894 block
->resized(block
->idstr
, newsize
, block
->host
);
1899 /* Called with ram_list.mutex held */
1900 static void dirty_memory_extend(ram_addr_t old_ram_size
,
1901 ram_addr_t new_ram_size
)
1903 ram_addr_t old_num_blocks
= DIV_ROUND_UP(old_ram_size
,
1904 DIRTY_MEMORY_BLOCK_SIZE
);
1905 ram_addr_t new_num_blocks
= DIV_ROUND_UP(new_ram_size
,
1906 DIRTY_MEMORY_BLOCK_SIZE
);
1909 /* Only need to extend if block count increased */
1910 if (new_num_blocks
<= old_num_blocks
) {
1914 for (i
= 0; i
< DIRTY_MEMORY_NUM
; i
++) {
1915 DirtyMemoryBlocks
*old_blocks
;
1916 DirtyMemoryBlocks
*new_blocks
;
1919 old_blocks
= atomic_rcu_read(&ram_list
.dirty_memory
[i
]);
1920 new_blocks
= g_malloc(sizeof(*new_blocks
) +
1921 sizeof(new_blocks
->blocks
[0]) * new_num_blocks
);
1923 if (old_num_blocks
) {
1924 memcpy(new_blocks
->blocks
, old_blocks
->blocks
,
1925 old_num_blocks
* sizeof(old_blocks
->blocks
[0]));
1928 for (j
= old_num_blocks
; j
< new_num_blocks
; j
++) {
1929 new_blocks
->blocks
[j
] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE
);
1932 atomic_rcu_set(&ram_list
.dirty_memory
[i
], new_blocks
);
1935 g_free_rcu(old_blocks
, rcu
);
1940 static void ram_block_add(RAMBlock
*new_block
, Error
**errp
, bool shared
)
1943 RAMBlock
*last_block
= NULL
;
1944 ram_addr_t old_ram_size
, new_ram_size
;
1947 old_ram_size
= last_ram_page();
1949 qemu_mutex_lock_ramlist();
1950 new_block
->offset
= find_ram_offset(new_block
->max_length
);
1952 if (!new_block
->host
) {
1953 if (xen_enabled()) {
1954 xen_ram_alloc(new_block
->offset
, new_block
->max_length
,
1955 new_block
->mr
, &err
);
1957 error_propagate(errp
, err
);
1958 qemu_mutex_unlock_ramlist();
1962 new_block
->host
= phys_mem_alloc(new_block
->max_length
,
1963 &new_block
->mr
->align
, shared
);
1964 if (!new_block
->host
) {
1965 error_setg_errno(errp
, errno
,
1966 "cannot set up guest memory '%s'",
1967 memory_region_name(new_block
->mr
));
1968 qemu_mutex_unlock_ramlist();
1971 memory_try_enable_merging(new_block
->host
, new_block
->max_length
);
1975 new_ram_size
= MAX(old_ram_size
,
1976 (new_block
->offset
+ new_block
->max_length
) >> TARGET_PAGE_BITS
);
1977 if (new_ram_size
> old_ram_size
) {
1978 dirty_memory_extend(old_ram_size
, new_ram_size
);
1980 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1981 * QLIST (which has an RCU-friendly variant) does not have insertion at
1982 * tail, so save the last element in last_block.
1984 RAMBLOCK_FOREACH(block
) {
1986 if (block
->max_length
< new_block
->max_length
) {
1991 QLIST_INSERT_BEFORE_RCU(block
, new_block
, next
);
1992 } else if (last_block
) {
1993 QLIST_INSERT_AFTER_RCU(last_block
, new_block
, next
);
1994 } else { /* list is empty */
1995 QLIST_INSERT_HEAD_RCU(&ram_list
.blocks
, new_block
, next
);
1997 ram_list
.mru_block
= NULL
;
1999 /* Write list before version */
2002 qemu_mutex_unlock_ramlist();
2004 cpu_physical_memory_set_dirty_range(new_block
->offset
,
2005 new_block
->used_length
,
2008 if (new_block
->host
) {
2009 qemu_ram_setup_dump(new_block
->host
, new_block
->max_length
);
2010 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_HUGEPAGE
);
2011 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
2012 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_DONTFORK
);
2013 ram_block_notify_add(new_block
->host
, new_block
->max_length
);
2018 RAMBlock
*qemu_ram_alloc_from_fd(ram_addr_t size
, MemoryRegion
*mr
,
2022 RAMBlock
*new_block
;
2023 Error
*local_err
= NULL
;
2026 if (xen_enabled()) {
2027 error_setg(errp
, "-mem-path not supported with Xen");
2031 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2033 "host lacks kvm mmu notifiers, -mem-path unsupported");
2037 if (phys_mem_alloc
!= qemu_anon_ram_alloc
) {
2039 * file_ram_alloc() needs to allocate just like
2040 * phys_mem_alloc, but we haven't bothered to provide
2044 "-mem-path not supported with this accelerator");
2048 size
= HOST_PAGE_ALIGN(size
);
2049 file_size
= get_file_size(fd
);
2050 if (file_size
> 0 && file_size
< size
) {
2051 error_setg(errp
, "backing store %s size 0x%" PRIx64
2052 " does not match 'size' option 0x" RAM_ADDR_FMT
,
2053 mem_path
, file_size
, size
);
2057 new_block
= g_malloc0(sizeof(*new_block
));
2059 new_block
->used_length
= size
;
2060 new_block
->max_length
= size
;
2061 new_block
->flags
= share
? RAM_SHARED
: 0;
2062 new_block
->host
= file_ram_alloc(new_block
, size
, fd
, !file_size
, errp
);
2063 if (!new_block
->host
) {
2068 ram_block_add(new_block
, &local_err
, share
);
2071 error_propagate(errp
, local_err
);
2079 RAMBlock
*qemu_ram_alloc_from_file(ram_addr_t size
, MemoryRegion
*mr
,
2080 bool share
, const char *mem_path
,
2087 fd
= file_ram_open(mem_path
, memory_region_name(mr
), &created
, errp
);
2092 block
= qemu_ram_alloc_from_fd(size
, mr
, share
, fd
, errp
);
2106 RAMBlock
*qemu_ram_alloc_internal(ram_addr_t size
, ram_addr_t max_size
,
2107 void (*resized
)(const char*,
2110 void *host
, bool resizeable
, bool share
,
2111 MemoryRegion
*mr
, Error
**errp
)
2113 RAMBlock
*new_block
;
2114 Error
*local_err
= NULL
;
2116 size
= HOST_PAGE_ALIGN(size
);
2117 max_size
= HOST_PAGE_ALIGN(max_size
);
2118 new_block
= g_malloc0(sizeof(*new_block
));
2120 new_block
->resized
= resized
;
2121 new_block
->used_length
= size
;
2122 new_block
->max_length
= max_size
;
2123 assert(max_size
>= size
);
2125 new_block
->page_size
= getpagesize();
2126 new_block
->host
= host
;
2128 new_block
->flags
|= RAM_PREALLOC
;
2131 new_block
->flags
|= RAM_RESIZEABLE
;
2133 ram_block_add(new_block
, &local_err
, share
);
2136 error_propagate(errp
, local_err
);
2142 RAMBlock
*qemu_ram_alloc_from_ptr(ram_addr_t size
, void *host
,
2143 MemoryRegion
*mr
, Error
**errp
)
2145 return qemu_ram_alloc_internal(size
, size
, NULL
, host
, false,
2149 RAMBlock
*qemu_ram_alloc(ram_addr_t size
, bool share
,
2150 MemoryRegion
*mr
, Error
**errp
)
2152 return qemu_ram_alloc_internal(size
, size
, NULL
, NULL
, false,
2156 RAMBlock
*qemu_ram_alloc_resizeable(ram_addr_t size
, ram_addr_t maxsz
,
2157 void (*resized
)(const char*,
2160 MemoryRegion
*mr
, Error
**errp
)
2162 return qemu_ram_alloc_internal(size
, maxsz
, resized
, NULL
, true,
2166 static void reclaim_ramblock(RAMBlock
*block
)
2168 if (block
->flags
& RAM_PREALLOC
) {
2170 } else if (xen_enabled()) {
2171 xen_invalidate_map_cache_entry(block
->host
);
2173 } else if (block
->fd
>= 0) {
2174 qemu_ram_munmap(block
->host
, block
->max_length
);
2178 qemu_anon_ram_free(block
->host
, block
->max_length
);
2183 void qemu_ram_free(RAMBlock
*block
)
2190 ram_block_notify_remove(block
->host
, block
->max_length
);
2193 qemu_mutex_lock_ramlist();
2194 QLIST_REMOVE_RCU(block
, next
);
2195 ram_list
.mru_block
= NULL
;
2196 /* Write list before version */
2199 call_rcu(block
, reclaim_ramblock
, rcu
);
2200 qemu_mutex_unlock_ramlist();
2204 void qemu_ram_remap(ram_addr_t addr
, ram_addr_t length
)
2211 RAMBLOCK_FOREACH(block
) {
2212 offset
= addr
- block
->offset
;
2213 if (offset
< block
->max_length
) {
2214 vaddr
= ramblock_ptr(block
, offset
);
2215 if (block
->flags
& RAM_PREALLOC
) {
2217 } else if (xen_enabled()) {
2221 if (block
->fd
>= 0) {
2222 flags
|= (block
->flags
& RAM_SHARED
?
2223 MAP_SHARED
: MAP_PRIVATE
);
2224 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2225 flags
, block
->fd
, offset
);
2228 * Remap needs to match alloc. Accelerators that
2229 * set phys_mem_alloc never remap. If they did,
2230 * we'd need a remap hook here.
2232 assert(phys_mem_alloc
== qemu_anon_ram_alloc
);
2234 flags
|= MAP_PRIVATE
| MAP_ANONYMOUS
;
2235 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2238 if (area
!= vaddr
) {
2239 error_report("Could not remap addr: "
2240 RAM_ADDR_FMT
"@" RAM_ADDR_FMT
"",
2244 memory_try_enable_merging(vaddr
, length
);
2245 qemu_ram_setup_dump(vaddr
, length
);
2250 #endif /* !_WIN32 */
2252 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2253 * This should not be used for general purpose DMA. Use address_space_map
2254 * or address_space_rw instead. For local memory (e.g. video ram) that the
2255 * device owns, use memory_region_get_ram_ptr.
2257 * Called within RCU critical section.
2259 void *qemu_map_ram_ptr(RAMBlock
*ram_block
, ram_addr_t addr
)
2261 RAMBlock
*block
= ram_block
;
2263 if (block
== NULL
) {
2264 block
= qemu_get_ram_block(addr
);
2265 addr
-= block
->offset
;
2268 if (xen_enabled() && block
->host
== NULL
) {
2269 /* We need to check if the requested address is in the RAM
2270 * because we don't want to map the entire memory in QEMU.
2271 * In that case just map until the end of the page.
2273 if (block
->offset
== 0) {
2274 return xen_map_cache(addr
, 0, 0, false);
2277 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, false);
2279 return ramblock_ptr(block
, addr
);
2282 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2283 * but takes a size argument.
2285 * Called within RCU critical section.
2287 static void *qemu_ram_ptr_length(RAMBlock
*ram_block
, ram_addr_t addr
,
2288 hwaddr
*size
, bool lock
)
2290 RAMBlock
*block
= ram_block
;
2295 if (block
== NULL
) {
2296 block
= qemu_get_ram_block(addr
);
2297 addr
-= block
->offset
;
2299 *size
= MIN(*size
, block
->max_length
- addr
);
2301 if (xen_enabled() && block
->host
== NULL
) {
2302 /* We need to check if the requested address is in the RAM
2303 * because we don't want to map the entire memory in QEMU.
2304 * In that case just map the requested area.
2306 if (block
->offset
== 0) {
2307 return xen_map_cache(addr
, *size
, lock
, lock
);
2310 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, lock
);
2313 return ramblock_ptr(block
, addr
);
2316 /* Return the offset of a hostpointer within a ramblock */
2317 ram_addr_t
qemu_ram_block_host_offset(RAMBlock
*rb
, void *host
)
2319 ram_addr_t res
= (uint8_t *)host
- (uint8_t *)rb
->host
;
2320 assert((uintptr_t)host
>= (uintptr_t)rb
->host
);
2321 assert(res
< rb
->max_length
);
2327 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2330 * ptr: Host pointer to look up
2331 * round_offset: If true round the result offset down to a page boundary
2332 * *ram_addr: set to result ram_addr
2333 * *offset: set to result offset within the RAMBlock
2335 * Returns: RAMBlock (or NULL if not found)
2337 * By the time this function returns, the returned pointer is not protected
2338 * by RCU anymore. If the caller is not within an RCU critical section and
2339 * does not hold the iothread lock, it must have other means of protecting the
2340 * pointer, such as a reference to the region that includes the incoming
2343 RAMBlock
*qemu_ram_block_from_host(void *ptr
, bool round_offset
,
2347 uint8_t *host
= ptr
;
2349 if (xen_enabled()) {
2350 ram_addr_t ram_addr
;
2352 ram_addr
= xen_ram_addr_from_mapcache(ptr
);
2353 block
= qemu_get_ram_block(ram_addr
);
2355 *offset
= ram_addr
- block
->offset
;
2362 block
= atomic_rcu_read(&ram_list
.mru_block
);
2363 if (block
&& block
->host
&& host
- block
->host
< block
->max_length
) {
2367 RAMBLOCK_FOREACH(block
) {
2368 /* This case append when the block is not mapped. */
2369 if (block
->host
== NULL
) {
2372 if (host
- block
->host
< block
->max_length
) {
2381 *offset
= (host
- block
->host
);
2383 *offset
&= TARGET_PAGE_MASK
;
2390 * Finds the named RAMBlock
2392 * name: The name of RAMBlock to find
2394 * Returns: RAMBlock (or NULL if not found)
2396 RAMBlock
*qemu_ram_block_by_name(const char *name
)
2400 RAMBLOCK_FOREACH(block
) {
2401 if (!strcmp(name
, block
->idstr
)) {
2409 /* Some of the softmmu routines need to translate from a host pointer
2410 (typically a TLB entry) back to a ram offset. */
2411 ram_addr_t
qemu_ram_addr_from_host(void *ptr
)
2416 block
= qemu_ram_block_from_host(ptr
, false, &offset
);
2418 return RAM_ADDR_INVALID
;
2421 return block
->offset
+ offset
;
2424 /* Called within RCU critical section. */
2425 void memory_notdirty_write_prepare(NotDirtyInfo
*ndi
,
2428 ram_addr_t ram_addr
,
2432 ndi
->ram_addr
= ram_addr
;
2433 ndi
->mem_vaddr
= mem_vaddr
;
2435 ndi
->locked
= false;
2437 assert(tcg_enabled());
2438 if (!cpu_physical_memory_get_dirty_flag(ram_addr
, DIRTY_MEMORY_CODE
)) {
2441 tb_invalidate_phys_page_fast(ram_addr
, size
);
2445 /* Called within RCU critical section. */
2446 void memory_notdirty_write_complete(NotDirtyInfo
*ndi
)
2452 /* Set both VGA and migration bits for simplicity and to remove
2453 * the notdirty callback faster.
2455 cpu_physical_memory_set_dirty_range(ndi
->ram_addr
, ndi
->size
,
2456 DIRTY_CLIENTS_NOCODE
);
2457 /* we remove the notdirty callback only if the code has been
2459 if (!cpu_physical_memory_is_clean(ndi
->ram_addr
)) {
2460 tlb_set_dirty(ndi
->cpu
, ndi
->mem_vaddr
);
2464 /* Called within RCU critical section. */
2465 static void notdirty_mem_write(void *opaque
, hwaddr ram_addr
,
2466 uint64_t val
, unsigned size
)
2470 memory_notdirty_write_prepare(&ndi
, current_cpu
, current_cpu
->mem_io_vaddr
,
2475 stb_p(qemu_map_ram_ptr(NULL
, ram_addr
), val
);
2478 stw_p(qemu_map_ram_ptr(NULL
, ram_addr
), val
);
2481 stl_p(qemu_map_ram_ptr(NULL
, ram_addr
), val
);
2484 stq_p(qemu_map_ram_ptr(NULL
, ram_addr
), val
);
2489 memory_notdirty_write_complete(&ndi
);
2492 static bool notdirty_mem_accepts(void *opaque
, hwaddr addr
,
2493 unsigned size
, bool is_write
)
2498 static const MemoryRegionOps notdirty_mem_ops
= {
2499 .write
= notdirty_mem_write
,
2500 .valid
.accepts
= notdirty_mem_accepts
,
2501 .endianness
= DEVICE_NATIVE_ENDIAN
,
2503 .min_access_size
= 1,
2504 .max_access_size
= 8,
2508 .min_access_size
= 1,
2509 .max_access_size
= 8,
2514 /* Generate a debug exception if a watchpoint has been hit. */
2515 static void check_watchpoint(int offset
, int len
, MemTxAttrs attrs
, int flags
)
2517 CPUState
*cpu
= current_cpu
;
2518 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
2522 assert(tcg_enabled());
2523 if (cpu
->watchpoint_hit
) {
2524 /* We re-entered the check after replacing the TB. Now raise
2525 * the debug interrupt so that is will trigger after the
2526 * current instruction. */
2527 cpu_interrupt(cpu
, CPU_INTERRUPT_DEBUG
);
2530 vaddr
= (cpu
->mem_io_vaddr
& TARGET_PAGE_MASK
) + offset
;
2531 vaddr
= cc
->adjust_watchpoint_address(cpu
, vaddr
, len
);
2532 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
2533 if (cpu_watchpoint_address_matches(wp
, vaddr
, len
)
2534 && (wp
->flags
& flags
)) {
2535 if (flags
== BP_MEM_READ
) {
2536 wp
->flags
|= BP_WATCHPOINT_HIT_READ
;
2538 wp
->flags
|= BP_WATCHPOINT_HIT_WRITE
;
2540 wp
->hitaddr
= vaddr
;
2541 wp
->hitattrs
= attrs
;
2542 if (!cpu
->watchpoint_hit
) {
2543 if (wp
->flags
& BP_CPU
&&
2544 !cc
->debug_check_watchpoint(cpu
, wp
)) {
2545 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
2548 cpu
->watchpoint_hit
= wp
;
2550 /* Both tb_lock and iothread_mutex will be reset when
2551 * cpu_loop_exit or cpu_loop_exit_noexc longjmp
2552 * back into the cpu_exec main loop.
2555 tb_check_watchpoint(cpu
);
2556 if (wp
->flags
& BP_STOP_BEFORE_ACCESS
) {
2557 cpu
->exception_index
= EXCP_DEBUG
;
2560 /* Force execution of one insn next time. */
2561 cpu
->cflags_next_tb
= 1 | curr_cflags();
2562 cpu_loop_exit_noexc(cpu
);
2566 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
2571 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2572 so these check for a hit then pass through to the normal out-of-line
2574 static MemTxResult
watch_mem_read(void *opaque
, hwaddr addr
, uint64_t *pdata
,
2575 unsigned size
, MemTxAttrs attrs
)
2579 int asidx
= cpu_asidx_from_attrs(current_cpu
, attrs
);
2580 AddressSpace
*as
= current_cpu
->cpu_ases
[asidx
].as
;
2582 check_watchpoint(addr
& ~TARGET_PAGE_MASK
, size
, attrs
, BP_MEM_READ
);
2585 data
= address_space_ldub(as
, addr
, attrs
, &res
);
2588 data
= address_space_lduw(as
, addr
, attrs
, &res
);
2591 data
= address_space_ldl(as
, addr
, attrs
, &res
);
2594 data
= address_space_ldq(as
, addr
, attrs
, &res
);
2602 static MemTxResult
watch_mem_write(void *opaque
, hwaddr addr
,
2603 uint64_t val
, unsigned size
,
2607 int asidx
= cpu_asidx_from_attrs(current_cpu
, attrs
);
2608 AddressSpace
*as
= current_cpu
->cpu_ases
[asidx
].as
;
2610 check_watchpoint(addr
& ~TARGET_PAGE_MASK
, size
, attrs
, BP_MEM_WRITE
);
2613 address_space_stb(as
, addr
, val
, attrs
, &res
);
2616 address_space_stw(as
, addr
, val
, attrs
, &res
);
2619 address_space_stl(as
, addr
, val
, attrs
, &res
);
2622 address_space_stq(as
, addr
, val
, attrs
, &res
);
2629 static const MemoryRegionOps watch_mem_ops
= {
2630 .read_with_attrs
= watch_mem_read
,
2631 .write_with_attrs
= watch_mem_write
,
2632 .endianness
= DEVICE_NATIVE_ENDIAN
,
2634 .min_access_size
= 1,
2635 .max_access_size
= 8,
2639 .min_access_size
= 1,
2640 .max_access_size
= 8,
2645 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2646 MemTxAttrs attrs
, uint8_t *buf
, int len
);
2647 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2648 const uint8_t *buf
, int len
);
2649 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, int len
,
2652 static MemTxResult
subpage_read(void *opaque
, hwaddr addr
, uint64_t *data
,
2653 unsigned len
, MemTxAttrs attrs
)
2655 subpage_t
*subpage
= opaque
;
2659 #if defined(DEBUG_SUBPAGE)
2660 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
"\n", __func__
,
2661 subpage
, len
, addr
);
2663 res
= flatview_read(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2669 *data
= ldub_p(buf
);
2672 *data
= lduw_p(buf
);
2685 static MemTxResult
subpage_write(void *opaque
, hwaddr addr
,
2686 uint64_t value
, unsigned len
, MemTxAttrs attrs
)
2688 subpage_t
*subpage
= opaque
;
2691 #if defined(DEBUG_SUBPAGE)
2692 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2693 " value %"PRIx64
"\n",
2694 __func__
, subpage
, len
, addr
, value
);
2712 return flatview_write(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2715 static bool subpage_accepts(void *opaque
, hwaddr addr
,
2716 unsigned len
, bool is_write
)
2718 subpage_t
*subpage
= opaque
;
2719 #if defined(DEBUG_SUBPAGE)
2720 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx
"\n",
2721 __func__
, subpage
, is_write
? 'w' : 'r', len
, addr
);
2724 return flatview_access_valid(subpage
->fv
, addr
+ subpage
->base
,
2728 static const MemoryRegionOps subpage_ops
= {
2729 .read_with_attrs
= subpage_read
,
2730 .write_with_attrs
= subpage_write
,
2731 .impl
.min_access_size
= 1,
2732 .impl
.max_access_size
= 8,
2733 .valid
.min_access_size
= 1,
2734 .valid
.max_access_size
= 8,
2735 .valid
.accepts
= subpage_accepts
,
2736 .endianness
= DEVICE_NATIVE_ENDIAN
,
2739 static int subpage_register (subpage_t
*mmio
, uint32_t start
, uint32_t end
,
2744 if (start
>= TARGET_PAGE_SIZE
|| end
>= TARGET_PAGE_SIZE
)
2746 idx
= SUBPAGE_IDX(start
);
2747 eidx
= SUBPAGE_IDX(end
);
2748 #if defined(DEBUG_SUBPAGE)
2749 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2750 __func__
, mmio
, start
, end
, idx
, eidx
, section
);
2752 for (; idx
<= eidx
; idx
++) {
2753 mmio
->sub_section
[idx
] = section
;
2759 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
)
2763 mmio
= g_malloc0(sizeof(subpage_t
) + TARGET_PAGE_SIZE
* sizeof(uint16_t));
2766 memory_region_init_io(&mmio
->iomem
, NULL
, &subpage_ops
, mmio
,
2767 NULL
, TARGET_PAGE_SIZE
);
2768 mmio
->iomem
.subpage
= true;
2769 #if defined(DEBUG_SUBPAGE)
2770 printf("%s: %p base " TARGET_FMT_plx
" len %08x\n", __func__
,
2771 mmio
, base
, TARGET_PAGE_SIZE
);
2773 subpage_register(mmio
, 0, TARGET_PAGE_SIZE
-1, PHYS_SECTION_UNASSIGNED
);
2778 static uint16_t dummy_section(PhysPageMap
*map
, FlatView
*fv
, MemoryRegion
*mr
)
2781 MemoryRegionSection section
= {
2784 .offset_within_address_space
= 0,
2785 .offset_within_region
= 0,
2786 .size
= int128_2_64(),
2789 return phys_section_add(map
, §ion
);
2792 static void readonly_mem_write(void *opaque
, hwaddr addr
,
2793 uint64_t val
, unsigned size
)
2795 /* Ignore any write to ROM. */
2798 static bool readonly_mem_accepts(void *opaque
, hwaddr addr
,
2799 unsigned size
, bool is_write
)
2804 /* This will only be used for writes, because reads are special cased
2805 * to directly access the underlying host ram.
2807 static const MemoryRegionOps readonly_mem_ops
= {
2808 .write
= readonly_mem_write
,
2809 .valid
.accepts
= readonly_mem_accepts
,
2810 .endianness
= DEVICE_NATIVE_ENDIAN
,
2812 .min_access_size
= 1,
2813 .max_access_size
= 8,
2817 .min_access_size
= 1,
2818 .max_access_size
= 8,
2823 MemoryRegion
*iotlb_to_region(CPUState
*cpu
, hwaddr index
, MemTxAttrs attrs
)
2825 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
2826 CPUAddressSpace
*cpuas
= &cpu
->cpu_ases
[asidx
];
2827 AddressSpaceDispatch
*d
= atomic_rcu_read(&cpuas
->memory_dispatch
);
2828 MemoryRegionSection
*sections
= d
->map
.sections
;
2830 return sections
[index
& ~TARGET_PAGE_MASK
].mr
;
2833 static void io_mem_init(void)
2835 memory_region_init_io(&io_mem_rom
, NULL
, &readonly_mem_ops
,
2836 NULL
, NULL
, UINT64_MAX
);
2837 memory_region_init_io(&io_mem_unassigned
, NULL
, &unassigned_mem_ops
, NULL
,
2840 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
2841 * which can be called without the iothread mutex.
2843 memory_region_init_io(&io_mem_notdirty
, NULL
, ¬dirty_mem_ops
, NULL
,
2845 memory_region_clear_global_locking(&io_mem_notdirty
);
2847 memory_region_init_io(&io_mem_watch
, NULL
, &watch_mem_ops
, NULL
,
2851 AddressSpaceDispatch
*address_space_dispatch_new(FlatView
*fv
)
2853 AddressSpaceDispatch
*d
= g_new0(AddressSpaceDispatch
, 1);
2856 n
= dummy_section(&d
->map
, fv
, &io_mem_unassigned
);
2857 assert(n
== PHYS_SECTION_UNASSIGNED
);
2858 n
= dummy_section(&d
->map
, fv
, &io_mem_notdirty
);
2859 assert(n
== PHYS_SECTION_NOTDIRTY
);
2860 n
= dummy_section(&d
->map
, fv
, &io_mem_rom
);
2861 assert(n
== PHYS_SECTION_ROM
);
2862 n
= dummy_section(&d
->map
, fv
, &io_mem_watch
);
2863 assert(n
== PHYS_SECTION_WATCH
);
2865 d
->phys_map
= (PhysPageEntry
) { .ptr
= PHYS_MAP_NODE_NIL
, .skip
= 1 };
2870 void address_space_dispatch_free(AddressSpaceDispatch
*d
)
2872 phys_sections_free(&d
->map
);
2876 static void tcg_commit(MemoryListener
*listener
)
2878 CPUAddressSpace
*cpuas
;
2879 AddressSpaceDispatch
*d
;
2881 /* since each CPU stores ram addresses in its TLB cache, we must
2882 reset the modified entries */
2883 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2884 cpu_reloading_memory_map();
2885 /* The CPU and TLB are protected by the iothread lock.
2886 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2887 * may have split the RCU critical section.
2889 d
= address_space_to_dispatch(cpuas
->as
);
2890 atomic_rcu_set(&cpuas
->memory_dispatch
, d
);
2891 tlb_flush(cpuas
->cpu
);
2894 static void memory_map_init(void)
2896 system_memory
= g_malloc(sizeof(*system_memory
));
2898 memory_region_init(system_memory
, NULL
, "system", UINT64_MAX
);
2899 address_space_init(&address_space_memory
, system_memory
, "memory");
2901 system_io
= g_malloc(sizeof(*system_io
));
2902 memory_region_init_io(system_io
, NULL
, &unassigned_io_ops
, NULL
, "io",
2904 address_space_init(&address_space_io
, system_io
, "I/O");
2907 MemoryRegion
*get_system_memory(void)
2909 return system_memory
;
2912 MemoryRegion
*get_system_io(void)
2917 #endif /* !defined(CONFIG_USER_ONLY) */
2919 /* physical memory access (slow version, mainly for debug) */
2920 #if defined(CONFIG_USER_ONLY)
2921 int cpu_memory_rw_debug(CPUState
*cpu
, target_ulong addr
,
2922 uint8_t *buf
, int len
, int is_write
)
2929 page
= addr
& TARGET_PAGE_MASK
;
2930 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
2933 flags
= page_get_flags(page
);
2934 if (!(flags
& PAGE_VALID
))
2937 if (!(flags
& PAGE_WRITE
))
2939 /* XXX: this code should not depend on lock_user */
2940 if (!(p
= lock_user(VERIFY_WRITE
, addr
, l
, 0)))
2943 unlock_user(p
, addr
, l
);
2945 if (!(flags
& PAGE_READ
))
2947 /* XXX: this code should not depend on lock_user */
2948 if (!(p
= lock_user(VERIFY_READ
, addr
, l
, 1)))
2951 unlock_user(p
, addr
, 0);
2962 static void invalidate_and_set_dirty(MemoryRegion
*mr
, hwaddr addr
,
2965 uint8_t dirty_log_mask
= memory_region_get_dirty_log_mask(mr
);
2966 addr
+= memory_region_get_ram_addr(mr
);
2968 /* No early return if dirty_log_mask is or becomes 0, because
2969 * cpu_physical_memory_set_dirty_range will still call
2970 * xen_modified_memory.
2972 if (dirty_log_mask
) {
2974 cpu_physical_memory_range_includes_clean(addr
, length
, dirty_log_mask
);
2976 if (dirty_log_mask
& (1 << DIRTY_MEMORY_CODE
)) {
2977 assert(tcg_enabled());
2979 tb_invalidate_phys_range(addr
, addr
+ length
);
2981 dirty_log_mask
&= ~(1 << DIRTY_MEMORY_CODE
);
2983 cpu_physical_memory_set_dirty_range(addr
, length
, dirty_log_mask
);
2986 static int memory_access_size(MemoryRegion
*mr
, unsigned l
, hwaddr addr
)
2988 unsigned access_size_max
= mr
->ops
->valid
.max_access_size
;
2990 /* Regions are assumed to support 1-4 byte accesses unless
2991 otherwise specified. */
2992 if (access_size_max
== 0) {
2993 access_size_max
= 4;
2996 /* Bound the maximum access by the alignment of the address. */
2997 if (!mr
->ops
->impl
.unaligned
) {
2998 unsigned align_size_max
= addr
& -addr
;
2999 if (align_size_max
!= 0 && align_size_max
< access_size_max
) {
3000 access_size_max
= align_size_max
;
3004 /* Don't attempt accesses larger than the maximum. */
3005 if (l
> access_size_max
) {
3006 l
= access_size_max
;
3013 static bool prepare_mmio_access(MemoryRegion
*mr
)
3015 bool unlocked
= !qemu_mutex_iothread_locked();
3016 bool release_lock
= false;
3018 if (unlocked
&& mr
->global_locking
) {
3019 qemu_mutex_lock_iothread();
3021 release_lock
= true;
3023 if (mr
->flush_coalesced_mmio
) {
3025 qemu_mutex_lock_iothread();
3027 qemu_flush_coalesced_mmio_buffer();
3029 qemu_mutex_unlock_iothread();
3033 return release_lock
;
3036 /* Called within RCU critical section. */
3037 static MemTxResult
flatview_write_continue(FlatView
*fv
, hwaddr addr
,
3040 int len
, hwaddr addr1
,
3041 hwaddr l
, MemoryRegion
*mr
)
3045 MemTxResult result
= MEMTX_OK
;
3046 bool release_lock
= false;
3049 if (!memory_access_is_direct(mr
, true)) {
3050 release_lock
|= prepare_mmio_access(mr
);
3051 l
= memory_access_size(mr
, l
, addr1
);
3052 /* XXX: could force current_cpu to NULL to avoid
3056 /* 64 bit write access */
3058 result
|= memory_region_dispatch_write(mr
, addr1
, val
, 8,
3062 /* 32 bit write access */
3063 val
= (uint32_t)ldl_p(buf
);
3064 result
|= memory_region_dispatch_write(mr
, addr1
, val
, 4,
3068 /* 16 bit write access */
3070 result
|= memory_region_dispatch_write(mr
, addr1
, val
, 2,
3074 /* 8 bit write access */
3076 result
|= memory_region_dispatch_write(mr
, addr1
, val
, 1,
3084 ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
3085 memcpy(ptr
, buf
, l
);
3086 invalidate_and_set_dirty(mr
, addr1
, l
);
3090 qemu_mutex_unlock_iothread();
3091 release_lock
= false;
3103 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true);
3109 /* Called from RCU critical section. */
3110 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
3111 const uint8_t *buf
, int len
)
3116 MemTxResult result
= MEMTX_OK
;
3119 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true);
3120 result
= flatview_write_continue(fv
, addr
, attrs
, buf
, len
,
3126 /* Called within RCU critical section. */
3127 MemTxResult
flatview_read_continue(FlatView
*fv
, hwaddr addr
,
3128 MemTxAttrs attrs
, uint8_t *buf
,
3129 int len
, hwaddr addr1
, hwaddr l
,
3134 MemTxResult result
= MEMTX_OK
;
3135 bool release_lock
= false;
3138 if (!memory_access_is_direct(mr
, false)) {
3140 release_lock
|= prepare_mmio_access(mr
);
3141 l
= memory_access_size(mr
, l
, addr1
);
3144 /* 64 bit read access */
3145 result
|= memory_region_dispatch_read(mr
, addr1
, &val
, 8,
3150 /* 32 bit read access */
3151 result
|= memory_region_dispatch_read(mr
, addr1
, &val
, 4,
3156 /* 16 bit read access */
3157 result
|= memory_region_dispatch_read(mr
, addr1
, &val
, 2,
3162 /* 8 bit read access */
3163 result
|= memory_region_dispatch_read(mr
, addr1
, &val
, 1,
3172 ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
3173 memcpy(buf
, ptr
, l
);
3177 qemu_mutex_unlock_iothread();
3178 release_lock
= false;
3190 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false);
3196 /* Called from RCU critical section. */
3197 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
3198 MemTxAttrs attrs
, uint8_t *buf
, int len
)
3205 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false);
3206 return flatview_read_continue(fv
, addr
, attrs
, buf
, len
,
3210 MemTxResult
address_space_read_full(AddressSpace
*as
, hwaddr addr
,
3211 MemTxAttrs attrs
, uint8_t *buf
, int len
)
3213 MemTxResult result
= MEMTX_OK
;
3218 fv
= address_space_to_flatview(as
);
3219 result
= flatview_read(fv
, addr
, attrs
, buf
, len
);
3226 MemTxResult
address_space_write(AddressSpace
*as
, hwaddr addr
,
3228 const uint8_t *buf
, int len
)
3230 MemTxResult result
= MEMTX_OK
;
3235 fv
= address_space_to_flatview(as
);
3236 result
= flatview_write(fv
, addr
, attrs
, buf
, len
);
3243 MemTxResult
address_space_rw(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
,
3244 uint8_t *buf
, int len
, bool is_write
)
3247 return address_space_write(as
, addr
, attrs
, buf
, len
);
3249 return address_space_read_full(as
, addr
, attrs
, buf
, len
);
3253 void cpu_physical_memory_rw(hwaddr addr
, uint8_t *buf
,
3254 int len
, int is_write
)
3256 address_space_rw(&address_space_memory
, addr
, MEMTXATTRS_UNSPECIFIED
,
3257 buf
, len
, is_write
);
3260 enum write_rom_type
{
3265 static inline void cpu_physical_memory_write_rom_internal(AddressSpace
*as
,
3266 hwaddr addr
, const uint8_t *buf
, int len
, enum write_rom_type type
)
3276 mr
= address_space_translate(as
, addr
, &addr1
, &l
, true);
3278 if (!(memory_region_is_ram(mr
) ||
3279 memory_region_is_romd(mr
))) {
3280 l
= memory_access_size(mr
, l
, addr1
);
3283 ptr
= qemu_map_ram_ptr(mr
->ram_block
, addr1
);
3286 memcpy(ptr
, buf
, l
);
3287 invalidate_and_set_dirty(mr
, addr1
, l
);
3290 flush_icache_range((uintptr_t)ptr
, (uintptr_t)ptr
+ l
);
3301 /* used for ROM loading : can write in RAM and ROM */
3302 void cpu_physical_memory_write_rom(AddressSpace
*as
, hwaddr addr
,
3303 const uint8_t *buf
, int len
)
3305 cpu_physical_memory_write_rom_internal(as
, addr
, buf
, len
, WRITE_DATA
);
3308 void cpu_flush_icache_range(hwaddr start
, int len
)
3311 * This function should do the same thing as an icache flush that was
3312 * triggered from within the guest. For TCG we are always cache coherent,
3313 * so there is no need to flush anything. For KVM / Xen we need to flush
3314 * the host's instruction cache at least.
3316 if (tcg_enabled()) {
3320 cpu_physical_memory_write_rom_internal(&address_space_memory
,
3321 start
, NULL
, len
, FLUSH_CACHE
);
3332 static BounceBuffer bounce
;
3334 typedef struct MapClient
{
3336 QLIST_ENTRY(MapClient
) link
;
3339 QemuMutex map_client_list_lock
;
3340 static QLIST_HEAD(map_client_list
, MapClient
) map_client_list
3341 = QLIST_HEAD_INITIALIZER(map_client_list
);
3343 static void cpu_unregister_map_client_do(MapClient
*client
)
3345 QLIST_REMOVE(client
, link
);
3349 static void cpu_notify_map_clients_locked(void)
3353 while (!QLIST_EMPTY(&map_client_list
)) {
3354 client
= QLIST_FIRST(&map_client_list
);
3355 qemu_bh_schedule(client
->bh
);
3356 cpu_unregister_map_client_do(client
);
3360 void cpu_register_map_client(QEMUBH
*bh
)
3362 MapClient
*client
= g_malloc(sizeof(*client
));
3364 qemu_mutex_lock(&map_client_list_lock
);
3366 QLIST_INSERT_HEAD(&map_client_list
, client
, link
);
3367 if (!atomic_read(&bounce
.in_use
)) {
3368 cpu_notify_map_clients_locked();
3370 qemu_mutex_unlock(&map_client_list_lock
);
3373 void cpu_exec_init_all(void)
3375 qemu_mutex_init(&ram_list
.mutex
);
3376 /* The data structures we set up here depend on knowing the page size,
3377 * so no more changes can be made after this point.
3378 * In an ideal world, nothing we did before we had finished the
3379 * machine setup would care about the target page size, and we could
3380 * do this much later, rather than requiring board models to state
3381 * up front what their requirements are.
3383 finalize_target_page_bits();
3386 qemu_mutex_init(&map_client_list_lock
);
3389 void cpu_unregister_map_client(QEMUBH
*bh
)
3393 qemu_mutex_lock(&map_client_list_lock
);
3394 QLIST_FOREACH(client
, &map_client_list
, link
) {
3395 if (client
->bh
== bh
) {
3396 cpu_unregister_map_client_do(client
);
3400 qemu_mutex_unlock(&map_client_list_lock
);
3403 static void cpu_notify_map_clients(void)
3405 qemu_mutex_lock(&map_client_list_lock
);
3406 cpu_notify_map_clients_locked();
3407 qemu_mutex_unlock(&map_client_list_lock
);
3410 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, int len
,
3418 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
);
3419 if (!memory_access_is_direct(mr
, is_write
)) {
3420 l
= memory_access_size(mr
, l
, addr
);
3421 if (!memory_region_access_valid(mr
, xlat
, l
, is_write
)) {
3432 bool address_space_access_valid(AddressSpace
*as
, hwaddr addr
,
3433 int len
, bool is_write
)
3439 fv
= address_space_to_flatview(as
);
3440 result
= flatview_access_valid(fv
, addr
, len
, is_write
);
3446 flatview_extend_translation(FlatView
*fv
, hwaddr addr
,
3448 MemoryRegion
*mr
, hwaddr base
, hwaddr len
,
3453 MemoryRegion
*this_mr
;
3459 if (target_len
== 0) {
3464 this_mr
= flatview_translate(fv
, addr
, &xlat
,
3466 if (this_mr
!= mr
|| xlat
!= base
+ done
) {
3472 /* Map a physical memory region into a host virtual address.
3473 * May map a subset of the requested range, given by and returned in *plen.
3474 * May return NULL if resources needed to perform the mapping are exhausted.
3475 * Use only for reads OR writes - not for read-modify-write operations.
3476 * Use cpu_register_map_client() to know when retrying the map operation is
3477 * likely to succeed.
3479 void *address_space_map(AddressSpace
*as
,
3496 fv
= address_space_to_flatview(as
);
3497 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
);
3499 if (!memory_access_is_direct(mr
, is_write
)) {
3500 if (atomic_xchg(&bounce
.in_use
, true)) {
3504 /* Avoid unbounded allocations */
3505 l
= MIN(l
, TARGET_PAGE_SIZE
);
3506 bounce
.buffer
= qemu_memalign(TARGET_PAGE_SIZE
, l
);
3510 memory_region_ref(mr
);
3513 flatview_read(fv
, addr
, MEMTXATTRS_UNSPECIFIED
,
3519 return bounce
.buffer
;
3523 memory_region_ref(mr
);
3524 *plen
= flatview_extend_translation(fv
, addr
, len
, mr
, xlat
,
3526 ptr
= qemu_ram_ptr_length(mr
->ram_block
, xlat
, plen
, true);
3532 /* Unmaps a memory region previously mapped by address_space_map().
3533 * Will also mark the memory as dirty if is_write == 1. access_len gives
3534 * the amount of memory that was actually read or written by the caller.
3536 void address_space_unmap(AddressSpace
*as
, void *buffer
, hwaddr len
,
3537 int is_write
, hwaddr access_len
)
3539 if (buffer
!= bounce
.buffer
) {
3543 mr
= memory_region_from_host(buffer
, &addr1
);
3546 invalidate_and_set_dirty(mr
, addr1
, access_len
);
3548 if (xen_enabled()) {
3549 xen_invalidate_map_cache_entry(buffer
);
3551 memory_region_unref(mr
);
3555 address_space_write(as
, bounce
.addr
, MEMTXATTRS_UNSPECIFIED
,
3556 bounce
.buffer
, access_len
);
3558 qemu_vfree(bounce
.buffer
);
3559 bounce
.buffer
= NULL
;
3560 memory_region_unref(bounce
.mr
);
3561 atomic_mb_set(&bounce
.in_use
, false);
3562 cpu_notify_map_clients();
3565 void *cpu_physical_memory_map(hwaddr addr
,
3569 return address_space_map(&address_space_memory
, addr
, plen
, is_write
);
3572 void cpu_physical_memory_unmap(void *buffer
, hwaddr len
,
3573 int is_write
, hwaddr access_len
)
3575 return address_space_unmap(&address_space_memory
, buffer
, len
, is_write
, access_len
);
3578 #define ARG1_DECL AddressSpace *as
3581 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3582 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3583 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3584 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3585 #define RCU_READ_LOCK(...) rcu_read_lock()
3586 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3587 #include "memory_ldst.inc.c"
3589 int64_t address_space_cache_init(MemoryRegionCache
*cache
,
3601 void address_space_cache_invalidate(MemoryRegionCache
*cache
,
3607 void address_space_cache_destroy(MemoryRegionCache
*cache
)
3612 #define ARG1_DECL MemoryRegionCache *cache
3614 #define SUFFIX _cached
3615 #define TRANSLATE(addr, ...) \
3616 address_space_translate(cache->as, cache->xlat + (addr), __VA_ARGS__)
3617 #define IS_DIRECT(mr, is_write) true
3618 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3619 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3620 #define RCU_READ_LOCK() rcu_read_lock()
3621 #define RCU_READ_UNLOCK() rcu_read_unlock()
3622 #include "memory_ldst.inc.c"
3624 /* virtual memory access for debug (includes writing to ROM) */
3625 int cpu_memory_rw_debug(CPUState
*cpu
, target_ulong addr
,
3626 uint8_t *buf
, int len
, int is_write
)
3632 cpu_synchronize_state(cpu
);
3637 page
= addr
& TARGET_PAGE_MASK
;
3638 phys_addr
= cpu_get_phys_page_attrs_debug(cpu
, page
, &attrs
);
3639 asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
3640 /* if no physical page mapped, return an error */
3641 if (phys_addr
== -1)
3643 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3646 phys_addr
+= (addr
& ~TARGET_PAGE_MASK
);
3648 cpu_physical_memory_write_rom(cpu
->cpu_ases
[asidx
].as
,
3651 address_space_rw(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3652 MEMTXATTRS_UNSPECIFIED
,
3663 * Allows code that needs to deal with migration bitmaps etc to still be built
3664 * target independent.
3666 size_t qemu_target_page_size(void)
3668 return TARGET_PAGE_SIZE
;
3671 int qemu_target_page_bits(void)
3673 return TARGET_PAGE_BITS
;
3676 int qemu_target_page_bits_min(void)
3678 return TARGET_PAGE_BITS_MIN
;
3683 * A helper function for the _utterly broken_ virtio device model to find out if
3684 * it's running on a big endian machine. Don't do this at home kids!
3686 bool target_words_bigendian(void);
3687 bool target_words_bigendian(void)
3689 #if defined(TARGET_WORDS_BIGENDIAN)
3696 #ifndef CONFIG_USER_ONLY
3697 bool cpu_physical_memory_is_io(hwaddr phys_addr
)
3704 mr
= address_space_translate(&address_space_memory
,
3705 phys_addr
, &phys_addr
, &l
, false);
3707 res
= !(memory_region_is_ram(mr
) || memory_region_is_romd(mr
));
3712 int qemu_ram_foreach_block(RAMBlockIterFunc func
, void *opaque
)
3718 RAMBLOCK_FOREACH(block
) {
3719 ret
= func(block
->idstr
, block
->host
, block
->offset
,
3720 block
->used_length
, opaque
);
3730 * Unmap pages of memory from start to start+length such that
3731 * they a) read as 0, b) Trigger whatever fault mechanism
3732 * the OS provides for postcopy.
3733 * The pages must be unmapped by the end of the function.
3734 * Returns: 0 on success, none-0 on failure
3737 int ram_block_discard_range(RAMBlock
*rb
, uint64_t start
, size_t length
)
3741 uint8_t *host_startaddr
= rb
->host
+ start
;
3743 if ((uintptr_t)host_startaddr
& (rb
->page_size
- 1)) {
3744 error_report("ram_block_discard_range: Unaligned start address: %p",
3749 if ((start
+ length
) <= rb
->used_length
) {
3750 bool need_madvise
, need_fallocate
;
3751 uint8_t *host_endaddr
= host_startaddr
+ length
;
3752 if ((uintptr_t)host_endaddr
& (rb
->page_size
- 1)) {
3753 error_report("ram_block_discard_range: Unaligned end address: %p",
3758 errno
= ENOTSUP
; /* If we are missing MADVISE etc */
3760 /* The logic here is messy;
3761 * madvise DONTNEED fails for hugepages
3762 * fallocate works on hugepages and shmem
3764 need_madvise
= (rb
->page_size
== qemu_host_page_size
);
3765 need_fallocate
= rb
->fd
!= -1;
3766 if (need_fallocate
) {
3767 /* For a file, this causes the area of the file to be zero'd
3768 * if read, and for hugetlbfs also causes it to be unmapped
3769 * so a userfault will trigger.
3771 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3772 ret
= fallocate(rb
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3776 error_report("ram_block_discard_range: Failed to fallocate "
3777 "%s:%" PRIx64
" +%zx (%d)",
3778 rb
->idstr
, start
, length
, ret
);
3783 error_report("ram_block_discard_range: fallocate not available/file"
3784 "%s:%" PRIx64
" +%zx (%d)",
3785 rb
->idstr
, start
, length
, ret
);
3790 /* For normal RAM this causes it to be unmapped,
3791 * for shared memory it causes the local mapping to disappear
3792 * and to fall back on the file contents (which we just
3793 * fallocate'd away).
3795 #if defined(CONFIG_MADVISE)
3796 ret
= madvise(host_startaddr
, length
, MADV_DONTNEED
);
3799 error_report("ram_block_discard_range: Failed to discard range "
3800 "%s:%" PRIx64
" +%zx (%d)",
3801 rb
->idstr
, start
, length
, ret
);
3806 error_report("ram_block_discard_range: MADVISE not available"
3807 "%s:%" PRIx64
" +%zx (%d)",
3808 rb
->idstr
, start
, length
, ret
);
3812 trace_ram_block_discard_range(rb
->idstr
, host_startaddr
, length
,
3813 need_madvise
, need_fallocate
, ret
);
3815 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3816 "/%zx/" RAM_ADDR_FMT
")",
3817 rb
->idstr
, start
, length
, rb
->used_length
);
3826 void page_size_init(void)
3828 /* NOTE: we can always suppose that qemu_host_page_size >=
3830 if (qemu_host_page_size
== 0) {
3831 qemu_host_page_size
= qemu_real_host_page_size
;
3833 if (qemu_host_page_size
< TARGET_PAGE_SIZE
) {
3834 qemu_host_page_size
= TARGET_PAGE_SIZE
;
3836 qemu_host_page_mask
= -(intptr_t)qemu_host_page_size
;
3839 #if !defined(CONFIG_USER_ONLY)
3841 static void mtree_print_phys_entries(fprintf_function mon
, void *f
,
3842 int start
, int end
, int skip
, int ptr
)
3844 if (start
== end
- 1) {
3845 mon(f
, "\t%3d ", start
);
3847 mon(f
, "\t%3d..%-3d ", start
, end
- 1);
3849 mon(f
, " skip=%d ", skip
);
3850 if (ptr
== PHYS_MAP_NODE_NIL
) {
3853 mon(f
, " ptr=#%d", ptr
);
3855 mon(f
, " ptr=[%d]", ptr
);
3860 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3861 int128_sub((size), int128_one())) : 0)
3863 void mtree_print_dispatch(fprintf_function mon
, void *f
,
3864 AddressSpaceDispatch
*d
, MemoryRegion
*root
)
3868 mon(f
, " Dispatch\n");
3869 mon(f
, " Physical sections\n");
3871 for (i
= 0; i
< d
->map
.sections_nb
; ++i
) {
3872 MemoryRegionSection
*s
= d
->map
.sections
+ i
;
3873 const char *names
[] = { " [unassigned]", " [not dirty]",
3874 " [ROM]", " [watch]" };
3876 mon(f
, " #%d @" TARGET_FMT_plx
".." TARGET_FMT_plx
" %s%s%s%s%s",
3878 s
->offset_within_address_space
,
3879 s
->offset_within_address_space
+ MR_SIZE(s
->mr
->size
),
3880 s
->mr
->name
? s
->mr
->name
: "(noname)",
3881 i
< ARRAY_SIZE(names
) ? names
[i
] : "",
3882 s
->mr
== root
? " [ROOT]" : "",
3883 s
== d
->mru_section
? " [MRU]" : "",
3884 s
->mr
->is_iommu
? " [iommu]" : "");
3887 mon(f
, " alias=%s", s
->mr
->alias
->name
?
3888 s
->mr
->alias
->name
: "noname");
3893 mon(f
, " Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3894 P_L2_BITS
, P_L2_LEVELS
, d
->phys_map
.ptr
, d
->phys_map
.skip
);
3895 for (i
= 0; i
< d
->map
.nodes_nb
; ++i
) {
3898 Node
*n
= d
->map
.nodes
+ i
;
3900 mon(f
, " [%d]\n", i
);
3902 for (j
= 0, jprev
= 0, prev
= *n
[0]; j
< ARRAY_SIZE(*n
); ++j
) {
3903 PhysPageEntry
*pe
= *n
+ j
;
3905 if (pe
->ptr
== prev
.ptr
&& pe
->skip
== prev
.skip
) {
3909 mtree_print_phys_entries(mon
, f
, jprev
, j
, prev
.skip
, prev
.ptr
);
3915 if (jprev
!= ARRAY_SIZE(*n
)) {
3916 mtree_print_phys_entries(mon
, f
, jprev
, j
, prev
.skip
, prev
.ptr
);