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 * address_space_translate_iommu - translate an address through an IOMMU
466 * memory region and then through the target address space.
468 * @iommu_mr: the IOMMU memory region that we start the translation from
469 * @addr: the address to be translated through the MMU
470 * @xlat: the translated address offset within the destination memory region.
471 * It cannot be %NULL.
472 * @plen_out: valid read/write length of the translated address. It
474 * @page_mask_out: page mask for the translated address. This
475 * should only be meaningful for IOMMU translated
476 * addresses, since there may be huge pages that this bit
477 * would tell. It can be %NULL if we don't care about it.
478 * @is_write: whether the translation operation is for write
479 * @is_mmio: whether this can be MMIO, set true if it can
480 * @target_as: the address space targeted by the IOMMU
481 * @attrs: transaction attributes
483 * This function is called from RCU critical section. It is the common
484 * part of flatview_do_translate and address_space_translate_cached.
486 static MemoryRegionSection
address_space_translate_iommu(IOMMUMemoryRegion
*iommu_mr
,
489 hwaddr
*page_mask_out
,
492 AddressSpace
**target_as
,
495 MemoryRegionSection
*section
;
496 hwaddr page_mask
= (hwaddr
)-1;
500 IOMMUMemoryRegionClass
*imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
501 IOMMUTLBEntry iotlb
= imrc
->translate(iommu_mr
, addr
, is_write
?
502 IOMMU_WO
: IOMMU_RO
);
504 if (!(iotlb
.perm
& (1 << is_write
))) {
508 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
509 | (addr
& iotlb
.addr_mask
));
510 page_mask
&= iotlb
.addr_mask
;
511 *plen_out
= MIN(*plen_out
, (addr
| iotlb
.addr_mask
) - addr
+ 1);
512 *target_as
= iotlb
.target_as
;
514 section
= address_space_translate_internal(
515 address_space_to_dispatch(iotlb
.target_as
), addr
, xlat
,
518 iommu_mr
= memory_region_get_iommu(section
->mr
);
519 } while (unlikely(iommu_mr
));
522 *page_mask_out
= page_mask
;
527 return (MemoryRegionSection
) { .mr
= &io_mem_unassigned
};
531 * flatview_do_translate - translate an address in FlatView
533 * @fv: the flat view that we want to translate on
534 * @addr: the address to be translated in above address space
535 * @xlat: the translated address offset within memory region. It
537 * @plen_out: valid read/write length of the translated address. It
538 * can be @NULL when we don't care about it.
539 * @page_mask_out: page mask for the translated address. This
540 * should only be meaningful for IOMMU translated
541 * addresses, since there may be huge pages that this bit
542 * would tell. It can be @NULL if we don't care about it.
543 * @is_write: whether the translation operation is for write
544 * @is_mmio: whether this can be MMIO, set true if it can
545 * @target_as: the address space targeted by the IOMMU
546 * @attrs: memory transaction attributes
548 * This function is called from RCU critical section
550 static MemoryRegionSection
flatview_do_translate(FlatView
*fv
,
554 hwaddr
*page_mask_out
,
557 AddressSpace
**target_as
,
560 MemoryRegionSection
*section
;
561 IOMMUMemoryRegion
*iommu_mr
;
562 hwaddr plen
= (hwaddr
)(-1);
568 section
= address_space_translate_internal(
569 flatview_to_dispatch(fv
), addr
, xlat
,
572 iommu_mr
= memory_region_get_iommu(section
->mr
);
573 if (unlikely(iommu_mr
)) {
574 return address_space_translate_iommu(iommu_mr
, xlat
,
575 plen_out
, page_mask_out
,
580 /* Not behind an IOMMU, use default page size. */
581 *page_mask_out
= ~TARGET_PAGE_MASK
;
587 /* Called from RCU critical section */
588 IOMMUTLBEntry
address_space_get_iotlb_entry(AddressSpace
*as
, hwaddr addr
,
589 bool is_write
, MemTxAttrs attrs
)
591 MemoryRegionSection section
;
592 hwaddr xlat
, page_mask
;
595 * This can never be MMIO, and we don't really care about plen,
598 section
= flatview_do_translate(address_space_to_flatview(as
), addr
, &xlat
,
599 NULL
, &page_mask
, is_write
, false, &as
,
602 /* Illegal translation */
603 if (section
.mr
== &io_mem_unassigned
) {
607 /* Convert memory region offset into address space offset */
608 xlat
+= section
.offset_within_address_space
-
609 section
.offset_within_region
;
611 return (IOMMUTLBEntry
) {
613 .iova
= addr
& ~page_mask
,
614 .translated_addr
= xlat
& ~page_mask
,
615 .addr_mask
= page_mask
,
616 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
621 return (IOMMUTLBEntry
) {0};
624 /* Called from RCU critical section */
625 MemoryRegion
*flatview_translate(FlatView
*fv
, hwaddr addr
, hwaddr
*xlat
,
626 hwaddr
*plen
, bool is_write
,
630 MemoryRegionSection section
;
631 AddressSpace
*as
= NULL
;
633 /* This can be MMIO, so setup MMIO bit. */
634 section
= flatview_do_translate(fv
, addr
, xlat
, plen
, NULL
,
635 is_write
, true, &as
, attrs
);
638 if (xen_enabled() && memory_access_is_direct(mr
, is_write
)) {
639 hwaddr page
= ((addr
& TARGET_PAGE_MASK
) + TARGET_PAGE_SIZE
) - addr
;
640 *plen
= MIN(page
, *plen
);
646 /* Called from RCU critical section */
647 MemoryRegionSection
*
648 address_space_translate_for_iotlb(CPUState
*cpu
, int asidx
, hwaddr addr
,
649 hwaddr
*xlat
, hwaddr
*plen
)
651 MemoryRegionSection
*section
;
652 AddressSpaceDispatch
*d
= atomic_rcu_read(&cpu
->cpu_ases
[asidx
].memory_dispatch
);
654 section
= address_space_translate_internal(d
, addr
, xlat
, plen
, false);
656 assert(!memory_region_is_iommu(section
->mr
));
661 #if !defined(CONFIG_USER_ONLY)
663 static int cpu_common_post_load(void *opaque
, int version_id
)
665 CPUState
*cpu
= opaque
;
667 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
668 version_id is increased. */
669 cpu
->interrupt_request
&= ~0x01;
672 /* loadvm has just updated the content of RAM, bypassing the
673 * usual mechanisms that ensure we flush TBs for writes to
674 * memory we've translated code from. So we must flush all TBs,
675 * which will now be stale.
682 static int cpu_common_pre_load(void *opaque
)
684 CPUState
*cpu
= opaque
;
686 cpu
->exception_index
= -1;
691 static bool cpu_common_exception_index_needed(void *opaque
)
693 CPUState
*cpu
= opaque
;
695 return tcg_enabled() && cpu
->exception_index
!= -1;
698 static const VMStateDescription vmstate_cpu_common_exception_index
= {
699 .name
= "cpu_common/exception_index",
701 .minimum_version_id
= 1,
702 .needed
= cpu_common_exception_index_needed
,
703 .fields
= (VMStateField
[]) {
704 VMSTATE_INT32(exception_index
, CPUState
),
705 VMSTATE_END_OF_LIST()
709 static bool cpu_common_crash_occurred_needed(void *opaque
)
711 CPUState
*cpu
= opaque
;
713 return cpu
->crash_occurred
;
716 static const VMStateDescription vmstate_cpu_common_crash_occurred
= {
717 .name
= "cpu_common/crash_occurred",
719 .minimum_version_id
= 1,
720 .needed
= cpu_common_crash_occurred_needed
,
721 .fields
= (VMStateField
[]) {
722 VMSTATE_BOOL(crash_occurred
, CPUState
),
723 VMSTATE_END_OF_LIST()
727 const VMStateDescription vmstate_cpu_common
= {
728 .name
= "cpu_common",
730 .minimum_version_id
= 1,
731 .pre_load
= cpu_common_pre_load
,
732 .post_load
= cpu_common_post_load
,
733 .fields
= (VMStateField
[]) {
734 VMSTATE_UINT32(halted
, CPUState
),
735 VMSTATE_UINT32(interrupt_request
, CPUState
),
736 VMSTATE_END_OF_LIST()
738 .subsections
= (const VMStateDescription
*[]) {
739 &vmstate_cpu_common_exception_index
,
740 &vmstate_cpu_common_crash_occurred
,
747 CPUState
*qemu_get_cpu(int index
)
752 if (cpu
->cpu_index
== index
) {
760 #if !defined(CONFIG_USER_ONLY)
761 void cpu_address_space_init(CPUState
*cpu
, int asidx
,
762 const char *prefix
, MemoryRegion
*mr
)
764 CPUAddressSpace
*newas
;
765 AddressSpace
*as
= g_new0(AddressSpace
, 1);
769 as_name
= g_strdup_printf("%s-%d", prefix
, cpu
->cpu_index
);
770 address_space_init(as
, mr
, as_name
);
773 /* Target code should have set num_ases before calling us */
774 assert(asidx
< cpu
->num_ases
);
777 /* address space 0 gets the convenience alias */
781 /* KVM cannot currently support multiple address spaces. */
782 assert(asidx
== 0 || !kvm_enabled());
784 if (!cpu
->cpu_ases
) {
785 cpu
->cpu_ases
= g_new0(CPUAddressSpace
, cpu
->num_ases
);
788 newas
= &cpu
->cpu_ases
[asidx
];
792 newas
->tcg_as_listener
.commit
= tcg_commit
;
793 memory_listener_register(&newas
->tcg_as_listener
, as
);
797 AddressSpace
*cpu_get_address_space(CPUState
*cpu
, int asidx
)
799 /* Return the AddressSpace corresponding to the specified index */
800 return cpu
->cpu_ases
[asidx
].as
;
804 void cpu_exec_unrealizefn(CPUState
*cpu
)
806 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
808 cpu_list_remove(cpu
);
810 if (cc
->vmsd
!= NULL
) {
811 vmstate_unregister(NULL
, cc
->vmsd
, cpu
);
813 if (qdev_get_vmsd(DEVICE(cpu
)) == NULL
) {
814 vmstate_unregister(NULL
, &vmstate_cpu_common
, cpu
);
818 Property cpu_common_props
[] = {
819 #ifndef CONFIG_USER_ONLY
820 /* Create a memory property for softmmu CPU object,
821 * so users can wire up its memory. (This can't go in qom/cpu.c
822 * because that file is compiled only once for both user-mode
823 * and system builds.) The default if no link is set up is to use
824 * the system address space.
826 DEFINE_PROP_LINK("memory", CPUState
, memory
, TYPE_MEMORY_REGION
,
829 DEFINE_PROP_END_OF_LIST(),
832 void cpu_exec_initfn(CPUState
*cpu
)
837 #ifndef CONFIG_USER_ONLY
838 cpu
->thread_id
= qemu_get_thread_id();
839 cpu
->memory
= system_memory
;
840 object_ref(OBJECT(cpu
->memory
));
844 void cpu_exec_realizefn(CPUState
*cpu
, Error
**errp
)
846 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
847 static bool tcg_target_initialized
;
851 if (tcg_enabled() && !tcg_target_initialized
) {
852 tcg_target_initialized
= true;
853 cc
->tcg_initialize();
856 #ifndef CONFIG_USER_ONLY
857 if (qdev_get_vmsd(DEVICE(cpu
)) == NULL
) {
858 vmstate_register(NULL
, cpu
->cpu_index
, &vmstate_cpu_common
, cpu
);
860 if (cc
->vmsd
!= NULL
) {
861 vmstate_register(NULL
, cpu
->cpu_index
, cc
->vmsd
, cpu
);
866 const char *parse_cpu_model(const char *cpu_model
)
870 gchar
**model_pieces
;
871 const char *cpu_type
;
873 model_pieces
= g_strsplit(cpu_model
, ",", 2);
875 oc
= cpu_class_by_name(CPU_RESOLVING_TYPE
, model_pieces
[0]);
877 error_report("unable to find CPU model '%s'", model_pieces
[0]);
878 g_strfreev(model_pieces
);
882 cpu_type
= object_class_get_name(oc
);
884 cc
->parse_features(cpu_type
, model_pieces
[1], &error_fatal
);
885 g_strfreev(model_pieces
);
889 #if defined(CONFIG_USER_ONLY)
890 static void breakpoint_invalidate(CPUState
*cpu
, target_ulong pc
)
894 tb_invalidate_phys_page_range(pc
, pc
+ 1, 0);
899 static void breakpoint_invalidate(CPUState
*cpu
, target_ulong pc
)
902 hwaddr phys
= cpu_get_phys_page_attrs_debug(cpu
, pc
, &attrs
);
903 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
905 /* Locks grabbed by tb_invalidate_phys_addr */
906 tb_invalidate_phys_addr(cpu
->cpu_ases
[asidx
].as
,
907 phys
| (pc
& ~TARGET_PAGE_MASK
), attrs
);
912 #if defined(CONFIG_USER_ONLY)
913 void cpu_watchpoint_remove_all(CPUState
*cpu
, int mask
)
918 int cpu_watchpoint_remove(CPUState
*cpu
, vaddr addr
, vaddr len
,
924 void cpu_watchpoint_remove_by_ref(CPUState
*cpu
, CPUWatchpoint
*watchpoint
)
928 int cpu_watchpoint_insert(CPUState
*cpu
, vaddr addr
, vaddr len
,
929 int flags
, CPUWatchpoint
**watchpoint
)
934 /* Add a watchpoint. */
935 int cpu_watchpoint_insert(CPUState
*cpu
, vaddr addr
, vaddr len
,
936 int flags
, CPUWatchpoint
**watchpoint
)
940 /* forbid ranges which are empty or run off the end of the address space */
941 if (len
== 0 || (addr
+ len
- 1) < addr
) {
942 error_report("tried to set invalid watchpoint at %"
943 VADDR_PRIx
", len=%" VADDR_PRIu
, addr
, len
);
946 wp
= g_malloc(sizeof(*wp
));
952 /* keep all GDB-injected watchpoints in front */
953 if (flags
& BP_GDB
) {
954 QTAILQ_INSERT_HEAD(&cpu
->watchpoints
, wp
, entry
);
956 QTAILQ_INSERT_TAIL(&cpu
->watchpoints
, wp
, entry
);
959 tlb_flush_page(cpu
, addr
);
966 /* Remove a specific watchpoint. */
967 int cpu_watchpoint_remove(CPUState
*cpu
, vaddr addr
, vaddr len
,
972 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
973 if (addr
== wp
->vaddr
&& len
== wp
->len
974 && flags
== (wp
->flags
& ~BP_WATCHPOINT_HIT
)) {
975 cpu_watchpoint_remove_by_ref(cpu
, wp
);
982 /* Remove a specific watchpoint by reference. */
983 void cpu_watchpoint_remove_by_ref(CPUState
*cpu
, CPUWatchpoint
*watchpoint
)
985 QTAILQ_REMOVE(&cpu
->watchpoints
, watchpoint
, entry
);
987 tlb_flush_page(cpu
, watchpoint
->vaddr
);
992 /* Remove all matching watchpoints. */
993 void cpu_watchpoint_remove_all(CPUState
*cpu
, int mask
)
995 CPUWatchpoint
*wp
, *next
;
997 QTAILQ_FOREACH_SAFE(wp
, &cpu
->watchpoints
, entry
, next
) {
998 if (wp
->flags
& mask
) {
999 cpu_watchpoint_remove_by_ref(cpu
, wp
);
1004 /* Return true if this watchpoint address matches the specified
1005 * access (ie the address range covered by the watchpoint overlaps
1006 * partially or completely with the address range covered by the
1009 static inline bool cpu_watchpoint_address_matches(CPUWatchpoint
*wp
,
1013 /* We know the lengths are non-zero, but a little caution is
1014 * required to avoid errors in the case where the range ends
1015 * exactly at the top of the address space and so addr + len
1016 * wraps round to zero.
1018 vaddr wpend
= wp
->vaddr
+ wp
->len
- 1;
1019 vaddr addrend
= addr
+ len
- 1;
1021 return !(addr
> wpend
|| wp
->vaddr
> addrend
);
1026 /* Add a breakpoint. */
1027 int cpu_breakpoint_insert(CPUState
*cpu
, vaddr pc
, int flags
,
1028 CPUBreakpoint
**breakpoint
)
1032 bp
= g_malloc(sizeof(*bp
));
1037 /* keep all GDB-injected breakpoints in front */
1038 if (flags
& BP_GDB
) {
1039 QTAILQ_INSERT_HEAD(&cpu
->breakpoints
, bp
, entry
);
1041 QTAILQ_INSERT_TAIL(&cpu
->breakpoints
, bp
, entry
);
1044 breakpoint_invalidate(cpu
, pc
);
1052 /* Remove a specific breakpoint. */
1053 int cpu_breakpoint_remove(CPUState
*cpu
, vaddr pc
, int flags
)
1057 QTAILQ_FOREACH(bp
, &cpu
->breakpoints
, entry
) {
1058 if (bp
->pc
== pc
&& bp
->flags
== flags
) {
1059 cpu_breakpoint_remove_by_ref(cpu
, bp
);
1066 /* Remove a specific breakpoint by reference. */
1067 void cpu_breakpoint_remove_by_ref(CPUState
*cpu
, CPUBreakpoint
*breakpoint
)
1069 QTAILQ_REMOVE(&cpu
->breakpoints
, breakpoint
, entry
);
1071 breakpoint_invalidate(cpu
, breakpoint
->pc
);
1076 /* Remove all matching breakpoints. */
1077 void cpu_breakpoint_remove_all(CPUState
*cpu
, int mask
)
1079 CPUBreakpoint
*bp
, *next
;
1081 QTAILQ_FOREACH_SAFE(bp
, &cpu
->breakpoints
, entry
, next
) {
1082 if (bp
->flags
& mask
) {
1083 cpu_breakpoint_remove_by_ref(cpu
, bp
);
1088 /* enable or disable single step mode. EXCP_DEBUG is returned by the
1089 CPU loop after each instruction */
1090 void cpu_single_step(CPUState
*cpu
, int enabled
)
1092 if (cpu
->singlestep_enabled
!= enabled
) {
1093 cpu
->singlestep_enabled
= enabled
;
1094 if (kvm_enabled()) {
1095 kvm_update_guest_debug(cpu
, 0);
1097 /* must flush all the translated code to avoid inconsistencies */
1098 /* XXX: only flush what is necessary */
1104 void cpu_abort(CPUState
*cpu
, const char *fmt
, ...)
1111 fprintf(stderr
, "qemu: fatal: ");
1112 vfprintf(stderr
, fmt
, ap
);
1113 fprintf(stderr
, "\n");
1114 cpu_dump_state(cpu
, stderr
, fprintf
, CPU_DUMP_FPU
| CPU_DUMP_CCOP
);
1115 if (qemu_log_separate()) {
1117 qemu_log("qemu: fatal: ");
1118 qemu_log_vprintf(fmt
, ap2
);
1120 log_cpu_state(cpu
, CPU_DUMP_FPU
| CPU_DUMP_CCOP
);
1128 #if defined(CONFIG_USER_ONLY)
1130 struct sigaction act
;
1131 sigfillset(&act
.sa_mask
);
1132 act
.sa_handler
= SIG_DFL
;
1134 sigaction(SIGABRT
, &act
, NULL
);
1140 #if !defined(CONFIG_USER_ONLY)
1141 /* Called from RCU critical section */
1142 static RAMBlock
*qemu_get_ram_block(ram_addr_t addr
)
1146 block
= atomic_rcu_read(&ram_list
.mru_block
);
1147 if (block
&& addr
- block
->offset
< block
->max_length
) {
1150 RAMBLOCK_FOREACH(block
) {
1151 if (addr
- block
->offset
< block
->max_length
) {
1156 fprintf(stderr
, "Bad ram offset %" PRIx64
"\n", (uint64_t)addr
);
1160 /* It is safe to write mru_block outside the iothread lock. This
1165 * xxx removed from list
1169 * call_rcu(reclaim_ramblock, xxx);
1172 * atomic_rcu_set is not needed here. The block was already published
1173 * when it was placed into the list. Here we're just making an extra
1174 * copy of the pointer.
1176 ram_list
.mru_block
= block
;
1180 static void tlb_reset_dirty_range_all(ram_addr_t start
, ram_addr_t length
)
1187 end
= TARGET_PAGE_ALIGN(start
+ length
);
1188 start
&= TARGET_PAGE_MASK
;
1191 block
= qemu_get_ram_block(start
);
1192 assert(block
== qemu_get_ram_block(end
- 1));
1193 start1
= (uintptr_t)ramblock_ptr(block
, start
- block
->offset
);
1195 tlb_reset_dirty(cpu
, start1
, length
);
1200 /* Note: start and end must be within the same ram block. */
1201 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start
,
1205 DirtyMemoryBlocks
*blocks
;
1206 unsigned long end
, page
;
1213 end
= TARGET_PAGE_ALIGN(start
+ length
) >> TARGET_PAGE_BITS
;
1214 page
= start
>> TARGET_PAGE_BITS
;
1218 blocks
= atomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1220 while (page
< end
) {
1221 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1222 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1223 unsigned long num
= MIN(end
- page
, DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1225 dirty
|= bitmap_test_and_clear_atomic(blocks
->blocks
[idx
],
1232 if (dirty
&& tcg_enabled()) {
1233 tlb_reset_dirty_range_all(start
, length
);
1239 DirtyBitmapSnapshot
*cpu_physical_memory_snapshot_and_clear_dirty
1240 (ram_addr_t start
, ram_addr_t length
, unsigned client
)
1242 DirtyMemoryBlocks
*blocks
;
1243 unsigned long align
= 1UL << (TARGET_PAGE_BITS
+ BITS_PER_LEVEL
);
1244 ram_addr_t first
= QEMU_ALIGN_DOWN(start
, align
);
1245 ram_addr_t last
= QEMU_ALIGN_UP(start
+ length
, align
);
1246 DirtyBitmapSnapshot
*snap
;
1247 unsigned long page
, end
, dest
;
1249 snap
= g_malloc0(sizeof(*snap
) +
1250 ((last
- first
) >> (TARGET_PAGE_BITS
+ 3)));
1251 snap
->start
= first
;
1254 page
= first
>> TARGET_PAGE_BITS
;
1255 end
= last
>> TARGET_PAGE_BITS
;
1260 blocks
= atomic_rcu_read(&ram_list
.dirty_memory
[client
]);
1262 while (page
< end
) {
1263 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
1264 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
1265 unsigned long num
= MIN(end
- page
, DIRTY_MEMORY_BLOCK_SIZE
- offset
);
1267 assert(QEMU_IS_ALIGNED(offset
, (1 << BITS_PER_LEVEL
)));
1268 assert(QEMU_IS_ALIGNED(num
, (1 << BITS_PER_LEVEL
)));
1269 offset
>>= BITS_PER_LEVEL
;
1271 bitmap_copy_and_clear_atomic(snap
->dirty
+ dest
,
1272 blocks
->blocks
[idx
] + offset
,
1275 dest
+= num
>> BITS_PER_LEVEL
;
1280 if (tcg_enabled()) {
1281 tlb_reset_dirty_range_all(start
, length
);
1287 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot
*snap
,
1291 unsigned long page
, end
;
1293 assert(start
>= snap
->start
);
1294 assert(start
+ length
<= snap
->end
);
1296 end
= TARGET_PAGE_ALIGN(start
+ length
- snap
->start
) >> TARGET_PAGE_BITS
;
1297 page
= (start
- snap
->start
) >> TARGET_PAGE_BITS
;
1299 while (page
< end
) {
1300 if (test_bit(page
, snap
->dirty
)) {
1308 /* Called from RCU critical section */
1309 hwaddr
memory_region_section_get_iotlb(CPUState
*cpu
,
1310 MemoryRegionSection
*section
,
1312 hwaddr paddr
, hwaddr xlat
,
1314 target_ulong
*address
)
1319 if (memory_region_is_ram(section
->mr
)) {
1321 iotlb
= memory_region_get_ram_addr(section
->mr
) + xlat
;
1322 if (!section
->readonly
) {
1323 iotlb
|= PHYS_SECTION_NOTDIRTY
;
1325 iotlb
|= PHYS_SECTION_ROM
;
1328 AddressSpaceDispatch
*d
;
1330 d
= flatview_to_dispatch(section
->fv
);
1331 iotlb
= section
- d
->map
.sections
;
1335 /* Make accesses to pages with watchpoints go via the
1336 watchpoint trap routines. */
1337 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
1338 if (cpu_watchpoint_address_matches(wp
, vaddr
, TARGET_PAGE_SIZE
)) {
1339 /* Avoid trapping reads of pages with a write breakpoint. */
1340 if ((prot
& PAGE_WRITE
) || (wp
->flags
& BP_MEM_READ
)) {
1341 iotlb
= PHYS_SECTION_WATCH
+ paddr
;
1342 *address
|= TLB_MMIO
;
1350 #endif /* defined(CONFIG_USER_ONLY) */
1352 #if !defined(CONFIG_USER_ONLY)
1354 static int subpage_register (subpage_t
*mmio
, uint32_t start
, uint32_t end
,
1356 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
);
1358 static void *(*phys_mem_alloc
)(size_t size
, uint64_t *align
, bool shared
) =
1359 qemu_anon_ram_alloc
;
1362 * Set a custom physical guest memory alloator.
1363 * Accelerators with unusual needs may need this. Hopefully, we can
1364 * get rid of it eventually.
1366 void phys_mem_set_alloc(void *(*alloc
)(size_t, uint64_t *align
, bool shared
))
1368 phys_mem_alloc
= alloc
;
1371 static uint16_t phys_section_add(PhysPageMap
*map
,
1372 MemoryRegionSection
*section
)
1374 /* The physical section number is ORed with a page-aligned
1375 * pointer to produce the iotlb entries. Thus it should
1376 * never overflow into the page-aligned value.
1378 assert(map
->sections_nb
< TARGET_PAGE_SIZE
);
1380 if (map
->sections_nb
== map
->sections_nb_alloc
) {
1381 map
->sections_nb_alloc
= MAX(map
->sections_nb_alloc
* 2, 16);
1382 map
->sections
= g_renew(MemoryRegionSection
, map
->sections
,
1383 map
->sections_nb_alloc
);
1385 map
->sections
[map
->sections_nb
] = *section
;
1386 memory_region_ref(section
->mr
);
1387 return map
->sections_nb
++;
1390 static void phys_section_destroy(MemoryRegion
*mr
)
1392 bool have_sub_page
= mr
->subpage
;
1394 memory_region_unref(mr
);
1396 if (have_sub_page
) {
1397 subpage_t
*subpage
= container_of(mr
, subpage_t
, iomem
);
1398 object_unref(OBJECT(&subpage
->iomem
));
1403 static void phys_sections_free(PhysPageMap
*map
)
1405 while (map
->sections_nb
> 0) {
1406 MemoryRegionSection
*section
= &map
->sections
[--map
->sections_nb
];
1407 phys_section_destroy(section
->mr
);
1409 g_free(map
->sections
);
1413 static void register_subpage(FlatView
*fv
, MemoryRegionSection
*section
)
1415 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1417 hwaddr base
= section
->offset_within_address_space
1419 MemoryRegionSection
*existing
= phys_page_find(d
, base
);
1420 MemoryRegionSection subsection
= {
1421 .offset_within_address_space
= base
,
1422 .size
= int128_make64(TARGET_PAGE_SIZE
),
1426 assert(existing
->mr
->subpage
|| existing
->mr
== &io_mem_unassigned
);
1428 if (!(existing
->mr
->subpage
)) {
1429 subpage
= subpage_init(fv
, base
);
1431 subsection
.mr
= &subpage
->iomem
;
1432 phys_page_set(d
, base
>> TARGET_PAGE_BITS
, 1,
1433 phys_section_add(&d
->map
, &subsection
));
1435 subpage
= container_of(existing
->mr
, subpage_t
, iomem
);
1437 start
= section
->offset_within_address_space
& ~TARGET_PAGE_MASK
;
1438 end
= start
+ int128_get64(section
->size
) - 1;
1439 subpage_register(subpage
, start
, end
,
1440 phys_section_add(&d
->map
, section
));
1444 static void register_multipage(FlatView
*fv
,
1445 MemoryRegionSection
*section
)
1447 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1448 hwaddr start_addr
= section
->offset_within_address_space
;
1449 uint16_t section_index
= phys_section_add(&d
->map
, section
);
1450 uint64_t num_pages
= int128_get64(int128_rshift(section
->size
,
1454 phys_page_set(d
, start_addr
>> TARGET_PAGE_BITS
, num_pages
, section_index
);
1457 void flatview_add_to_dispatch(FlatView
*fv
, MemoryRegionSection
*section
)
1459 MemoryRegionSection now
= *section
, remain
= *section
;
1460 Int128 page_size
= int128_make64(TARGET_PAGE_SIZE
);
1462 if (now
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1463 uint64_t left
= TARGET_PAGE_ALIGN(now
.offset_within_address_space
)
1464 - now
.offset_within_address_space
;
1466 now
.size
= int128_min(int128_make64(left
), now
.size
);
1467 register_subpage(fv
, &now
);
1469 now
.size
= int128_zero();
1471 while (int128_ne(remain
.size
, now
.size
)) {
1472 remain
.size
= int128_sub(remain
.size
, now
.size
);
1473 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1474 remain
.offset_within_region
+= int128_get64(now
.size
);
1476 if (int128_lt(remain
.size
, page_size
)) {
1477 register_subpage(fv
, &now
);
1478 } else if (remain
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1479 now
.size
= page_size
;
1480 register_subpage(fv
, &now
);
1482 now
.size
= int128_and(now
.size
, int128_neg(page_size
));
1483 register_multipage(fv
, &now
);
1488 void qemu_flush_coalesced_mmio_buffer(void)
1491 kvm_flush_coalesced_mmio_buffer();
1494 void qemu_mutex_lock_ramlist(void)
1496 qemu_mutex_lock(&ram_list
.mutex
);
1499 void qemu_mutex_unlock_ramlist(void)
1501 qemu_mutex_unlock(&ram_list
.mutex
);
1504 void ram_block_dump(Monitor
*mon
)
1510 monitor_printf(mon
, "%24s %8s %18s %18s %18s\n",
1511 "Block Name", "PSize", "Offset", "Used", "Total");
1512 RAMBLOCK_FOREACH(block
) {
1513 psize
= size_to_str(block
->page_size
);
1514 monitor_printf(mon
, "%24s %8s 0x%016" PRIx64
" 0x%016" PRIx64
1515 " 0x%016" PRIx64
"\n", block
->idstr
, psize
,
1516 (uint64_t)block
->offset
,
1517 (uint64_t)block
->used_length
,
1518 (uint64_t)block
->max_length
);
1526 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1527 * may or may not name the same files / on the same filesystem now as
1528 * when we actually open and map them. Iterate over the file
1529 * descriptors instead, and use qemu_fd_getpagesize().
1531 static int find_max_supported_pagesize(Object
*obj
, void *opaque
)
1533 long *hpsize_min
= opaque
;
1535 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1536 long hpsize
= host_memory_backend_pagesize(MEMORY_BACKEND(obj
));
1538 if (hpsize
< *hpsize_min
) {
1539 *hpsize_min
= hpsize
;
1546 long qemu_getrampagesize(void)
1548 long hpsize
= LONG_MAX
;
1549 long mainrampagesize
;
1550 Object
*memdev_root
;
1552 mainrampagesize
= qemu_mempath_getpagesize(mem_path
);
1554 /* it's possible we have memory-backend objects with
1555 * hugepage-backed RAM. these may get mapped into system
1556 * address space via -numa parameters or memory hotplug
1557 * hooks. we want to take these into account, but we
1558 * also want to make sure these supported hugepage
1559 * sizes are applicable across the entire range of memory
1560 * we may boot from, so we take the min across all
1561 * backends, and assume normal pages in cases where a
1562 * backend isn't backed by hugepages.
1564 memdev_root
= object_resolve_path("/objects", NULL
);
1566 object_child_foreach(memdev_root
, find_max_supported_pagesize
, &hpsize
);
1568 if (hpsize
== LONG_MAX
) {
1569 /* No additional memory regions found ==> Report main RAM page size */
1570 return mainrampagesize
;
1573 /* If NUMA is disabled or the NUMA nodes are not backed with a
1574 * memory-backend, then there is at least one node using "normal" RAM,
1575 * so if its page size is smaller we have got to report that size instead.
1577 if (hpsize
> mainrampagesize
&&
1578 (nb_numa_nodes
== 0 || numa_info
[0].node_memdev
== NULL
)) {
1581 error_report("Huge page support disabled (n/a for main memory).");
1584 return mainrampagesize
;
1590 long qemu_getrampagesize(void)
1592 return getpagesize();
1597 static int64_t get_file_size(int fd
)
1599 int64_t size
= lseek(fd
, 0, SEEK_END
);
1606 static int file_ram_open(const char *path
,
1607 const char *region_name
,
1612 char *sanitized_name
;
1618 fd
= open(path
, O_RDWR
);
1620 /* @path names an existing file, use it */
1623 if (errno
== ENOENT
) {
1624 /* @path names a file that doesn't exist, create it */
1625 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0644);
1630 } else if (errno
== EISDIR
) {
1631 /* @path names a directory, create a file there */
1632 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1633 sanitized_name
= g_strdup(region_name
);
1634 for (c
= sanitized_name
; *c
!= '\0'; c
++) {
1640 filename
= g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path
,
1642 g_free(sanitized_name
);
1644 fd
= mkstemp(filename
);
1652 if (errno
!= EEXIST
&& errno
!= EINTR
) {
1653 error_setg_errno(errp
, errno
,
1654 "can't open backing store %s for guest RAM",
1659 * Try again on EINTR and EEXIST. The latter happens when
1660 * something else creates the file between our two open().
1667 static void *file_ram_alloc(RAMBlock
*block
,
1675 block
->page_size
= qemu_fd_getpagesize(fd
);
1676 if (block
->mr
->align
% block
->page_size
) {
1677 error_setg(errp
, "alignment 0x%" PRIx64
1678 " must be multiples of page size 0x%zx",
1679 block
->mr
->align
, block
->page_size
);
1682 block
->mr
->align
= MAX(block
->page_size
, block
->mr
->align
);
1683 #if defined(__s390x__)
1684 if (kvm_enabled()) {
1685 block
->mr
->align
= MAX(block
->mr
->align
, QEMU_VMALLOC_ALIGN
);
1689 if (memory
< block
->page_size
) {
1690 error_setg(errp
, "memory size 0x" RAM_ADDR_FMT
" must be equal to "
1691 "or larger than page size 0x%zx",
1692 memory
, block
->page_size
);
1696 memory
= ROUND_UP(memory
, block
->page_size
);
1699 * ftruncate is not supported by hugetlbfs in older
1700 * hosts, so don't bother bailing out on errors.
1701 * If anything goes wrong with it under other filesystems,
1704 * Do not truncate the non-empty backend file to avoid corrupting
1705 * the existing data in the file. Disabling shrinking is not
1706 * enough. For example, the current vNVDIMM implementation stores
1707 * the guest NVDIMM labels at the end of the backend file. If the
1708 * backend file is later extended, QEMU will not be able to find
1709 * those labels. Therefore, extending the non-empty backend file
1710 * is disabled as well.
1712 if (truncate
&& ftruncate(fd
, memory
)) {
1713 perror("ftruncate");
1716 area
= qemu_ram_mmap(fd
, memory
, block
->mr
->align
,
1717 block
->flags
& RAM_SHARED
);
1718 if (area
== MAP_FAILED
) {
1719 error_setg_errno(errp
, errno
,
1720 "unable to map backing store for guest RAM");
1725 os_mem_prealloc(fd
, area
, memory
, smp_cpus
, errp
);
1726 if (errp
&& *errp
) {
1727 qemu_ram_munmap(area
, memory
);
1737 /* Allocate space within the ram_addr_t space that governs the
1739 * Called with the ramlist lock held.
1741 static ram_addr_t
find_ram_offset(ram_addr_t size
)
1743 RAMBlock
*block
, *next_block
;
1744 ram_addr_t offset
= RAM_ADDR_MAX
, mingap
= RAM_ADDR_MAX
;
1746 assert(size
!= 0); /* it would hand out same offset multiple times */
1748 if (QLIST_EMPTY_RCU(&ram_list
.blocks
)) {
1752 RAMBLOCK_FOREACH(block
) {
1753 ram_addr_t candidate
, next
= RAM_ADDR_MAX
;
1755 /* Align blocks to start on a 'long' in the bitmap
1756 * which makes the bitmap sync'ing take the fast path.
1758 candidate
= block
->offset
+ block
->max_length
;
1759 candidate
= ROUND_UP(candidate
, BITS_PER_LONG
<< TARGET_PAGE_BITS
);
1761 /* Search for the closest following block
1764 RAMBLOCK_FOREACH(next_block
) {
1765 if (next_block
->offset
>= candidate
) {
1766 next
= MIN(next
, next_block
->offset
);
1770 /* If it fits remember our place and remember the size
1771 * of gap, but keep going so that we might find a smaller
1772 * gap to fill so avoiding fragmentation.
1774 if (next
- candidate
>= size
&& next
- candidate
< mingap
) {
1776 mingap
= next
- candidate
;
1779 trace_find_ram_offset_loop(size
, candidate
, offset
, next
, mingap
);
1782 if (offset
== RAM_ADDR_MAX
) {
1783 fprintf(stderr
, "Failed to find gap of requested size: %" PRIu64
"\n",
1788 trace_find_ram_offset(size
, offset
);
1793 unsigned long last_ram_page(void)
1796 ram_addr_t last
= 0;
1799 RAMBLOCK_FOREACH(block
) {
1800 last
= MAX(last
, block
->offset
+ block
->max_length
);
1803 return last
>> TARGET_PAGE_BITS
;
1806 static void qemu_ram_setup_dump(void *addr
, ram_addr_t size
)
1810 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1811 if (!machine_dump_guest_core(current_machine
)) {
1812 ret
= qemu_madvise(addr
, size
, QEMU_MADV_DONTDUMP
);
1814 perror("qemu_madvise");
1815 fprintf(stderr
, "madvise doesn't support MADV_DONTDUMP, "
1816 "but dump_guest_core=off specified\n");
1821 const char *qemu_ram_get_idstr(RAMBlock
*rb
)
1826 bool qemu_ram_is_shared(RAMBlock
*rb
)
1828 return rb
->flags
& RAM_SHARED
;
1831 /* Note: Only set at the start of postcopy */
1832 bool qemu_ram_is_uf_zeroable(RAMBlock
*rb
)
1834 return rb
->flags
& RAM_UF_ZEROPAGE
;
1837 void qemu_ram_set_uf_zeroable(RAMBlock
*rb
)
1839 rb
->flags
|= RAM_UF_ZEROPAGE
;
1842 /* Called with iothread lock held. */
1843 void qemu_ram_set_idstr(RAMBlock
*new_block
, const char *name
, DeviceState
*dev
)
1848 assert(!new_block
->idstr
[0]);
1851 char *id
= qdev_get_dev_path(dev
);
1853 snprintf(new_block
->idstr
, sizeof(new_block
->idstr
), "%s/", id
);
1857 pstrcat(new_block
->idstr
, sizeof(new_block
->idstr
), name
);
1860 RAMBLOCK_FOREACH(block
) {
1861 if (block
!= new_block
&&
1862 !strcmp(block
->idstr
, new_block
->idstr
)) {
1863 fprintf(stderr
, "RAMBlock \"%s\" already registered, abort!\n",
1871 /* Called with iothread lock held. */
1872 void qemu_ram_unset_idstr(RAMBlock
*block
)
1874 /* FIXME: arch_init.c assumes that this is not called throughout
1875 * migration. Ignore the problem since hot-unplug during migration
1876 * does not work anyway.
1879 memset(block
->idstr
, 0, sizeof(block
->idstr
));
1883 size_t qemu_ram_pagesize(RAMBlock
*rb
)
1885 return rb
->page_size
;
1888 /* Returns the largest size of page in use */
1889 size_t qemu_ram_pagesize_largest(void)
1894 RAMBLOCK_FOREACH(block
) {
1895 largest
= MAX(largest
, qemu_ram_pagesize(block
));
1901 static int memory_try_enable_merging(void *addr
, size_t len
)
1903 if (!machine_mem_merge(current_machine
)) {
1904 /* disabled by the user */
1908 return qemu_madvise(addr
, len
, QEMU_MADV_MERGEABLE
);
1911 /* Only legal before guest might have detected the memory size: e.g. on
1912 * incoming migration, or right after reset.
1914 * As memory core doesn't know how is memory accessed, it is up to
1915 * resize callback to update device state and/or add assertions to detect
1916 * misuse, if necessary.
1918 int qemu_ram_resize(RAMBlock
*block
, ram_addr_t newsize
, Error
**errp
)
1922 newsize
= HOST_PAGE_ALIGN(newsize
);
1924 if (block
->used_length
== newsize
) {
1928 if (!(block
->flags
& RAM_RESIZEABLE
)) {
1929 error_setg_errno(errp
, EINVAL
,
1930 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1931 " in != 0x" RAM_ADDR_FMT
, block
->idstr
,
1932 newsize
, block
->used_length
);
1936 if (block
->max_length
< newsize
) {
1937 error_setg_errno(errp
, EINVAL
,
1938 "Length too large: %s: 0x" RAM_ADDR_FMT
1939 " > 0x" RAM_ADDR_FMT
, block
->idstr
,
1940 newsize
, block
->max_length
);
1944 cpu_physical_memory_clear_dirty_range(block
->offset
, block
->used_length
);
1945 block
->used_length
= newsize
;
1946 cpu_physical_memory_set_dirty_range(block
->offset
, block
->used_length
,
1948 memory_region_set_size(block
->mr
, newsize
);
1949 if (block
->resized
) {
1950 block
->resized(block
->idstr
, newsize
, block
->host
);
1955 /* Called with ram_list.mutex held */
1956 static void dirty_memory_extend(ram_addr_t old_ram_size
,
1957 ram_addr_t new_ram_size
)
1959 ram_addr_t old_num_blocks
= DIV_ROUND_UP(old_ram_size
,
1960 DIRTY_MEMORY_BLOCK_SIZE
);
1961 ram_addr_t new_num_blocks
= DIV_ROUND_UP(new_ram_size
,
1962 DIRTY_MEMORY_BLOCK_SIZE
);
1965 /* Only need to extend if block count increased */
1966 if (new_num_blocks
<= old_num_blocks
) {
1970 for (i
= 0; i
< DIRTY_MEMORY_NUM
; i
++) {
1971 DirtyMemoryBlocks
*old_blocks
;
1972 DirtyMemoryBlocks
*new_blocks
;
1975 old_blocks
= atomic_rcu_read(&ram_list
.dirty_memory
[i
]);
1976 new_blocks
= g_malloc(sizeof(*new_blocks
) +
1977 sizeof(new_blocks
->blocks
[0]) * new_num_blocks
);
1979 if (old_num_blocks
) {
1980 memcpy(new_blocks
->blocks
, old_blocks
->blocks
,
1981 old_num_blocks
* sizeof(old_blocks
->blocks
[0]));
1984 for (j
= old_num_blocks
; j
< new_num_blocks
; j
++) {
1985 new_blocks
->blocks
[j
] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE
);
1988 atomic_rcu_set(&ram_list
.dirty_memory
[i
], new_blocks
);
1991 g_free_rcu(old_blocks
, rcu
);
1996 static void ram_block_add(RAMBlock
*new_block
, Error
**errp
, bool shared
)
1999 RAMBlock
*last_block
= NULL
;
2000 ram_addr_t old_ram_size
, new_ram_size
;
2003 old_ram_size
= last_ram_page();
2005 qemu_mutex_lock_ramlist();
2006 new_block
->offset
= find_ram_offset(new_block
->max_length
);
2008 if (!new_block
->host
) {
2009 if (xen_enabled()) {
2010 xen_ram_alloc(new_block
->offset
, new_block
->max_length
,
2011 new_block
->mr
, &err
);
2013 error_propagate(errp
, err
);
2014 qemu_mutex_unlock_ramlist();
2018 new_block
->host
= phys_mem_alloc(new_block
->max_length
,
2019 &new_block
->mr
->align
, shared
);
2020 if (!new_block
->host
) {
2021 error_setg_errno(errp
, errno
,
2022 "cannot set up guest memory '%s'",
2023 memory_region_name(new_block
->mr
));
2024 qemu_mutex_unlock_ramlist();
2027 memory_try_enable_merging(new_block
->host
, new_block
->max_length
);
2031 new_ram_size
= MAX(old_ram_size
,
2032 (new_block
->offset
+ new_block
->max_length
) >> TARGET_PAGE_BITS
);
2033 if (new_ram_size
> old_ram_size
) {
2034 dirty_memory_extend(old_ram_size
, new_ram_size
);
2036 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2037 * QLIST (which has an RCU-friendly variant) does not have insertion at
2038 * tail, so save the last element in last_block.
2040 RAMBLOCK_FOREACH(block
) {
2042 if (block
->max_length
< new_block
->max_length
) {
2047 QLIST_INSERT_BEFORE_RCU(block
, new_block
, next
);
2048 } else if (last_block
) {
2049 QLIST_INSERT_AFTER_RCU(last_block
, new_block
, next
);
2050 } else { /* list is empty */
2051 QLIST_INSERT_HEAD_RCU(&ram_list
.blocks
, new_block
, next
);
2053 ram_list
.mru_block
= NULL
;
2055 /* Write list before version */
2058 qemu_mutex_unlock_ramlist();
2060 cpu_physical_memory_set_dirty_range(new_block
->offset
,
2061 new_block
->used_length
,
2064 if (new_block
->host
) {
2065 qemu_ram_setup_dump(new_block
->host
, new_block
->max_length
);
2066 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_HUGEPAGE
);
2067 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
2068 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_DONTFORK
);
2069 ram_block_notify_add(new_block
->host
, new_block
->max_length
);
2074 RAMBlock
*qemu_ram_alloc_from_fd(ram_addr_t size
, MemoryRegion
*mr
,
2078 RAMBlock
*new_block
;
2079 Error
*local_err
= NULL
;
2082 if (xen_enabled()) {
2083 error_setg(errp
, "-mem-path not supported with Xen");
2087 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2089 "host lacks kvm mmu notifiers, -mem-path unsupported");
2093 if (phys_mem_alloc
!= qemu_anon_ram_alloc
) {
2095 * file_ram_alloc() needs to allocate just like
2096 * phys_mem_alloc, but we haven't bothered to provide
2100 "-mem-path not supported with this accelerator");
2104 size
= HOST_PAGE_ALIGN(size
);
2105 file_size
= get_file_size(fd
);
2106 if (file_size
> 0 && file_size
< size
) {
2107 error_setg(errp
, "backing store %s size 0x%" PRIx64
2108 " does not match 'size' option 0x" RAM_ADDR_FMT
,
2109 mem_path
, file_size
, size
);
2113 new_block
= g_malloc0(sizeof(*new_block
));
2115 new_block
->used_length
= size
;
2116 new_block
->max_length
= size
;
2117 new_block
->flags
= share
? RAM_SHARED
: 0;
2118 new_block
->host
= file_ram_alloc(new_block
, size
, fd
, !file_size
, errp
);
2119 if (!new_block
->host
) {
2124 ram_block_add(new_block
, &local_err
, share
);
2127 error_propagate(errp
, local_err
);
2135 RAMBlock
*qemu_ram_alloc_from_file(ram_addr_t size
, MemoryRegion
*mr
,
2136 bool share
, const char *mem_path
,
2143 fd
= file_ram_open(mem_path
, memory_region_name(mr
), &created
, errp
);
2148 block
= qemu_ram_alloc_from_fd(size
, mr
, share
, fd
, errp
);
2162 RAMBlock
*qemu_ram_alloc_internal(ram_addr_t size
, ram_addr_t max_size
,
2163 void (*resized
)(const char*,
2166 void *host
, bool resizeable
, bool share
,
2167 MemoryRegion
*mr
, Error
**errp
)
2169 RAMBlock
*new_block
;
2170 Error
*local_err
= NULL
;
2172 size
= HOST_PAGE_ALIGN(size
);
2173 max_size
= HOST_PAGE_ALIGN(max_size
);
2174 new_block
= g_malloc0(sizeof(*new_block
));
2176 new_block
->resized
= resized
;
2177 new_block
->used_length
= size
;
2178 new_block
->max_length
= max_size
;
2179 assert(max_size
>= size
);
2181 new_block
->page_size
= getpagesize();
2182 new_block
->host
= host
;
2184 new_block
->flags
|= RAM_PREALLOC
;
2187 new_block
->flags
|= RAM_RESIZEABLE
;
2189 ram_block_add(new_block
, &local_err
, share
);
2192 error_propagate(errp
, local_err
);
2198 RAMBlock
*qemu_ram_alloc_from_ptr(ram_addr_t size
, void *host
,
2199 MemoryRegion
*mr
, Error
**errp
)
2201 return qemu_ram_alloc_internal(size
, size
, NULL
, host
, false,
2205 RAMBlock
*qemu_ram_alloc(ram_addr_t size
, bool share
,
2206 MemoryRegion
*mr
, Error
**errp
)
2208 return qemu_ram_alloc_internal(size
, size
, NULL
, NULL
, false,
2212 RAMBlock
*qemu_ram_alloc_resizeable(ram_addr_t size
, ram_addr_t maxsz
,
2213 void (*resized
)(const char*,
2216 MemoryRegion
*mr
, Error
**errp
)
2218 return qemu_ram_alloc_internal(size
, maxsz
, resized
, NULL
, true,
2222 static void reclaim_ramblock(RAMBlock
*block
)
2224 if (block
->flags
& RAM_PREALLOC
) {
2226 } else if (xen_enabled()) {
2227 xen_invalidate_map_cache_entry(block
->host
);
2229 } else if (block
->fd
>= 0) {
2230 qemu_ram_munmap(block
->host
, block
->max_length
);
2234 qemu_anon_ram_free(block
->host
, block
->max_length
);
2239 void qemu_ram_free(RAMBlock
*block
)
2246 ram_block_notify_remove(block
->host
, block
->max_length
);
2249 qemu_mutex_lock_ramlist();
2250 QLIST_REMOVE_RCU(block
, next
);
2251 ram_list
.mru_block
= NULL
;
2252 /* Write list before version */
2255 call_rcu(block
, reclaim_ramblock
, rcu
);
2256 qemu_mutex_unlock_ramlist();
2260 void qemu_ram_remap(ram_addr_t addr
, ram_addr_t length
)
2267 RAMBLOCK_FOREACH(block
) {
2268 offset
= addr
- block
->offset
;
2269 if (offset
< block
->max_length
) {
2270 vaddr
= ramblock_ptr(block
, offset
);
2271 if (block
->flags
& RAM_PREALLOC
) {
2273 } else if (xen_enabled()) {
2277 if (block
->fd
>= 0) {
2278 flags
|= (block
->flags
& RAM_SHARED
?
2279 MAP_SHARED
: MAP_PRIVATE
);
2280 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2281 flags
, block
->fd
, offset
);
2284 * Remap needs to match alloc. Accelerators that
2285 * set phys_mem_alloc never remap. If they did,
2286 * we'd need a remap hook here.
2288 assert(phys_mem_alloc
== qemu_anon_ram_alloc
);
2290 flags
|= MAP_PRIVATE
| MAP_ANONYMOUS
;
2291 area
= mmap(vaddr
, length
, PROT_READ
| PROT_WRITE
,
2294 if (area
!= vaddr
) {
2295 error_report("Could not remap addr: "
2296 RAM_ADDR_FMT
"@" RAM_ADDR_FMT
"",
2300 memory_try_enable_merging(vaddr
, length
);
2301 qemu_ram_setup_dump(vaddr
, length
);
2306 #endif /* !_WIN32 */
2308 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2309 * This should not be used for general purpose DMA. Use address_space_map
2310 * or address_space_rw instead. For local memory (e.g. video ram) that the
2311 * device owns, use memory_region_get_ram_ptr.
2313 * Called within RCU critical section.
2315 void *qemu_map_ram_ptr(RAMBlock
*ram_block
, ram_addr_t addr
)
2317 RAMBlock
*block
= ram_block
;
2319 if (block
== NULL
) {
2320 block
= qemu_get_ram_block(addr
);
2321 addr
-= block
->offset
;
2324 if (xen_enabled() && block
->host
== NULL
) {
2325 /* We need to check if the requested address is in the RAM
2326 * because we don't want to map the entire memory in QEMU.
2327 * In that case just map until the end of the page.
2329 if (block
->offset
== 0) {
2330 return xen_map_cache(addr
, 0, 0, false);
2333 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, false);
2335 return ramblock_ptr(block
, addr
);
2338 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2339 * but takes a size argument.
2341 * Called within RCU critical section.
2343 static void *qemu_ram_ptr_length(RAMBlock
*ram_block
, ram_addr_t addr
,
2344 hwaddr
*size
, bool lock
)
2346 RAMBlock
*block
= ram_block
;
2351 if (block
== NULL
) {
2352 block
= qemu_get_ram_block(addr
);
2353 addr
-= block
->offset
;
2355 *size
= MIN(*size
, block
->max_length
- addr
);
2357 if (xen_enabled() && block
->host
== NULL
) {
2358 /* We need to check if the requested address is in the RAM
2359 * because we don't want to map the entire memory in QEMU.
2360 * In that case just map the requested area.
2362 if (block
->offset
== 0) {
2363 return xen_map_cache(addr
, *size
, lock
, lock
);
2366 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, lock
);
2369 return ramblock_ptr(block
, addr
);
2372 /* Return the offset of a hostpointer within a ramblock */
2373 ram_addr_t
qemu_ram_block_host_offset(RAMBlock
*rb
, void *host
)
2375 ram_addr_t res
= (uint8_t *)host
- (uint8_t *)rb
->host
;
2376 assert((uintptr_t)host
>= (uintptr_t)rb
->host
);
2377 assert(res
< rb
->max_length
);
2383 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2386 * ptr: Host pointer to look up
2387 * round_offset: If true round the result offset down to a page boundary
2388 * *ram_addr: set to result ram_addr
2389 * *offset: set to result offset within the RAMBlock
2391 * Returns: RAMBlock (or NULL if not found)
2393 * By the time this function returns, the returned pointer is not protected
2394 * by RCU anymore. If the caller is not within an RCU critical section and
2395 * does not hold the iothread lock, it must have other means of protecting the
2396 * pointer, such as a reference to the region that includes the incoming
2399 RAMBlock
*qemu_ram_block_from_host(void *ptr
, bool round_offset
,
2403 uint8_t *host
= ptr
;
2405 if (xen_enabled()) {
2406 ram_addr_t ram_addr
;
2408 ram_addr
= xen_ram_addr_from_mapcache(ptr
);
2409 block
= qemu_get_ram_block(ram_addr
);
2411 *offset
= ram_addr
- block
->offset
;
2418 block
= atomic_rcu_read(&ram_list
.mru_block
);
2419 if (block
&& block
->host
&& host
- block
->host
< block
->max_length
) {
2423 RAMBLOCK_FOREACH(block
) {
2424 /* This case append when the block is not mapped. */
2425 if (block
->host
== NULL
) {
2428 if (host
- block
->host
< block
->max_length
) {
2437 *offset
= (host
- block
->host
);
2439 *offset
&= TARGET_PAGE_MASK
;
2446 * Finds the named RAMBlock
2448 * name: The name of RAMBlock to find
2450 * Returns: RAMBlock (or NULL if not found)
2452 RAMBlock
*qemu_ram_block_by_name(const char *name
)
2456 RAMBLOCK_FOREACH(block
) {
2457 if (!strcmp(name
, block
->idstr
)) {
2465 /* Some of the softmmu routines need to translate from a host pointer
2466 (typically a TLB entry) back to a ram offset. */
2467 ram_addr_t
qemu_ram_addr_from_host(void *ptr
)
2472 block
= qemu_ram_block_from_host(ptr
, false, &offset
);
2474 return RAM_ADDR_INVALID
;
2477 return block
->offset
+ offset
;
2480 /* Called within RCU critical section. */
2481 void memory_notdirty_write_prepare(NotDirtyInfo
*ndi
,
2484 ram_addr_t ram_addr
,
2488 ndi
->ram_addr
= ram_addr
;
2489 ndi
->mem_vaddr
= mem_vaddr
;
2491 ndi
->locked
= false;
2493 assert(tcg_enabled());
2494 if (!cpu_physical_memory_get_dirty_flag(ram_addr
, DIRTY_MEMORY_CODE
)) {
2497 tb_invalidate_phys_page_fast(ram_addr
, size
);
2501 /* Called within RCU critical section. */
2502 void memory_notdirty_write_complete(NotDirtyInfo
*ndi
)
2508 /* Set both VGA and migration bits for simplicity and to remove
2509 * the notdirty callback faster.
2511 cpu_physical_memory_set_dirty_range(ndi
->ram_addr
, ndi
->size
,
2512 DIRTY_CLIENTS_NOCODE
);
2513 /* we remove the notdirty callback only if the code has been
2515 if (!cpu_physical_memory_is_clean(ndi
->ram_addr
)) {
2516 tlb_set_dirty(ndi
->cpu
, ndi
->mem_vaddr
);
2520 /* Called within RCU critical section. */
2521 static void notdirty_mem_write(void *opaque
, hwaddr ram_addr
,
2522 uint64_t val
, unsigned size
)
2526 memory_notdirty_write_prepare(&ndi
, current_cpu
, current_cpu
->mem_io_vaddr
,
2531 stb_p(qemu_map_ram_ptr(NULL
, ram_addr
), val
);
2534 stw_p(qemu_map_ram_ptr(NULL
, ram_addr
), val
);
2537 stl_p(qemu_map_ram_ptr(NULL
, ram_addr
), val
);
2540 stq_p(qemu_map_ram_ptr(NULL
, ram_addr
), val
);
2545 memory_notdirty_write_complete(&ndi
);
2548 static bool notdirty_mem_accepts(void *opaque
, hwaddr addr
,
2549 unsigned size
, bool is_write
,
2555 static const MemoryRegionOps notdirty_mem_ops
= {
2556 .write
= notdirty_mem_write
,
2557 .valid
.accepts
= notdirty_mem_accepts
,
2558 .endianness
= DEVICE_NATIVE_ENDIAN
,
2560 .min_access_size
= 1,
2561 .max_access_size
= 8,
2565 .min_access_size
= 1,
2566 .max_access_size
= 8,
2571 /* Generate a debug exception if a watchpoint has been hit. */
2572 static void check_watchpoint(int offset
, int len
, MemTxAttrs attrs
, int flags
)
2574 CPUState
*cpu
= current_cpu
;
2575 CPUClass
*cc
= CPU_GET_CLASS(cpu
);
2579 assert(tcg_enabled());
2580 if (cpu
->watchpoint_hit
) {
2581 /* We re-entered the check after replacing the TB. Now raise
2582 * the debug interrupt so that is will trigger after the
2583 * current instruction. */
2584 cpu_interrupt(cpu
, CPU_INTERRUPT_DEBUG
);
2587 vaddr
= (cpu
->mem_io_vaddr
& TARGET_PAGE_MASK
) + offset
;
2588 vaddr
= cc
->adjust_watchpoint_address(cpu
, vaddr
, len
);
2589 QTAILQ_FOREACH(wp
, &cpu
->watchpoints
, entry
) {
2590 if (cpu_watchpoint_address_matches(wp
, vaddr
, len
)
2591 && (wp
->flags
& flags
)) {
2592 if (flags
== BP_MEM_READ
) {
2593 wp
->flags
|= BP_WATCHPOINT_HIT_READ
;
2595 wp
->flags
|= BP_WATCHPOINT_HIT_WRITE
;
2597 wp
->hitaddr
= vaddr
;
2598 wp
->hitattrs
= attrs
;
2599 if (!cpu
->watchpoint_hit
) {
2600 if (wp
->flags
& BP_CPU
&&
2601 !cc
->debug_check_watchpoint(cpu
, wp
)) {
2602 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
2605 cpu
->watchpoint_hit
= wp
;
2607 /* Both tb_lock and iothread_mutex will be reset when
2608 * cpu_loop_exit or cpu_loop_exit_noexc longjmp
2609 * back into the cpu_exec main loop.
2612 tb_check_watchpoint(cpu
);
2613 if (wp
->flags
& BP_STOP_BEFORE_ACCESS
) {
2614 cpu
->exception_index
= EXCP_DEBUG
;
2617 /* Force execution of one insn next time. */
2618 cpu
->cflags_next_tb
= 1 | curr_cflags();
2619 cpu_loop_exit_noexc(cpu
);
2623 wp
->flags
&= ~BP_WATCHPOINT_HIT
;
2628 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2629 so these check for a hit then pass through to the normal out-of-line
2631 static MemTxResult
watch_mem_read(void *opaque
, hwaddr addr
, uint64_t *pdata
,
2632 unsigned size
, MemTxAttrs attrs
)
2636 int asidx
= cpu_asidx_from_attrs(current_cpu
, attrs
);
2637 AddressSpace
*as
= current_cpu
->cpu_ases
[asidx
].as
;
2639 check_watchpoint(addr
& ~TARGET_PAGE_MASK
, size
, attrs
, BP_MEM_READ
);
2642 data
= address_space_ldub(as
, addr
, attrs
, &res
);
2645 data
= address_space_lduw(as
, addr
, attrs
, &res
);
2648 data
= address_space_ldl(as
, addr
, attrs
, &res
);
2651 data
= address_space_ldq(as
, addr
, attrs
, &res
);
2659 static MemTxResult
watch_mem_write(void *opaque
, hwaddr addr
,
2660 uint64_t val
, unsigned size
,
2664 int asidx
= cpu_asidx_from_attrs(current_cpu
, attrs
);
2665 AddressSpace
*as
= current_cpu
->cpu_ases
[asidx
].as
;
2667 check_watchpoint(addr
& ~TARGET_PAGE_MASK
, size
, attrs
, BP_MEM_WRITE
);
2670 address_space_stb(as
, addr
, val
, attrs
, &res
);
2673 address_space_stw(as
, addr
, val
, attrs
, &res
);
2676 address_space_stl(as
, addr
, val
, attrs
, &res
);
2679 address_space_stq(as
, addr
, val
, attrs
, &res
);
2686 static const MemoryRegionOps watch_mem_ops
= {
2687 .read_with_attrs
= watch_mem_read
,
2688 .write_with_attrs
= watch_mem_write
,
2689 .endianness
= DEVICE_NATIVE_ENDIAN
,
2691 .min_access_size
= 1,
2692 .max_access_size
= 8,
2696 .min_access_size
= 1,
2697 .max_access_size
= 8,
2702 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2703 MemTxAttrs attrs
, uint8_t *buf
, int len
);
2704 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2705 const uint8_t *buf
, int len
);
2706 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, int len
,
2707 bool is_write
, MemTxAttrs attrs
);
2709 static MemTxResult
subpage_read(void *opaque
, hwaddr addr
, uint64_t *data
,
2710 unsigned len
, MemTxAttrs attrs
)
2712 subpage_t
*subpage
= opaque
;
2716 #if defined(DEBUG_SUBPAGE)
2717 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
"\n", __func__
,
2718 subpage
, len
, addr
);
2720 res
= flatview_read(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2726 *data
= ldub_p(buf
);
2729 *data
= lduw_p(buf
);
2742 static MemTxResult
subpage_write(void *opaque
, hwaddr addr
,
2743 uint64_t value
, unsigned len
, MemTxAttrs attrs
)
2745 subpage_t
*subpage
= opaque
;
2748 #if defined(DEBUG_SUBPAGE)
2749 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2750 " value %"PRIx64
"\n",
2751 __func__
, subpage
, len
, addr
, value
);
2769 return flatview_write(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2772 static bool subpage_accepts(void *opaque
, hwaddr addr
,
2773 unsigned len
, bool is_write
,
2776 subpage_t
*subpage
= opaque
;
2777 #if defined(DEBUG_SUBPAGE)
2778 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx
"\n",
2779 __func__
, subpage
, is_write
? 'w' : 'r', len
, addr
);
2782 return flatview_access_valid(subpage
->fv
, addr
+ subpage
->base
,
2783 len
, is_write
, attrs
);
2786 static const MemoryRegionOps subpage_ops
= {
2787 .read_with_attrs
= subpage_read
,
2788 .write_with_attrs
= subpage_write
,
2789 .impl
.min_access_size
= 1,
2790 .impl
.max_access_size
= 8,
2791 .valid
.min_access_size
= 1,
2792 .valid
.max_access_size
= 8,
2793 .valid
.accepts
= subpage_accepts
,
2794 .endianness
= DEVICE_NATIVE_ENDIAN
,
2797 static int subpage_register (subpage_t
*mmio
, uint32_t start
, uint32_t end
,
2802 if (start
>= TARGET_PAGE_SIZE
|| end
>= TARGET_PAGE_SIZE
)
2804 idx
= SUBPAGE_IDX(start
);
2805 eidx
= SUBPAGE_IDX(end
);
2806 #if defined(DEBUG_SUBPAGE)
2807 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2808 __func__
, mmio
, start
, end
, idx
, eidx
, section
);
2810 for (; idx
<= eidx
; idx
++) {
2811 mmio
->sub_section
[idx
] = section
;
2817 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
)
2821 mmio
= g_malloc0(sizeof(subpage_t
) + TARGET_PAGE_SIZE
* sizeof(uint16_t));
2824 memory_region_init_io(&mmio
->iomem
, NULL
, &subpage_ops
, mmio
,
2825 NULL
, TARGET_PAGE_SIZE
);
2826 mmio
->iomem
.subpage
= true;
2827 #if defined(DEBUG_SUBPAGE)
2828 printf("%s: %p base " TARGET_FMT_plx
" len %08x\n", __func__
,
2829 mmio
, base
, TARGET_PAGE_SIZE
);
2831 subpage_register(mmio
, 0, TARGET_PAGE_SIZE
-1, PHYS_SECTION_UNASSIGNED
);
2836 static uint16_t dummy_section(PhysPageMap
*map
, FlatView
*fv
, MemoryRegion
*mr
)
2839 MemoryRegionSection section
= {
2842 .offset_within_address_space
= 0,
2843 .offset_within_region
= 0,
2844 .size
= int128_2_64(),
2847 return phys_section_add(map
, §ion
);
2850 static void readonly_mem_write(void *opaque
, hwaddr addr
,
2851 uint64_t val
, unsigned size
)
2853 /* Ignore any write to ROM. */
2856 static bool readonly_mem_accepts(void *opaque
, hwaddr addr
,
2857 unsigned size
, bool is_write
,
2863 /* This will only be used for writes, because reads are special cased
2864 * to directly access the underlying host ram.
2866 static const MemoryRegionOps readonly_mem_ops
= {
2867 .write
= readonly_mem_write
,
2868 .valid
.accepts
= readonly_mem_accepts
,
2869 .endianness
= DEVICE_NATIVE_ENDIAN
,
2871 .min_access_size
= 1,
2872 .max_access_size
= 8,
2876 .min_access_size
= 1,
2877 .max_access_size
= 8,
2882 MemoryRegion
*iotlb_to_region(CPUState
*cpu
, hwaddr index
, MemTxAttrs attrs
)
2884 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
2885 CPUAddressSpace
*cpuas
= &cpu
->cpu_ases
[asidx
];
2886 AddressSpaceDispatch
*d
= atomic_rcu_read(&cpuas
->memory_dispatch
);
2887 MemoryRegionSection
*sections
= d
->map
.sections
;
2889 return sections
[index
& ~TARGET_PAGE_MASK
].mr
;
2892 static void io_mem_init(void)
2894 memory_region_init_io(&io_mem_rom
, NULL
, &readonly_mem_ops
,
2895 NULL
, NULL
, UINT64_MAX
);
2896 memory_region_init_io(&io_mem_unassigned
, NULL
, &unassigned_mem_ops
, NULL
,
2899 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
2900 * which can be called without the iothread mutex.
2902 memory_region_init_io(&io_mem_notdirty
, NULL
, ¬dirty_mem_ops
, NULL
,
2904 memory_region_clear_global_locking(&io_mem_notdirty
);
2906 memory_region_init_io(&io_mem_watch
, NULL
, &watch_mem_ops
, NULL
,
2910 AddressSpaceDispatch
*address_space_dispatch_new(FlatView
*fv
)
2912 AddressSpaceDispatch
*d
= g_new0(AddressSpaceDispatch
, 1);
2915 n
= dummy_section(&d
->map
, fv
, &io_mem_unassigned
);
2916 assert(n
== PHYS_SECTION_UNASSIGNED
);
2917 n
= dummy_section(&d
->map
, fv
, &io_mem_notdirty
);
2918 assert(n
== PHYS_SECTION_NOTDIRTY
);
2919 n
= dummy_section(&d
->map
, fv
, &io_mem_rom
);
2920 assert(n
== PHYS_SECTION_ROM
);
2921 n
= dummy_section(&d
->map
, fv
, &io_mem_watch
);
2922 assert(n
== PHYS_SECTION_WATCH
);
2924 d
->phys_map
= (PhysPageEntry
) { .ptr
= PHYS_MAP_NODE_NIL
, .skip
= 1 };
2929 void address_space_dispatch_free(AddressSpaceDispatch
*d
)
2931 phys_sections_free(&d
->map
);
2935 static void tcg_commit(MemoryListener
*listener
)
2937 CPUAddressSpace
*cpuas
;
2938 AddressSpaceDispatch
*d
;
2940 /* since each CPU stores ram addresses in its TLB cache, we must
2941 reset the modified entries */
2942 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2943 cpu_reloading_memory_map();
2944 /* The CPU and TLB are protected by the iothread lock.
2945 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2946 * may have split the RCU critical section.
2948 d
= address_space_to_dispatch(cpuas
->as
);
2949 atomic_rcu_set(&cpuas
->memory_dispatch
, d
);
2950 tlb_flush(cpuas
->cpu
);
2953 static void memory_map_init(void)
2955 system_memory
= g_malloc(sizeof(*system_memory
));
2957 memory_region_init(system_memory
, NULL
, "system", UINT64_MAX
);
2958 address_space_init(&address_space_memory
, system_memory
, "memory");
2960 system_io
= g_malloc(sizeof(*system_io
));
2961 memory_region_init_io(system_io
, NULL
, &unassigned_io_ops
, NULL
, "io",
2963 address_space_init(&address_space_io
, system_io
, "I/O");
2966 MemoryRegion
*get_system_memory(void)
2968 return system_memory
;
2971 MemoryRegion
*get_system_io(void)
2976 #endif /* !defined(CONFIG_USER_ONLY) */
2978 /* physical memory access (slow version, mainly for debug) */
2979 #if defined(CONFIG_USER_ONLY)
2980 int cpu_memory_rw_debug(CPUState
*cpu
, target_ulong addr
,
2981 uint8_t *buf
, int len
, int is_write
)
2988 page
= addr
& TARGET_PAGE_MASK
;
2989 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
2992 flags
= page_get_flags(page
);
2993 if (!(flags
& PAGE_VALID
))
2996 if (!(flags
& PAGE_WRITE
))
2998 /* XXX: this code should not depend on lock_user */
2999 if (!(p
= lock_user(VERIFY_WRITE
, addr
, l
, 0)))
3002 unlock_user(p
, addr
, l
);
3004 if (!(flags
& PAGE_READ
))
3006 /* XXX: this code should not depend on lock_user */
3007 if (!(p
= lock_user(VERIFY_READ
, addr
, l
, 1)))
3010 unlock_user(p
, addr
, 0);
3021 static void invalidate_and_set_dirty(MemoryRegion
*mr
, hwaddr addr
,
3024 uint8_t dirty_log_mask
= memory_region_get_dirty_log_mask(mr
);
3025 addr
+= memory_region_get_ram_addr(mr
);
3027 /* No early return if dirty_log_mask is or becomes 0, because
3028 * cpu_physical_memory_set_dirty_range will still call
3029 * xen_modified_memory.
3031 if (dirty_log_mask
) {
3033 cpu_physical_memory_range_includes_clean(addr
, length
, dirty_log_mask
);
3035 if (dirty_log_mask
& (1 << DIRTY_MEMORY_CODE
)) {
3036 assert(tcg_enabled());
3038 tb_invalidate_phys_range(addr
, addr
+ length
);
3040 dirty_log_mask
&= ~(1 << DIRTY_MEMORY_CODE
);
3042 cpu_physical_memory_set_dirty_range(addr
, length
, dirty_log_mask
);
3045 static int memory_access_size(MemoryRegion
*mr
, unsigned l
, hwaddr addr
)
3047 unsigned access_size_max
= mr
->ops
->valid
.max_access_size
;
3049 /* Regions are assumed to support 1-4 byte accesses unless
3050 otherwise specified. */
3051 if (access_size_max
== 0) {
3052 access_size_max
= 4;
3055 /* Bound the maximum access by the alignment of the address. */
3056 if (!mr
->ops
->impl
.unaligned
) {
3057 unsigned align_size_max
= addr
& -addr
;
3058 if (align_size_max
!= 0 && align_size_max
< access_size_max
) {
3059 access_size_max
= align_size_max
;
3063 /* Don't attempt accesses larger than the maximum. */
3064 if (l
> access_size_max
) {
3065 l
= access_size_max
;
3072 static bool prepare_mmio_access(MemoryRegion
*mr
)
3074 bool unlocked
= !qemu_mutex_iothread_locked();
3075 bool release_lock
= false;
3077 if (unlocked
&& mr
->global_locking
) {
3078 qemu_mutex_lock_iothread();
3080 release_lock
= true;
3082 if (mr
->flush_coalesced_mmio
) {
3084 qemu_mutex_lock_iothread();
3086 qemu_flush_coalesced_mmio_buffer();
3088 qemu_mutex_unlock_iothread();
3092 return release_lock
;
3095 /* Called within RCU critical section. */
3096 static MemTxResult
flatview_write_continue(FlatView
*fv
, hwaddr addr
,
3099 int len
, hwaddr addr1
,
3100 hwaddr l
, MemoryRegion
*mr
)
3104 MemTxResult result
= MEMTX_OK
;
3105 bool release_lock
= false;
3108 if (!memory_access_is_direct(mr
, true)) {
3109 release_lock
|= prepare_mmio_access(mr
);
3110 l
= memory_access_size(mr
, l
, addr1
);
3111 /* XXX: could force current_cpu to NULL to avoid
3115 /* 64 bit write access */
3117 result
|= memory_region_dispatch_write(mr
, addr1
, val
, 8,
3121 /* 32 bit write access */
3122 val
= (uint32_t)ldl_p(buf
);
3123 result
|= memory_region_dispatch_write(mr
, addr1
, val
, 4,
3127 /* 16 bit write access */
3129 result
|= memory_region_dispatch_write(mr
, addr1
, val
, 2,
3133 /* 8 bit write access */
3135 result
|= memory_region_dispatch_write(mr
, addr1
, val
, 1,
3143 ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
3144 memcpy(ptr
, buf
, l
);
3145 invalidate_and_set_dirty(mr
, addr1
, l
);
3149 qemu_mutex_unlock_iothread();
3150 release_lock
= false;
3162 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
3168 /* Called from RCU critical section. */
3169 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
3170 const uint8_t *buf
, int len
)
3175 MemTxResult result
= MEMTX_OK
;
3178 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
3179 result
= flatview_write_continue(fv
, addr
, attrs
, buf
, len
,
3185 /* Called within RCU critical section. */
3186 MemTxResult
flatview_read_continue(FlatView
*fv
, hwaddr addr
,
3187 MemTxAttrs attrs
, uint8_t *buf
,
3188 int len
, hwaddr addr1
, hwaddr l
,
3193 MemTxResult result
= MEMTX_OK
;
3194 bool release_lock
= false;
3197 if (!memory_access_is_direct(mr
, false)) {
3199 release_lock
|= prepare_mmio_access(mr
);
3200 l
= memory_access_size(mr
, l
, addr1
);
3203 /* 64 bit read access */
3204 result
|= memory_region_dispatch_read(mr
, addr1
, &val
, 8,
3209 /* 32 bit read access */
3210 result
|= memory_region_dispatch_read(mr
, addr1
, &val
, 4,
3215 /* 16 bit read access */
3216 result
|= memory_region_dispatch_read(mr
, addr1
, &val
, 2,
3221 /* 8 bit read access */
3222 result
|= memory_region_dispatch_read(mr
, addr1
, &val
, 1,
3231 ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
3232 memcpy(buf
, ptr
, l
);
3236 qemu_mutex_unlock_iothread();
3237 release_lock
= false;
3249 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
3255 /* Called from RCU critical section. */
3256 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
3257 MemTxAttrs attrs
, uint8_t *buf
, int len
)
3264 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
3265 return flatview_read_continue(fv
, addr
, attrs
, buf
, len
,
3269 MemTxResult
address_space_read_full(AddressSpace
*as
, hwaddr addr
,
3270 MemTxAttrs attrs
, uint8_t *buf
, int len
)
3272 MemTxResult result
= MEMTX_OK
;
3277 fv
= address_space_to_flatview(as
);
3278 result
= flatview_read(fv
, addr
, attrs
, buf
, len
);
3285 MemTxResult
address_space_write(AddressSpace
*as
, hwaddr addr
,
3287 const uint8_t *buf
, int len
)
3289 MemTxResult result
= MEMTX_OK
;
3294 fv
= address_space_to_flatview(as
);
3295 result
= flatview_write(fv
, addr
, attrs
, buf
, len
);
3302 MemTxResult
address_space_rw(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
,
3303 uint8_t *buf
, int len
, bool is_write
)
3306 return address_space_write(as
, addr
, attrs
, buf
, len
);
3308 return address_space_read_full(as
, addr
, attrs
, buf
, len
);
3312 void cpu_physical_memory_rw(hwaddr addr
, uint8_t *buf
,
3313 int len
, int is_write
)
3315 address_space_rw(&address_space_memory
, addr
, MEMTXATTRS_UNSPECIFIED
,
3316 buf
, len
, is_write
);
3319 enum write_rom_type
{
3324 static inline void cpu_physical_memory_write_rom_internal(AddressSpace
*as
,
3325 hwaddr addr
, const uint8_t *buf
, int len
, enum write_rom_type type
)
3335 mr
= address_space_translate(as
, addr
, &addr1
, &l
, true,
3336 MEMTXATTRS_UNSPECIFIED
);
3338 if (!(memory_region_is_ram(mr
) ||
3339 memory_region_is_romd(mr
))) {
3340 l
= memory_access_size(mr
, l
, addr1
);
3343 ptr
= qemu_map_ram_ptr(mr
->ram_block
, addr1
);
3346 memcpy(ptr
, buf
, l
);
3347 invalidate_and_set_dirty(mr
, addr1
, l
);
3350 flush_icache_range((uintptr_t)ptr
, (uintptr_t)ptr
+ l
);
3361 /* used for ROM loading : can write in RAM and ROM */
3362 void cpu_physical_memory_write_rom(AddressSpace
*as
, hwaddr addr
,
3363 const uint8_t *buf
, int len
)
3365 cpu_physical_memory_write_rom_internal(as
, addr
, buf
, len
, WRITE_DATA
);
3368 void cpu_flush_icache_range(hwaddr start
, int len
)
3371 * This function should do the same thing as an icache flush that was
3372 * triggered from within the guest. For TCG we are always cache coherent,
3373 * so there is no need to flush anything. For KVM / Xen we need to flush
3374 * the host's instruction cache at least.
3376 if (tcg_enabled()) {
3380 cpu_physical_memory_write_rom_internal(&address_space_memory
,
3381 start
, NULL
, len
, FLUSH_CACHE
);
3392 static BounceBuffer bounce
;
3394 typedef struct MapClient
{
3396 QLIST_ENTRY(MapClient
) link
;
3399 QemuMutex map_client_list_lock
;
3400 static QLIST_HEAD(map_client_list
, MapClient
) map_client_list
3401 = QLIST_HEAD_INITIALIZER(map_client_list
);
3403 static void cpu_unregister_map_client_do(MapClient
*client
)
3405 QLIST_REMOVE(client
, link
);
3409 static void cpu_notify_map_clients_locked(void)
3413 while (!QLIST_EMPTY(&map_client_list
)) {
3414 client
= QLIST_FIRST(&map_client_list
);
3415 qemu_bh_schedule(client
->bh
);
3416 cpu_unregister_map_client_do(client
);
3420 void cpu_register_map_client(QEMUBH
*bh
)
3422 MapClient
*client
= g_malloc(sizeof(*client
));
3424 qemu_mutex_lock(&map_client_list_lock
);
3426 QLIST_INSERT_HEAD(&map_client_list
, client
, link
);
3427 if (!atomic_read(&bounce
.in_use
)) {
3428 cpu_notify_map_clients_locked();
3430 qemu_mutex_unlock(&map_client_list_lock
);
3433 void cpu_exec_init_all(void)
3435 qemu_mutex_init(&ram_list
.mutex
);
3436 /* The data structures we set up here depend on knowing the page size,
3437 * so no more changes can be made after this point.
3438 * In an ideal world, nothing we did before we had finished the
3439 * machine setup would care about the target page size, and we could
3440 * do this much later, rather than requiring board models to state
3441 * up front what their requirements are.
3443 finalize_target_page_bits();
3446 qemu_mutex_init(&map_client_list_lock
);
3449 void cpu_unregister_map_client(QEMUBH
*bh
)
3453 qemu_mutex_lock(&map_client_list_lock
);
3454 QLIST_FOREACH(client
, &map_client_list
, link
) {
3455 if (client
->bh
== bh
) {
3456 cpu_unregister_map_client_do(client
);
3460 qemu_mutex_unlock(&map_client_list_lock
);
3463 static void cpu_notify_map_clients(void)
3465 qemu_mutex_lock(&map_client_list_lock
);
3466 cpu_notify_map_clients_locked();
3467 qemu_mutex_unlock(&map_client_list_lock
);
3470 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, int len
,
3471 bool is_write
, MemTxAttrs attrs
)
3478 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3479 if (!memory_access_is_direct(mr
, is_write
)) {
3480 l
= memory_access_size(mr
, l
, addr
);
3481 if (!memory_region_access_valid(mr
, xlat
, l
, is_write
, attrs
)) {
3492 bool address_space_access_valid(AddressSpace
*as
, hwaddr addr
,
3493 int len
, bool is_write
,
3500 fv
= address_space_to_flatview(as
);
3501 result
= flatview_access_valid(fv
, addr
, len
, is_write
, attrs
);
3507 flatview_extend_translation(FlatView
*fv
, hwaddr addr
,
3509 MemoryRegion
*mr
, hwaddr base
, hwaddr len
,
3510 bool is_write
, MemTxAttrs attrs
)
3514 MemoryRegion
*this_mr
;
3520 if (target_len
== 0) {
3525 this_mr
= flatview_translate(fv
, addr
, &xlat
,
3526 &len
, is_write
, attrs
);
3527 if (this_mr
!= mr
|| xlat
!= base
+ done
) {
3533 /* Map a physical memory region into a host virtual address.
3534 * May map a subset of the requested range, given by and returned in *plen.
3535 * May return NULL if resources needed to perform the mapping are exhausted.
3536 * Use only for reads OR writes - not for read-modify-write operations.
3537 * Use cpu_register_map_client() to know when retrying the map operation is
3538 * likely to succeed.
3540 void *address_space_map(AddressSpace
*as
,
3558 fv
= address_space_to_flatview(as
);
3559 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3561 if (!memory_access_is_direct(mr
, is_write
)) {
3562 if (atomic_xchg(&bounce
.in_use
, true)) {
3566 /* Avoid unbounded allocations */
3567 l
= MIN(l
, TARGET_PAGE_SIZE
);
3568 bounce
.buffer
= qemu_memalign(TARGET_PAGE_SIZE
, l
);
3572 memory_region_ref(mr
);
3575 flatview_read(fv
, addr
, MEMTXATTRS_UNSPECIFIED
,
3581 return bounce
.buffer
;
3585 memory_region_ref(mr
);
3586 *plen
= flatview_extend_translation(fv
, addr
, len
, mr
, xlat
,
3587 l
, is_write
, attrs
);
3588 ptr
= qemu_ram_ptr_length(mr
->ram_block
, xlat
, plen
, true);
3594 /* Unmaps a memory region previously mapped by address_space_map().
3595 * Will also mark the memory as dirty if is_write == 1. access_len gives
3596 * the amount of memory that was actually read or written by the caller.
3598 void address_space_unmap(AddressSpace
*as
, void *buffer
, hwaddr len
,
3599 int is_write
, hwaddr access_len
)
3601 if (buffer
!= bounce
.buffer
) {
3605 mr
= memory_region_from_host(buffer
, &addr1
);
3608 invalidate_and_set_dirty(mr
, addr1
, access_len
);
3610 if (xen_enabled()) {
3611 xen_invalidate_map_cache_entry(buffer
);
3613 memory_region_unref(mr
);
3617 address_space_write(as
, bounce
.addr
, MEMTXATTRS_UNSPECIFIED
,
3618 bounce
.buffer
, access_len
);
3620 qemu_vfree(bounce
.buffer
);
3621 bounce
.buffer
= NULL
;
3622 memory_region_unref(bounce
.mr
);
3623 atomic_mb_set(&bounce
.in_use
, false);
3624 cpu_notify_map_clients();
3627 void *cpu_physical_memory_map(hwaddr addr
,
3631 return address_space_map(&address_space_memory
, addr
, plen
, is_write
,
3632 MEMTXATTRS_UNSPECIFIED
);
3635 void cpu_physical_memory_unmap(void *buffer
, hwaddr len
,
3636 int is_write
, hwaddr access_len
)
3638 return address_space_unmap(&address_space_memory
, buffer
, len
, is_write
, access_len
);
3641 #define ARG1_DECL AddressSpace *as
3644 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3645 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3646 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3647 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3648 #define RCU_READ_LOCK(...) rcu_read_lock()
3649 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3650 #include "memory_ldst.inc.c"
3652 int64_t address_space_cache_init(MemoryRegionCache
*cache
,
3658 AddressSpaceDispatch
*d
;
3665 cache
->fv
= address_space_get_flatview(as
);
3666 d
= flatview_to_dispatch(cache
->fv
);
3667 cache
->mrs
= *address_space_translate_internal(d
, addr
, &cache
->xlat
, &l
, true);
3670 memory_region_ref(mr
);
3671 if (memory_access_is_direct(mr
, is_write
)) {
3672 /* We don't care about the memory attributes here as we're only
3673 * doing this if we found actual RAM, which behaves the same
3674 * regardless of attributes; so UNSPECIFIED is fine.
3676 l
= flatview_extend_translation(cache
->fv
, addr
, len
, mr
,
3677 cache
->xlat
, l
, is_write
,
3678 MEMTXATTRS_UNSPECIFIED
);
3679 cache
->ptr
= qemu_ram_ptr_length(mr
->ram_block
, cache
->xlat
, &l
, true);
3685 cache
->is_write
= is_write
;
3689 void address_space_cache_invalidate(MemoryRegionCache
*cache
,
3693 assert(cache
->is_write
);
3694 if (likely(cache
->ptr
)) {
3695 invalidate_and_set_dirty(cache
->mrs
.mr
, addr
+ cache
->xlat
, access_len
);
3699 void address_space_cache_destroy(MemoryRegionCache
*cache
)
3701 if (!cache
->mrs
.mr
) {
3705 if (xen_enabled()) {
3706 xen_invalidate_map_cache_entry(cache
->ptr
);
3708 memory_region_unref(cache
->mrs
.mr
);
3709 flatview_unref(cache
->fv
);
3710 cache
->mrs
.mr
= NULL
;
3714 /* Called from RCU critical section. This function has the same
3715 * semantics as address_space_translate, but it only works on a
3716 * predefined range of a MemoryRegion that was mapped with
3717 * address_space_cache_init.
3719 static inline MemoryRegion
*address_space_translate_cached(
3720 MemoryRegionCache
*cache
, hwaddr addr
, hwaddr
*xlat
,
3721 hwaddr
*plen
, bool is_write
, MemTxAttrs attrs
)
3723 MemoryRegionSection section
;
3725 IOMMUMemoryRegion
*iommu_mr
;
3726 AddressSpace
*target_as
;
3728 assert(!cache
->ptr
);
3729 *xlat
= addr
+ cache
->xlat
;
3732 iommu_mr
= memory_region_get_iommu(mr
);
3738 section
= address_space_translate_iommu(iommu_mr
, xlat
, plen
,
3739 NULL
, is_write
, true,
3744 /* Called from RCU critical section. address_space_read_cached uses this
3745 * out of line function when the target is an MMIO or IOMMU region.
3748 address_space_read_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3755 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, false,
3756 MEMTXATTRS_UNSPECIFIED
);
3757 flatview_read_continue(cache
->fv
,
3758 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3762 /* Called from RCU critical section. address_space_write_cached uses this
3763 * out of line function when the target is an MMIO or IOMMU region.
3766 address_space_write_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3767 const void *buf
, int len
)
3773 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, true,
3774 MEMTXATTRS_UNSPECIFIED
);
3775 flatview_write_continue(cache
->fv
,
3776 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3780 #define ARG1_DECL MemoryRegionCache *cache
3782 #define SUFFIX _cached_slow
3783 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3784 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3785 #define MAP_RAM(mr, ofs) (cache->ptr + (ofs - cache->xlat))
3786 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3787 #define RCU_READ_LOCK() ((void)0)
3788 #define RCU_READ_UNLOCK() ((void)0)
3789 #include "memory_ldst.inc.c"
3791 /* virtual memory access for debug (includes writing to ROM) */
3792 int cpu_memory_rw_debug(CPUState
*cpu
, target_ulong addr
,
3793 uint8_t *buf
, int len
, int is_write
)
3799 cpu_synchronize_state(cpu
);
3804 page
= addr
& TARGET_PAGE_MASK
;
3805 phys_addr
= cpu_get_phys_page_attrs_debug(cpu
, page
, &attrs
);
3806 asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
3807 /* if no physical page mapped, return an error */
3808 if (phys_addr
== -1)
3810 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3813 phys_addr
+= (addr
& ~TARGET_PAGE_MASK
);
3815 cpu_physical_memory_write_rom(cpu
->cpu_ases
[asidx
].as
,
3818 address_space_rw(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3819 MEMTXATTRS_UNSPECIFIED
,
3830 * Allows code that needs to deal with migration bitmaps etc to still be built
3831 * target independent.
3833 size_t qemu_target_page_size(void)
3835 return TARGET_PAGE_SIZE
;
3838 int qemu_target_page_bits(void)
3840 return TARGET_PAGE_BITS
;
3843 int qemu_target_page_bits_min(void)
3845 return TARGET_PAGE_BITS_MIN
;
3850 * A helper function for the _utterly broken_ virtio device model to find out if
3851 * it's running on a big endian machine. Don't do this at home kids!
3853 bool target_words_bigendian(void);
3854 bool target_words_bigendian(void)
3856 #if defined(TARGET_WORDS_BIGENDIAN)
3863 #ifndef CONFIG_USER_ONLY
3864 bool cpu_physical_memory_is_io(hwaddr phys_addr
)
3871 mr
= address_space_translate(&address_space_memory
,
3872 phys_addr
, &phys_addr
, &l
, false,
3873 MEMTXATTRS_UNSPECIFIED
);
3875 res
= !(memory_region_is_ram(mr
) || memory_region_is_romd(mr
));
3880 int qemu_ram_foreach_block(RAMBlockIterFunc func
, void *opaque
)
3886 RAMBLOCK_FOREACH(block
) {
3887 ret
= func(block
->idstr
, block
->host
, block
->offset
,
3888 block
->used_length
, opaque
);
3898 * Unmap pages of memory from start to start+length such that
3899 * they a) read as 0, b) Trigger whatever fault mechanism
3900 * the OS provides for postcopy.
3901 * The pages must be unmapped by the end of the function.
3902 * Returns: 0 on success, none-0 on failure
3905 int ram_block_discard_range(RAMBlock
*rb
, uint64_t start
, size_t length
)
3909 uint8_t *host_startaddr
= rb
->host
+ start
;
3911 if ((uintptr_t)host_startaddr
& (rb
->page_size
- 1)) {
3912 error_report("ram_block_discard_range: Unaligned start address: %p",
3917 if ((start
+ length
) <= rb
->used_length
) {
3918 bool need_madvise
, need_fallocate
;
3919 uint8_t *host_endaddr
= host_startaddr
+ length
;
3920 if ((uintptr_t)host_endaddr
& (rb
->page_size
- 1)) {
3921 error_report("ram_block_discard_range: Unaligned end address: %p",
3926 errno
= ENOTSUP
; /* If we are missing MADVISE etc */
3928 /* The logic here is messy;
3929 * madvise DONTNEED fails for hugepages
3930 * fallocate works on hugepages and shmem
3932 need_madvise
= (rb
->page_size
== qemu_host_page_size
);
3933 need_fallocate
= rb
->fd
!= -1;
3934 if (need_fallocate
) {
3935 /* For a file, this causes the area of the file to be zero'd
3936 * if read, and for hugetlbfs also causes it to be unmapped
3937 * so a userfault will trigger.
3939 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3940 ret
= fallocate(rb
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3944 error_report("ram_block_discard_range: Failed to fallocate "
3945 "%s:%" PRIx64
" +%zx (%d)",
3946 rb
->idstr
, start
, length
, ret
);
3951 error_report("ram_block_discard_range: fallocate not available/file"
3952 "%s:%" PRIx64
" +%zx (%d)",
3953 rb
->idstr
, start
, length
, ret
);
3958 /* For normal RAM this causes it to be unmapped,
3959 * for shared memory it causes the local mapping to disappear
3960 * and to fall back on the file contents (which we just
3961 * fallocate'd away).
3963 #if defined(CONFIG_MADVISE)
3964 ret
= madvise(host_startaddr
, length
, MADV_DONTNEED
);
3967 error_report("ram_block_discard_range: Failed to discard range "
3968 "%s:%" PRIx64
" +%zx (%d)",
3969 rb
->idstr
, start
, length
, ret
);
3974 error_report("ram_block_discard_range: MADVISE not available"
3975 "%s:%" PRIx64
" +%zx (%d)",
3976 rb
->idstr
, start
, length
, ret
);
3980 trace_ram_block_discard_range(rb
->idstr
, host_startaddr
, length
,
3981 need_madvise
, need_fallocate
, ret
);
3983 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3984 "/%zx/" RAM_ADDR_FMT
")",
3985 rb
->idstr
, start
, length
, rb
->used_length
);
3994 void page_size_init(void)
3996 /* NOTE: we can always suppose that qemu_host_page_size >=
3998 if (qemu_host_page_size
== 0) {
3999 qemu_host_page_size
= qemu_real_host_page_size
;
4001 if (qemu_host_page_size
< TARGET_PAGE_SIZE
) {
4002 qemu_host_page_size
= TARGET_PAGE_SIZE
;
4004 qemu_host_page_mask
= -(intptr_t)qemu_host_page_size
;
4007 #if !defined(CONFIG_USER_ONLY)
4009 static void mtree_print_phys_entries(fprintf_function mon
, void *f
,
4010 int start
, int end
, int skip
, int ptr
)
4012 if (start
== end
- 1) {
4013 mon(f
, "\t%3d ", start
);
4015 mon(f
, "\t%3d..%-3d ", start
, end
- 1);
4017 mon(f
, " skip=%d ", skip
);
4018 if (ptr
== PHYS_MAP_NODE_NIL
) {
4021 mon(f
, " ptr=#%d", ptr
);
4023 mon(f
, " ptr=[%d]", ptr
);
4028 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
4029 int128_sub((size), int128_one())) : 0)
4031 void mtree_print_dispatch(fprintf_function mon
, void *f
,
4032 AddressSpaceDispatch
*d
, MemoryRegion
*root
)
4036 mon(f
, " Dispatch\n");
4037 mon(f
, " Physical sections\n");
4039 for (i
= 0; i
< d
->map
.sections_nb
; ++i
) {
4040 MemoryRegionSection
*s
= d
->map
.sections
+ i
;
4041 const char *names
[] = { " [unassigned]", " [not dirty]",
4042 " [ROM]", " [watch]" };
4044 mon(f
, " #%d @" TARGET_FMT_plx
".." TARGET_FMT_plx
" %s%s%s%s%s",
4046 s
->offset_within_address_space
,
4047 s
->offset_within_address_space
+ MR_SIZE(s
->mr
->size
),
4048 s
->mr
->name
? s
->mr
->name
: "(noname)",
4049 i
< ARRAY_SIZE(names
) ? names
[i
] : "",
4050 s
->mr
== root
? " [ROOT]" : "",
4051 s
== d
->mru_section
? " [MRU]" : "",
4052 s
->mr
->is_iommu
? " [iommu]" : "");
4055 mon(f
, " alias=%s", s
->mr
->alias
->name
?
4056 s
->mr
->alias
->name
: "noname");
4061 mon(f
, " Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
4062 P_L2_BITS
, P_L2_LEVELS
, d
->phys_map
.ptr
, d
->phys_map
.skip
);
4063 for (i
= 0; i
< d
->map
.nodes_nb
; ++i
) {
4066 Node
*n
= d
->map
.nodes
+ i
;
4068 mon(f
, " [%d]\n", i
);
4070 for (j
= 0, jprev
= 0, prev
= *n
[0]; j
< ARRAY_SIZE(*n
); ++j
) {
4071 PhysPageEntry
*pe
= *n
+ j
;
4073 if (pe
->ptr
== prev
.ptr
&& pe
->skip
== prev
.skip
) {
4077 mtree_print_phys_entries(mon
, f
, jprev
, j
, prev
.skip
, prev
.ptr
);
4083 if (jprev
!= ARRAY_SIZE(*n
)) {
4084 mtree_print_phys_entries(mon
, f
, jprev
, j
, prev
.skip
, prev
.ptr
);