2 * RAM allocation and memory access
4 * Copyright (c) 2003 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 #include "qemu/osdep.h"
21 #include "exec/page-vary.h"
22 #include "qapi/error.h"
24 #include "qemu/cutils.h"
25 #include "qemu/cacheflush.h"
26 #include "qemu/hbitmap.h"
27 #include "qemu/madvise.h"
30 #include "hw/core/tcg-cpu-ops.h"
31 #endif /* CONFIG_TCG */
33 #include "exec/exec-all.h"
34 #include "exec/target_page.h"
35 #include "hw/qdev-core.h"
36 #include "hw/qdev-properties.h"
37 #include "hw/boards.h"
38 #include "hw/xen/xen.h"
39 #include "sysemu/kvm.h"
40 #include "sysemu/tcg.h"
41 #include "sysemu/qtest.h"
42 #include "qemu/timer.h"
43 #include "qemu/config-file.h"
44 #include "qemu/error-report.h"
45 #include "qemu/qemu-print.h"
47 #include "qemu/memalign.h"
48 #include "exec/memory.h"
49 #include "exec/ioport.h"
50 #include "sysemu/dma.h"
51 #include "sysemu/hostmem.h"
52 #include "sysemu/hw_accel.h"
53 #include "sysemu/xen-mapcache.h"
54 #include "trace/trace-root.h"
56 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
57 #include <linux/falloc.h>
60 #include "qemu/rcu_queue.h"
61 #include "qemu/main-loop.h"
62 #include "exec/translate-all.h"
63 #include "sysemu/replay.h"
65 #include "exec/memory-internal.h"
66 #include "exec/ram_addr.h"
68 #include "qemu/pmem.h"
70 #include "migration/vmstate.h"
72 #include "qemu/range.h"
74 #include "qemu/mmap-alloc.h"
77 #include "monitor/monitor.h"
79 #ifdef CONFIG_LIBDAXCTL
80 #include <daxctl/libdaxctl.h>
83 //#define DEBUG_SUBPAGE
85 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
86 * are protected by the ramlist lock.
88 RAMList ram_list
= { .blocks
= QLIST_HEAD_INITIALIZER(ram_list
.blocks
) };
90 static MemoryRegion
*system_memory
;
91 static MemoryRegion
*system_io
;
93 AddressSpace address_space_io
;
94 AddressSpace address_space_memory
;
96 static MemoryRegion io_mem_unassigned
;
98 typedef struct PhysPageEntry PhysPageEntry
;
100 struct PhysPageEntry
{
101 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
103 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
107 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
109 /* Size of the L2 (and L3, etc) page tables. */
110 #define ADDR_SPACE_BITS 64
113 #define P_L2_SIZE (1 << P_L2_BITS)
115 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
117 typedef PhysPageEntry Node
[P_L2_SIZE
];
119 typedef struct PhysPageMap
{
122 unsigned sections_nb
;
123 unsigned sections_nb_alloc
;
125 unsigned nodes_nb_alloc
;
127 MemoryRegionSection
*sections
;
130 struct AddressSpaceDispatch
{
131 MemoryRegionSection
*mru_section
;
132 /* This is a multi-level map on the physical address space.
133 * The bottom level has pointers to MemoryRegionSections.
135 PhysPageEntry phys_map
;
139 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
140 typedef struct subpage_t
{
144 uint16_t sub_section
[];
147 #define PHYS_SECTION_UNASSIGNED 0
149 static void io_mem_init(void);
150 static void memory_map_init(void);
151 static void tcg_log_global_after_sync(MemoryListener
*listener
);
152 static void tcg_commit(MemoryListener
*listener
);
155 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
156 * @cpu: the CPU whose AddressSpace this is
157 * @as: the AddressSpace itself
158 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
159 * @tcg_as_listener: listener for tracking changes to the AddressSpace
161 struct CPUAddressSpace
{
164 struct AddressSpaceDispatch
*memory_dispatch
;
165 MemoryListener tcg_as_listener
;
168 struct DirtyBitmapSnapshot
{
171 unsigned long dirty
[];
174 static void phys_map_node_reserve(PhysPageMap
*map
, unsigned nodes
)
176 static unsigned alloc_hint
= 16;
177 if (map
->nodes_nb
+ nodes
> map
->nodes_nb_alloc
) {
178 map
->nodes_nb_alloc
= MAX(alloc_hint
, map
->nodes_nb
+ nodes
);
179 map
->nodes
= g_renew(Node
, map
->nodes
, map
->nodes_nb_alloc
);
180 alloc_hint
= map
->nodes_nb_alloc
;
184 static uint32_t phys_map_node_alloc(PhysPageMap
*map
, bool leaf
)
191 ret
= map
->nodes_nb
++;
193 assert(ret
!= PHYS_MAP_NODE_NIL
);
194 assert(ret
!= map
->nodes_nb_alloc
);
196 e
.skip
= leaf
? 0 : 1;
197 e
.ptr
= leaf
? PHYS_SECTION_UNASSIGNED
: PHYS_MAP_NODE_NIL
;
198 for (i
= 0; i
< P_L2_SIZE
; ++i
) {
199 memcpy(&p
[i
], &e
, sizeof(e
));
204 static void phys_page_set_level(PhysPageMap
*map
, PhysPageEntry
*lp
,
205 hwaddr
*index
, uint64_t *nb
, uint16_t leaf
,
209 hwaddr step
= (hwaddr
)1 << (level
* P_L2_BITS
);
211 if (lp
->skip
&& lp
->ptr
== PHYS_MAP_NODE_NIL
) {
212 lp
->ptr
= phys_map_node_alloc(map
, level
== 0);
214 p
= map
->nodes
[lp
->ptr
];
215 lp
= &p
[(*index
>> (level
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
217 while (*nb
&& lp
< &p
[P_L2_SIZE
]) {
218 if ((*index
& (step
- 1)) == 0 && *nb
>= step
) {
224 phys_page_set_level(map
, lp
, index
, nb
, leaf
, level
- 1);
230 static void phys_page_set(AddressSpaceDispatch
*d
,
231 hwaddr index
, uint64_t nb
,
234 /* Wildly overreserve - it doesn't matter much. */
235 phys_map_node_reserve(&d
->map
, 3 * P_L2_LEVELS
);
237 phys_page_set_level(&d
->map
, &d
->phys_map
, &index
, &nb
, leaf
, P_L2_LEVELS
- 1);
240 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
241 * and update our entry so we can skip it and go directly to the destination.
243 static void phys_page_compact(PhysPageEntry
*lp
, Node
*nodes
)
245 unsigned valid_ptr
= P_L2_SIZE
;
250 if (lp
->ptr
== PHYS_MAP_NODE_NIL
) {
255 for (i
= 0; i
< P_L2_SIZE
; i
++) {
256 if (p
[i
].ptr
== PHYS_MAP_NODE_NIL
) {
263 phys_page_compact(&p
[i
], nodes
);
267 /* We can only compress if there's only one child. */
272 assert(valid_ptr
< P_L2_SIZE
);
274 /* Don't compress if it won't fit in the # of bits we have. */
275 if (P_L2_LEVELS
>= (1 << 6) &&
276 lp
->skip
+ p
[valid_ptr
].skip
>= (1 << 6)) {
280 lp
->ptr
= p
[valid_ptr
].ptr
;
281 if (!p
[valid_ptr
].skip
) {
282 /* If our only child is a leaf, make this a leaf. */
283 /* By design, we should have made this node a leaf to begin with so we
284 * should never reach here.
285 * But since it's so simple to handle this, let's do it just in case we
290 lp
->skip
+= p
[valid_ptr
].skip
;
294 void address_space_dispatch_compact(AddressSpaceDispatch
*d
)
296 if (d
->phys_map
.skip
) {
297 phys_page_compact(&d
->phys_map
, d
->map
.nodes
);
301 static inline bool section_covers_addr(const MemoryRegionSection
*section
,
304 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
305 * the section must cover the entire address space.
307 return int128_gethi(section
->size
) ||
308 range_covers_byte(section
->offset_within_address_space
,
309 int128_getlo(section
->size
), addr
);
312 static MemoryRegionSection
*phys_page_find(AddressSpaceDispatch
*d
, hwaddr addr
)
314 PhysPageEntry lp
= d
->phys_map
, *p
;
315 Node
*nodes
= d
->map
.nodes
;
316 MemoryRegionSection
*sections
= d
->map
.sections
;
317 hwaddr index
= addr
>> TARGET_PAGE_BITS
;
320 for (i
= P_L2_LEVELS
; lp
.skip
&& (i
-= lp
.skip
) >= 0;) {
321 if (lp
.ptr
== PHYS_MAP_NODE_NIL
) {
322 return §ions
[PHYS_SECTION_UNASSIGNED
];
325 lp
= p
[(index
>> (i
* P_L2_BITS
)) & (P_L2_SIZE
- 1)];
328 if (section_covers_addr(§ions
[lp
.ptr
], addr
)) {
329 return §ions
[lp
.ptr
];
331 return §ions
[PHYS_SECTION_UNASSIGNED
];
335 /* Called from RCU critical section */
336 static MemoryRegionSection
*address_space_lookup_region(AddressSpaceDispatch
*d
,
338 bool resolve_subpage
)
340 MemoryRegionSection
*section
= qatomic_read(&d
->mru_section
);
343 if (!section
|| section
== &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
] ||
344 !section_covers_addr(section
, addr
)) {
345 section
= phys_page_find(d
, addr
);
346 qatomic_set(&d
->mru_section
, section
);
348 if (resolve_subpage
&& section
->mr
->subpage
) {
349 subpage
= container_of(section
->mr
, subpage_t
, iomem
);
350 section
= &d
->map
.sections
[subpage
->sub_section
[SUBPAGE_IDX(addr
)]];
355 /* Called from RCU critical section */
356 static MemoryRegionSection
*
357 address_space_translate_internal(AddressSpaceDispatch
*d
, hwaddr addr
, hwaddr
*xlat
,
358 hwaddr
*plen
, bool resolve_subpage
)
360 MemoryRegionSection
*section
;
364 section
= address_space_lookup_region(d
, addr
, resolve_subpage
);
365 /* Compute offset within MemoryRegionSection */
366 addr
-= section
->offset_within_address_space
;
368 /* Compute offset within MemoryRegion */
369 *xlat
= addr
+ section
->offset_within_region
;
373 /* MMIO registers can be expected to perform full-width accesses based only
374 * on their address, without considering adjacent registers that could
375 * decode to completely different MemoryRegions. When such registers
376 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
377 * regions overlap wildly. For this reason we cannot clamp the accesses
380 * If the length is small (as is the case for address_space_ldl/stl),
381 * everything works fine. If the incoming length is large, however,
382 * the caller really has to do the clamping through memory_access_size.
384 if (memory_region_is_ram(mr
)) {
385 diff
= int128_sub(section
->size
, int128_make64(addr
));
386 *plen
= int128_get64(int128_min(diff
, int128_make64(*plen
)));
392 * address_space_translate_iommu - translate an address through an IOMMU
393 * memory region and then through the target address space.
395 * @iommu_mr: the IOMMU memory region that we start the translation from
396 * @addr: the address to be translated through the MMU
397 * @xlat: the translated address offset within the destination memory region.
398 * It cannot be %NULL.
399 * @plen_out: valid read/write length of the translated address. It
401 * @page_mask_out: page mask for the translated address. This
402 * should only be meaningful for IOMMU translated
403 * addresses, since there may be huge pages that this bit
404 * would tell. It can be %NULL if we don't care about it.
405 * @is_write: whether the translation operation is for write
406 * @is_mmio: whether this can be MMIO, set true if it can
407 * @target_as: the address space targeted by the IOMMU
408 * @attrs: transaction attributes
410 * This function is called from RCU critical section. It is the common
411 * part of flatview_do_translate and address_space_translate_cached.
413 static MemoryRegionSection
address_space_translate_iommu(IOMMUMemoryRegion
*iommu_mr
,
416 hwaddr
*page_mask_out
,
419 AddressSpace
**target_as
,
422 MemoryRegionSection
*section
;
423 hwaddr page_mask
= (hwaddr
)-1;
427 IOMMUMemoryRegionClass
*imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
431 if (imrc
->attrs_to_index
) {
432 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
435 iotlb
= imrc
->translate(iommu_mr
, addr
, is_write
?
436 IOMMU_WO
: IOMMU_RO
, iommu_idx
);
438 if (!(iotlb
.perm
& (1 << is_write
))) {
442 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
443 | (addr
& iotlb
.addr_mask
));
444 page_mask
&= iotlb
.addr_mask
;
445 *plen_out
= MIN(*plen_out
, (addr
| iotlb
.addr_mask
) - addr
+ 1);
446 *target_as
= iotlb
.target_as
;
448 section
= address_space_translate_internal(
449 address_space_to_dispatch(iotlb
.target_as
), addr
, xlat
,
452 iommu_mr
= memory_region_get_iommu(section
->mr
);
453 } while (unlikely(iommu_mr
));
456 *page_mask_out
= page_mask
;
461 return (MemoryRegionSection
) { .mr
= &io_mem_unassigned
};
465 * flatview_do_translate - translate an address in FlatView
467 * @fv: the flat view that we want to translate on
468 * @addr: the address to be translated in above address space
469 * @xlat: the translated address offset within memory region. It
471 * @plen_out: valid read/write length of the translated address. It
472 * can be @NULL when we don't care about it.
473 * @page_mask_out: page mask for the translated address. This
474 * should only be meaningful for IOMMU translated
475 * addresses, since there may be huge pages that this bit
476 * would tell. It can be @NULL if we don't care about it.
477 * @is_write: whether the translation operation is for write
478 * @is_mmio: whether this can be MMIO, set true if it can
479 * @target_as: the address space targeted by the IOMMU
480 * @attrs: memory transaction attributes
482 * This function is called from RCU critical section
484 static MemoryRegionSection
flatview_do_translate(FlatView
*fv
,
488 hwaddr
*page_mask_out
,
491 AddressSpace
**target_as
,
494 MemoryRegionSection
*section
;
495 IOMMUMemoryRegion
*iommu_mr
;
496 hwaddr plen
= (hwaddr
)(-1);
502 section
= address_space_translate_internal(
503 flatview_to_dispatch(fv
), addr
, xlat
,
506 iommu_mr
= memory_region_get_iommu(section
->mr
);
507 if (unlikely(iommu_mr
)) {
508 return address_space_translate_iommu(iommu_mr
, xlat
,
509 plen_out
, page_mask_out
,
514 /* Not behind an IOMMU, use default page size. */
515 *page_mask_out
= ~TARGET_PAGE_MASK
;
521 /* Called from RCU critical section */
522 IOMMUTLBEntry
address_space_get_iotlb_entry(AddressSpace
*as
, hwaddr addr
,
523 bool is_write
, MemTxAttrs attrs
)
525 MemoryRegionSection section
;
526 hwaddr xlat
, page_mask
;
529 * This can never be MMIO, and we don't really care about plen,
532 section
= flatview_do_translate(address_space_to_flatview(as
), addr
, &xlat
,
533 NULL
, &page_mask
, is_write
, false, &as
,
536 /* Illegal translation */
537 if (section
.mr
== &io_mem_unassigned
) {
541 /* Convert memory region offset into address space offset */
542 xlat
+= section
.offset_within_address_space
-
543 section
.offset_within_region
;
545 return (IOMMUTLBEntry
) {
547 .iova
= addr
& ~page_mask
,
548 .translated_addr
= xlat
& ~page_mask
,
549 .addr_mask
= page_mask
,
550 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
555 return (IOMMUTLBEntry
) {0};
558 /* Called from RCU critical section */
559 MemoryRegion
*flatview_translate(FlatView
*fv
, hwaddr addr
, hwaddr
*xlat
,
560 hwaddr
*plen
, bool is_write
,
564 MemoryRegionSection section
;
565 AddressSpace
*as
= NULL
;
567 /* This can be MMIO, so setup MMIO bit. */
568 section
= flatview_do_translate(fv
, addr
, xlat
, plen
, NULL
,
569 is_write
, true, &as
, attrs
);
572 if (xen_enabled() && memory_access_is_direct(mr
, is_write
)) {
573 hwaddr page
= ((addr
& TARGET_PAGE_MASK
) + TARGET_PAGE_SIZE
) - addr
;
574 *plen
= MIN(page
, *plen
);
580 typedef struct TCGIOMMUNotifier
{
588 static void tcg_iommu_unmap_notify(IOMMUNotifier
*n
, IOMMUTLBEntry
*iotlb
)
590 TCGIOMMUNotifier
*notifier
= container_of(n
, TCGIOMMUNotifier
, n
);
592 if (!notifier
->active
) {
595 tlb_flush(notifier
->cpu
);
596 notifier
->active
= false;
597 /* We leave the notifier struct on the list to avoid reallocating it later.
598 * Generally the number of IOMMUs a CPU deals with will be small.
599 * In any case we can't unregister the iommu notifier from a notify
604 static void tcg_register_iommu_notifier(CPUState
*cpu
,
605 IOMMUMemoryRegion
*iommu_mr
,
608 /* Make sure this CPU has an IOMMU notifier registered for this
609 * IOMMU/IOMMU index combination, so that we can flush its TLB
610 * when the IOMMU tells us the mappings we've cached have changed.
612 MemoryRegion
*mr
= MEMORY_REGION(iommu_mr
);
613 TCGIOMMUNotifier
*notifier
= NULL
;
616 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
617 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
618 if (notifier
->mr
== mr
&& notifier
->iommu_idx
== iommu_idx
) {
622 if (i
== cpu
->iommu_notifiers
->len
) {
623 /* Not found, add a new entry at the end of the array */
624 cpu
->iommu_notifiers
= g_array_set_size(cpu
->iommu_notifiers
, i
+ 1);
625 notifier
= g_new0(TCGIOMMUNotifier
, 1);
626 g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
) = notifier
;
629 notifier
->iommu_idx
= iommu_idx
;
631 /* Rather than trying to register interest in the specific part
632 * of the iommu's address space that we've accessed and then
633 * expand it later as subsequent accesses touch more of it, we
634 * just register interest in the whole thing, on the assumption
635 * that iommu reconfiguration will be rare.
637 iommu_notifier_init(¬ifier
->n
,
638 tcg_iommu_unmap_notify
,
639 IOMMU_NOTIFIER_UNMAP
,
643 memory_region_register_iommu_notifier(notifier
->mr
, ¬ifier
->n
,
647 if (!notifier
->active
) {
648 notifier
->active
= true;
652 void tcg_iommu_free_notifier_list(CPUState
*cpu
)
654 /* Destroy the CPU's notifier list */
656 TCGIOMMUNotifier
*notifier
;
658 for (i
= 0; i
< cpu
->iommu_notifiers
->len
; i
++) {
659 notifier
= g_array_index(cpu
->iommu_notifiers
, TCGIOMMUNotifier
*, i
);
660 memory_region_unregister_iommu_notifier(notifier
->mr
, ¬ifier
->n
);
663 g_array_free(cpu
->iommu_notifiers
, true);
666 void tcg_iommu_init_notifier_list(CPUState
*cpu
)
668 cpu
->iommu_notifiers
= g_array_new(false, true, sizeof(TCGIOMMUNotifier
*));
671 /* Called from RCU critical section */
672 MemoryRegionSection
*
673 address_space_translate_for_iotlb(CPUState
*cpu
, int asidx
, hwaddr orig_addr
,
674 hwaddr
*xlat
, hwaddr
*plen
,
675 MemTxAttrs attrs
, int *prot
)
677 MemoryRegionSection
*section
;
678 IOMMUMemoryRegion
*iommu_mr
;
679 IOMMUMemoryRegionClass
*imrc
;
682 hwaddr addr
= orig_addr
;
683 AddressSpaceDispatch
*d
= cpu
->cpu_ases
[asidx
].memory_dispatch
;
686 section
= address_space_translate_internal(d
, addr
, &addr
, plen
, false);
688 iommu_mr
= memory_region_get_iommu(section
->mr
);
693 imrc
= memory_region_get_iommu_class_nocheck(iommu_mr
);
695 iommu_idx
= imrc
->attrs_to_index(iommu_mr
, attrs
);
696 tcg_register_iommu_notifier(cpu
, iommu_mr
, iommu_idx
);
697 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
698 * doesn't short-cut its translation table walk.
700 iotlb
= imrc
->translate(iommu_mr
, addr
, IOMMU_NONE
, iommu_idx
);
701 addr
= ((iotlb
.translated_addr
& ~iotlb
.addr_mask
)
702 | (addr
& iotlb
.addr_mask
));
703 /* Update the caller's prot bits to remove permissions the IOMMU
704 * is giving us a failure response for. If we get down to no
705 * permissions left at all we can give up now.
707 if (!(iotlb
.perm
& IOMMU_RO
)) {
708 *prot
&= ~(PAGE_READ
| PAGE_EXEC
);
710 if (!(iotlb
.perm
& IOMMU_WO
)) {
711 *prot
&= ~PAGE_WRITE
;
718 d
= flatview_to_dispatch(address_space_to_flatview(iotlb
.target_as
));
721 assert(!memory_region_is_iommu(section
->mr
));
727 * We should be given a page-aligned address -- certainly
728 * tlb_set_page_with_attrs() does so. The page offset of xlat
729 * is used to index sections[], and PHYS_SECTION_UNASSIGNED = 0.
730 * The page portion of xlat will be logged by memory_region_access_valid()
731 * when this memory access is rejected, so use the original untranslated
734 assert((orig_addr
& ~TARGET_PAGE_MASK
) == 0);
736 return &d
->map
.sections
[PHYS_SECTION_UNASSIGNED
];
739 void cpu_address_space_init(CPUState
*cpu
, int asidx
,
740 const char *prefix
, MemoryRegion
*mr
)
742 CPUAddressSpace
*newas
;
743 AddressSpace
*as
= g_new0(AddressSpace
, 1);
747 as_name
= g_strdup_printf("%s-%d", prefix
, cpu
->cpu_index
);
748 address_space_init(as
, mr
, as_name
);
751 /* Target code should have set num_ases before calling us */
752 assert(asidx
< cpu
->num_ases
);
755 /* address space 0 gets the convenience alias */
759 /* KVM cannot currently support multiple address spaces. */
760 assert(asidx
== 0 || !kvm_enabled());
762 if (!cpu
->cpu_ases
) {
763 cpu
->cpu_ases
= g_new0(CPUAddressSpace
, cpu
->num_ases
);
766 newas
= &cpu
->cpu_ases
[asidx
];
770 newas
->tcg_as_listener
.log_global_after_sync
= tcg_log_global_after_sync
;
771 newas
->tcg_as_listener
.commit
= tcg_commit
;
772 newas
->tcg_as_listener
.name
= "tcg";
773 memory_listener_register(&newas
->tcg_as_listener
, as
);
777 AddressSpace
*cpu_get_address_space(CPUState
*cpu
, int asidx
)
779 /* Return the AddressSpace corresponding to the specified index */
780 return cpu
->cpu_ases
[asidx
].as
;
783 /* Called from RCU critical section */
784 static RAMBlock
*qemu_get_ram_block(ram_addr_t addr
)
788 block
= qatomic_rcu_read(&ram_list
.mru_block
);
789 if (block
&& addr
- block
->offset
< block
->max_length
) {
792 RAMBLOCK_FOREACH(block
) {
793 if (addr
- block
->offset
< block
->max_length
) {
798 fprintf(stderr
, "Bad ram offset %" PRIx64
"\n", (uint64_t)addr
);
802 /* It is safe to write mru_block outside the iothread lock. This
807 * xxx removed from list
811 * call_rcu(reclaim_ramblock, xxx);
814 * qatomic_rcu_set is not needed here. The block was already published
815 * when it was placed into the list. Here we're just making an extra
816 * copy of the pointer.
818 ram_list
.mru_block
= block
;
822 static void tlb_reset_dirty_range_all(ram_addr_t start
, ram_addr_t length
)
829 assert(tcg_enabled());
830 end
= TARGET_PAGE_ALIGN(start
+ length
);
831 start
&= TARGET_PAGE_MASK
;
833 RCU_READ_LOCK_GUARD();
834 block
= qemu_get_ram_block(start
);
835 assert(block
== qemu_get_ram_block(end
- 1));
836 start1
= (uintptr_t)ramblock_ptr(block
, start
- block
->offset
);
838 tlb_reset_dirty(cpu
, start1
, length
);
842 /* Note: start and end must be within the same ram block. */
843 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start
,
847 DirtyMemoryBlocks
*blocks
;
848 unsigned long end
, page
, start_page
;
851 uint64_t mr_offset
, mr_size
;
857 end
= TARGET_PAGE_ALIGN(start
+ length
) >> TARGET_PAGE_BITS
;
858 start_page
= start
>> TARGET_PAGE_BITS
;
861 WITH_RCU_READ_LOCK_GUARD() {
862 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
863 ramblock
= qemu_get_ram_block(start
);
864 /* Range sanity check on the ramblock */
865 assert(start
>= ramblock
->offset
&&
866 start
+ length
<= ramblock
->offset
+ ramblock
->used_length
);
869 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
870 unsigned long offset
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
871 unsigned long num
= MIN(end
- page
,
872 DIRTY_MEMORY_BLOCK_SIZE
- offset
);
874 dirty
|= bitmap_test_and_clear_atomic(blocks
->blocks
[idx
],
879 mr_offset
= (ram_addr_t
)(start_page
<< TARGET_PAGE_BITS
) - ramblock
->offset
;
880 mr_size
= (end
- start_page
) << TARGET_PAGE_BITS
;
881 memory_region_clear_dirty_bitmap(ramblock
->mr
, mr_offset
, mr_size
);
884 if (dirty
&& tcg_enabled()) {
885 tlb_reset_dirty_range_all(start
, length
);
891 DirtyBitmapSnapshot
*cpu_physical_memory_snapshot_and_clear_dirty
892 (MemoryRegion
*mr
, hwaddr offset
, hwaddr length
, unsigned client
)
894 DirtyMemoryBlocks
*blocks
;
895 ram_addr_t start
= memory_region_get_ram_addr(mr
) + offset
;
896 unsigned long align
= 1UL << (TARGET_PAGE_BITS
+ BITS_PER_LEVEL
);
897 ram_addr_t first
= QEMU_ALIGN_DOWN(start
, align
);
898 ram_addr_t last
= QEMU_ALIGN_UP(start
+ length
, align
);
899 DirtyBitmapSnapshot
*snap
;
900 unsigned long page
, end
, dest
;
902 snap
= g_malloc0(sizeof(*snap
) +
903 ((last
- first
) >> (TARGET_PAGE_BITS
+ 3)));
907 page
= first
>> TARGET_PAGE_BITS
;
908 end
= last
>> TARGET_PAGE_BITS
;
911 WITH_RCU_READ_LOCK_GUARD() {
912 blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[client
]);
915 unsigned long idx
= page
/ DIRTY_MEMORY_BLOCK_SIZE
;
916 unsigned long ofs
= page
% DIRTY_MEMORY_BLOCK_SIZE
;
917 unsigned long num
= MIN(end
- page
,
918 DIRTY_MEMORY_BLOCK_SIZE
- ofs
);
920 assert(QEMU_IS_ALIGNED(ofs
, (1 << BITS_PER_LEVEL
)));
921 assert(QEMU_IS_ALIGNED(num
, (1 << BITS_PER_LEVEL
)));
922 ofs
>>= BITS_PER_LEVEL
;
924 bitmap_copy_and_clear_atomic(snap
->dirty
+ dest
,
925 blocks
->blocks
[idx
] + ofs
,
928 dest
+= num
>> BITS_PER_LEVEL
;
933 tlb_reset_dirty_range_all(start
, length
);
936 memory_region_clear_dirty_bitmap(mr
, offset
, length
);
941 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot
*snap
,
945 unsigned long page
, end
;
947 assert(start
>= snap
->start
);
948 assert(start
+ length
<= snap
->end
);
950 end
= TARGET_PAGE_ALIGN(start
+ length
- snap
->start
) >> TARGET_PAGE_BITS
;
951 page
= (start
- snap
->start
) >> TARGET_PAGE_BITS
;
954 if (test_bit(page
, snap
->dirty
)) {
962 /* Called from RCU critical section */
963 hwaddr
memory_region_section_get_iotlb(CPUState
*cpu
,
964 MemoryRegionSection
*section
)
966 AddressSpaceDispatch
*d
= flatview_to_dispatch(section
->fv
);
967 return section
- d
->map
.sections
;
970 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
972 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
);
974 static uint16_t phys_section_add(PhysPageMap
*map
,
975 MemoryRegionSection
*section
)
977 /* The physical section number is ORed with a page-aligned
978 * pointer to produce the iotlb entries. Thus it should
979 * never overflow into the page-aligned value.
981 assert(map
->sections_nb
< TARGET_PAGE_SIZE
);
983 if (map
->sections_nb
== map
->sections_nb_alloc
) {
984 map
->sections_nb_alloc
= MAX(map
->sections_nb_alloc
* 2, 16);
985 map
->sections
= g_renew(MemoryRegionSection
, map
->sections
,
986 map
->sections_nb_alloc
);
988 map
->sections
[map
->sections_nb
] = *section
;
989 memory_region_ref(section
->mr
);
990 return map
->sections_nb
++;
993 static void phys_section_destroy(MemoryRegion
*mr
)
995 bool have_sub_page
= mr
->subpage
;
997 memory_region_unref(mr
);
1000 subpage_t
*subpage
= container_of(mr
, subpage_t
, iomem
);
1001 object_unref(OBJECT(&subpage
->iomem
));
1006 static void phys_sections_free(PhysPageMap
*map
)
1008 while (map
->sections_nb
> 0) {
1009 MemoryRegionSection
*section
= &map
->sections
[--map
->sections_nb
];
1010 phys_section_destroy(section
->mr
);
1012 g_free(map
->sections
);
1016 static void register_subpage(FlatView
*fv
, MemoryRegionSection
*section
)
1018 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1020 hwaddr base
= section
->offset_within_address_space
1022 MemoryRegionSection
*existing
= phys_page_find(d
, base
);
1023 MemoryRegionSection subsection
= {
1024 .offset_within_address_space
= base
,
1025 .size
= int128_make64(TARGET_PAGE_SIZE
),
1029 assert(existing
->mr
->subpage
|| existing
->mr
== &io_mem_unassigned
);
1031 if (!(existing
->mr
->subpage
)) {
1032 subpage
= subpage_init(fv
, base
);
1034 subsection
.mr
= &subpage
->iomem
;
1035 phys_page_set(d
, base
>> TARGET_PAGE_BITS
, 1,
1036 phys_section_add(&d
->map
, &subsection
));
1038 subpage
= container_of(existing
->mr
, subpage_t
, iomem
);
1040 start
= section
->offset_within_address_space
& ~TARGET_PAGE_MASK
;
1041 end
= start
+ int128_get64(section
->size
) - 1;
1042 subpage_register(subpage
, start
, end
,
1043 phys_section_add(&d
->map
, section
));
1047 static void register_multipage(FlatView
*fv
,
1048 MemoryRegionSection
*section
)
1050 AddressSpaceDispatch
*d
= flatview_to_dispatch(fv
);
1051 hwaddr start_addr
= section
->offset_within_address_space
;
1052 uint16_t section_index
= phys_section_add(&d
->map
, section
);
1053 uint64_t num_pages
= int128_get64(int128_rshift(section
->size
,
1057 phys_page_set(d
, start_addr
>> TARGET_PAGE_BITS
, num_pages
, section_index
);
1061 * The range in *section* may look like this:
1065 * where s stands for subpage and P for page.
1067 void flatview_add_to_dispatch(FlatView
*fv
, MemoryRegionSection
*section
)
1069 MemoryRegionSection remain
= *section
;
1070 Int128 page_size
= int128_make64(TARGET_PAGE_SIZE
);
1072 /* register first subpage */
1073 if (remain
.offset_within_address_space
& ~TARGET_PAGE_MASK
) {
1074 uint64_t left
= TARGET_PAGE_ALIGN(remain
.offset_within_address_space
)
1075 - remain
.offset_within_address_space
;
1077 MemoryRegionSection now
= remain
;
1078 now
.size
= int128_min(int128_make64(left
), now
.size
);
1079 register_subpage(fv
, &now
);
1080 if (int128_eq(remain
.size
, now
.size
)) {
1083 remain
.size
= int128_sub(remain
.size
, now
.size
);
1084 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1085 remain
.offset_within_region
+= int128_get64(now
.size
);
1088 /* register whole pages */
1089 if (int128_ge(remain
.size
, page_size
)) {
1090 MemoryRegionSection now
= remain
;
1091 now
.size
= int128_and(now
.size
, int128_neg(page_size
));
1092 register_multipage(fv
, &now
);
1093 if (int128_eq(remain
.size
, now
.size
)) {
1096 remain
.size
= int128_sub(remain
.size
, now
.size
);
1097 remain
.offset_within_address_space
+= int128_get64(now
.size
);
1098 remain
.offset_within_region
+= int128_get64(now
.size
);
1101 /* register last subpage */
1102 register_subpage(fv
, &remain
);
1105 void qemu_flush_coalesced_mmio_buffer(void)
1108 kvm_flush_coalesced_mmio_buffer();
1111 void qemu_mutex_lock_ramlist(void)
1113 qemu_mutex_lock(&ram_list
.mutex
);
1116 void qemu_mutex_unlock_ramlist(void)
1118 qemu_mutex_unlock(&ram_list
.mutex
);
1121 GString
*ram_block_format(void)
1125 GString
*buf
= g_string_new("");
1127 RCU_READ_LOCK_GUARD();
1128 g_string_append_printf(buf
, "%24s %8s %18s %18s %18s %18s %3s\n",
1129 "Block Name", "PSize", "Offset", "Used", "Total",
1132 RAMBLOCK_FOREACH(block
) {
1133 psize
= size_to_str(block
->page_size
);
1134 g_string_append_printf(buf
, "%24s %8s 0x%016" PRIx64
" 0x%016" PRIx64
1135 " 0x%016" PRIx64
" 0x%016" PRIx64
" %3s\n",
1136 block
->idstr
, psize
,
1137 (uint64_t)block
->offset
,
1138 (uint64_t)block
->used_length
,
1139 (uint64_t)block
->max_length
,
1140 (uint64_t)(uintptr_t)block
->host
,
1141 block
->mr
->readonly
? "ro" : "rw");
1149 static int find_min_backend_pagesize(Object
*obj
, void *opaque
)
1151 long *hpsize_min
= opaque
;
1153 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1154 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1155 long hpsize
= host_memory_backend_pagesize(backend
);
1157 if (host_memory_backend_is_mapped(backend
) && (hpsize
< *hpsize_min
)) {
1158 *hpsize_min
= hpsize
;
1165 static int find_max_backend_pagesize(Object
*obj
, void *opaque
)
1167 long *hpsize_max
= opaque
;
1169 if (object_dynamic_cast(obj
, TYPE_MEMORY_BACKEND
)) {
1170 HostMemoryBackend
*backend
= MEMORY_BACKEND(obj
);
1171 long hpsize
= host_memory_backend_pagesize(backend
);
1173 if (host_memory_backend_is_mapped(backend
) && (hpsize
> *hpsize_max
)) {
1174 *hpsize_max
= hpsize
;
1182 * TODO: We assume right now that all mapped host memory backends are
1183 * used as RAM, however some might be used for different purposes.
1185 long qemu_minrampagesize(void)
1187 long hpsize
= LONG_MAX
;
1188 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1190 object_child_foreach(memdev_root
, find_min_backend_pagesize
, &hpsize
);
1194 long qemu_maxrampagesize(void)
1197 Object
*memdev_root
= object_resolve_path("/objects", NULL
);
1199 object_child_foreach(memdev_root
, find_max_backend_pagesize
, &pagesize
);
1204 static int64_t get_file_size(int fd
)
1207 #if defined(__linux__)
1210 if (fstat(fd
, &st
) < 0) {
1214 /* Special handling for devdax character devices */
1215 if (S_ISCHR(st
.st_mode
)) {
1216 g_autofree
char *subsystem_path
= NULL
;
1217 g_autofree
char *subsystem
= NULL
;
1219 subsystem_path
= g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1220 major(st
.st_rdev
), minor(st
.st_rdev
));
1221 subsystem
= g_file_read_link(subsystem_path
, NULL
);
1223 if (subsystem
&& g_str_has_suffix(subsystem
, "/dax")) {
1224 g_autofree
char *size_path
= NULL
;
1225 g_autofree
char *size_str
= NULL
;
1227 size_path
= g_strdup_printf("/sys/dev/char/%d:%d/size",
1228 major(st
.st_rdev
), minor(st
.st_rdev
));
1230 if (g_file_get_contents(size_path
, &size_str
, NULL
, NULL
)) {
1231 return g_ascii_strtoll(size_str
, NULL
, 0);
1235 #endif /* defined(__linux__) */
1237 /* st.st_size may be zero for special files yet lseek(2) works */
1238 size
= lseek(fd
, 0, SEEK_END
);
1245 static int64_t get_file_align(int fd
)
1248 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1251 if (fstat(fd
, &st
) < 0) {
1255 /* Special handling for devdax character devices */
1256 if (S_ISCHR(st
.st_mode
)) {
1257 g_autofree
char *path
= NULL
;
1258 g_autofree
char *rpath
= NULL
;
1259 struct daxctl_ctx
*ctx
;
1260 struct daxctl_region
*region
;
1263 path
= g_strdup_printf("/sys/dev/char/%d:%d",
1264 major(st
.st_rdev
), minor(st
.st_rdev
));
1265 rpath
= realpath(path
, NULL
);
1270 rc
= daxctl_new(&ctx
);
1275 daxctl_region_foreach(ctx
, region
) {
1276 if (strstr(rpath
, daxctl_region_get_path(region
))) {
1277 align
= daxctl_region_get_align(region
);
1283 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1288 static int file_ram_open(const char *path
,
1289 const char *region_name
,
1294 char *sanitized_name
;
1300 fd
= open(path
, readonly
? O_RDONLY
: O_RDWR
);
1303 * open(O_RDONLY) won't fail with EISDIR. Check manually if we
1304 * opened a directory and fail similarly to how we fail ENOENT
1305 * in readonly mode. Note that mkstemp() would imply O_RDWR.
1308 struct stat file_stat
;
1310 if (fstat(fd
, &file_stat
)) {
1312 if (errno
== EINTR
) {
1316 } else if (S_ISDIR(file_stat
.st_mode
)) {
1321 /* @path names an existing file, use it */
1324 if (errno
== ENOENT
) {
1326 /* Refuse to create new, readonly files. */
1329 /* @path names a file that doesn't exist, create it */
1330 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0644);
1335 } else if (errno
== EISDIR
) {
1336 /* @path names a directory, create a file there */
1337 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1338 sanitized_name
= g_strdup(region_name
);
1339 for (c
= sanitized_name
; *c
!= '\0'; c
++) {
1345 filename
= g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path
,
1347 g_free(sanitized_name
);
1349 fd
= mkstemp(filename
);
1357 if (errno
!= EEXIST
&& errno
!= EINTR
) {
1361 * Try again on EINTR and EEXIST. The latter happens when
1362 * something else creates the file between our two open().
1369 static void *file_ram_alloc(RAMBlock
*block
,
1376 uint32_t qemu_map_flags
;
1379 block
->page_size
= qemu_fd_getpagesize(fd
);
1380 if (block
->mr
->align
% block
->page_size
) {
1381 error_setg(errp
, "alignment 0x%" PRIx64
1382 " must be multiples of page size 0x%zx",
1383 block
->mr
->align
, block
->page_size
);
1385 } else if (block
->mr
->align
&& !is_power_of_2(block
->mr
->align
)) {
1386 error_setg(errp
, "alignment 0x%" PRIx64
1387 " must be a power of two", block
->mr
->align
);
1389 } else if (offset
% block
->page_size
) {
1390 error_setg(errp
, "offset 0x%" PRIx64
1391 " must be multiples of page size 0x%zx",
1392 offset
, block
->page_size
);
1395 block
->mr
->align
= MAX(block
->page_size
, block
->mr
->align
);
1396 #if defined(__s390x__)
1397 if (kvm_enabled()) {
1398 block
->mr
->align
= MAX(block
->mr
->align
, QEMU_VMALLOC_ALIGN
);
1402 if (memory
< block
->page_size
) {
1403 error_setg(errp
, "memory size 0x" RAM_ADDR_FMT
" must be equal to "
1404 "or larger than page size 0x%zx",
1405 memory
, block
->page_size
);
1409 memory
= ROUND_UP(memory
, block
->page_size
);
1412 * ftruncate is not supported by hugetlbfs in older
1413 * hosts, so don't bother bailing out on errors.
1414 * If anything goes wrong with it under other filesystems,
1417 * Do not truncate the non-empty backend file to avoid corrupting
1418 * the existing data in the file. Disabling shrinking is not
1419 * enough. For example, the current vNVDIMM implementation stores
1420 * the guest NVDIMM labels at the end of the backend file. If the
1421 * backend file is later extended, QEMU will not be able to find
1422 * those labels. Therefore, extending the non-empty backend file
1423 * is disabled as well.
1425 if (truncate
&& ftruncate(fd
, offset
+ memory
)) {
1426 perror("ftruncate");
1429 qemu_map_flags
= (block
->flags
& RAM_READONLY
) ? QEMU_MAP_READONLY
: 0;
1430 qemu_map_flags
|= (block
->flags
& RAM_SHARED
) ? QEMU_MAP_SHARED
: 0;
1431 qemu_map_flags
|= (block
->flags
& RAM_PMEM
) ? QEMU_MAP_SYNC
: 0;
1432 qemu_map_flags
|= (block
->flags
& RAM_NORESERVE
) ? QEMU_MAP_NORESERVE
: 0;
1433 area
= qemu_ram_mmap(fd
, memory
, block
->mr
->align
, qemu_map_flags
, offset
);
1434 if (area
== MAP_FAILED
) {
1435 error_setg_errno(errp
, errno
,
1436 "unable to map backing store for guest RAM");
1441 block
->fd_offset
= offset
;
1446 /* Allocate space within the ram_addr_t space that governs the
1448 * Called with the ramlist lock held.
1450 static ram_addr_t
find_ram_offset(ram_addr_t size
)
1452 RAMBlock
*block
, *next_block
;
1453 ram_addr_t offset
= RAM_ADDR_MAX
, mingap
= RAM_ADDR_MAX
;
1455 assert(size
!= 0); /* it would hand out same offset multiple times */
1457 if (QLIST_EMPTY_RCU(&ram_list
.blocks
)) {
1461 RAMBLOCK_FOREACH(block
) {
1462 ram_addr_t candidate
, next
= RAM_ADDR_MAX
;
1464 /* Align blocks to start on a 'long' in the bitmap
1465 * which makes the bitmap sync'ing take the fast path.
1467 candidate
= block
->offset
+ block
->max_length
;
1468 candidate
= ROUND_UP(candidate
, BITS_PER_LONG
<< TARGET_PAGE_BITS
);
1470 /* Search for the closest following block
1473 RAMBLOCK_FOREACH(next_block
) {
1474 if (next_block
->offset
>= candidate
) {
1475 next
= MIN(next
, next_block
->offset
);
1479 /* If it fits remember our place and remember the size
1480 * of gap, but keep going so that we might find a smaller
1481 * gap to fill so avoiding fragmentation.
1483 if (next
- candidate
>= size
&& next
- candidate
< mingap
) {
1485 mingap
= next
- candidate
;
1488 trace_find_ram_offset_loop(size
, candidate
, offset
, next
, mingap
);
1491 if (offset
== RAM_ADDR_MAX
) {
1492 fprintf(stderr
, "Failed to find gap of requested size: %" PRIu64
"\n",
1497 trace_find_ram_offset(size
, offset
);
1502 static unsigned long last_ram_page(void)
1505 ram_addr_t last
= 0;
1507 RCU_READ_LOCK_GUARD();
1508 RAMBLOCK_FOREACH(block
) {
1509 last
= MAX(last
, block
->offset
+ block
->max_length
);
1511 return last
>> TARGET_PAGE_BITS
;
1514 static void qemu_ram_setup_dump(void *addr
, ram_addr_t size
)
1518 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1519 if (!machine_dump_guest_core(current_machine
)) {
1520 ret
= qemu_madvise(addr
, size
, QEMU_MADV_DONTDUMP
);
1522 perror("qemu_madvise");
1523 fprintf(stderr
, "madvise doesn't support MADV_DONTDUMP, "
1524 "but dump_guest_core=off specified\n");
1529 const char *qemu_ram_get_idstr(RAMBlock
*rb
)
1534 void *qemu_ram_get_host_addr(RAMBlock
*rb
)
1539 ram_addr_t
qemu_ram_get_offset(RAMBlock
*rb
)
1544 ram_addr_t
qemu_ram_get_used_length(RAMBlock
*rb
)
1546 return rb
->used_length
;
1549 ram_addr_t
qemu_ram_get_max_length(RAMBlock
*rb
)
1551 return rb
->max_length
;
1554 bool qemu_ram_is_shared(RAMBlock
*rb
)
1556 return rb
->flags
& RAM_SHARED
;
1559 bool qemu_ram_is_noreserve(RAMBlock
*rb
)
1561 return rb
->flags
& RAM_NORESERVE
;
1564 /* Note: Only set at the start of postcopy */
1565 bool qemu_ram_is_uf_zeroable(RAMBlock
*rb
)
1567 return rb
->flags
& RAM_UF_ZEROPAGE
;
1570 void qemu_ram_set_uf_zeroable(RAMBlock
*rb
)
1572 rb
->flags
|= RAM_UF_ZEROPAGE
;
1575 bool qemu_ram_is_migratable(RAMBlock
*rb
)
1577 return rb
->flags
& RAM_MIGRATABLE
;
1580 void qemu_ram_set_migratable(RAMBlock
*rb
)
1582 rb
->flags
|= RAM_MIGRATABLE
;
1585 void qemu_ram_unset_migratable(RAMBlock
*rb
)
1587 rb
->flags
&= ~RAM_MIGRATABLE
;
1590 bool qemu_ram_is_named_file(RAMBlock
*rb
)
1592 return rb
->flags
& RAM_NAMED_FILE
;
1595 int qemu_ram_get_fd(RAMBlock
*rb
)
1600 /* Called with iothread lock held. */
1601 void qemu_ram_set_idstr(RAMBlock
*new_block
, const char *name
, DeviceState
*dev
)
1606 assert(!new_block
->idstr
[0]);
1609 char *id
= qdev_get_dev_path(dev
);
1611 snprintf(new_block
->idstr
, sizeof(new_block
->idstr
), "%s/", id
);
1615 pstrcat(new_block
->idstr
, sizeof(new_block
->idstr
), name
);
1617 RCU_READ_LOCK_GUARD();
1618 RAMBLOCK_FOREACH(block
) {
1619 if (block
!= new_block
&&
1620 !strcmp(block
->idstr
, new_block
->idstr
)) {
1621 fprintf(stderr
, "RAMBlock \"%s\" already registered, abort!\n",
1628 /* Called with iothread lock held. */
1629 void qemu_ram_unset_idstr(RAMBlock
*block
)
1631 /* FIXME: arch_init.c assumes that this is not called throughout
1632 * migration. Ignore the problem since hot-unplug during migration
1633 * does not work anyway.
1636 memset(block
->idstr
, 0, sizeof(block
->idstr
));
1640 size_t qemu_ram_pagesize(RAMBlock
*rb
)
1642 return rb
->page_size
;
1645 /* Returns the largest size of page in use */
1646 size_t qemu_ram_pagesize_largest(void)
1651 RAMBLOCK_FOREACH(block
) {
1652 largest
= MAX(largest
, qemu_ram_pagesize(block
));
1658 static int memory_try_enable_merging(void *addr
, size_t len
)
1660 if (!machine_mem_merge(current_machine
)) {
1661 /* disabled by the user */
1665 return qemu_madvise(addr
, len
, QEMU_MADV_MERGEABLE
);
1669 * Resizing RAM while migrating can result in the migration being canceled.
1670 * Care has to be taken if the guest might have already detected the memory.
1672 * As memory core doesn't know how is memory accessed, it is up to
1673 * resize callback to update device state and/or add assertions to detect
1674 * misuse, if necessary.
1676 int qemu_ram_resize(RAMBlock
*block
, ram_addr_t newsize
, Error
**errp
)
1678 const ram_addr_t oldsize
= block
->used_length
;
1679 const ram_addr_t unaligned_size
= newsize
;
1683 newsize
= HOST_PAGE_ALIGN(newsize
);
1685 if (block
->used_length
== newsize
) {
1687 * We don't have to resize the ram block (which only knows aligned
1688 * sizes), however, we have to notify if the unaligned size changed.
1690 if (unaligned_size
!= memory_region_size(block
->mr
)) {
1691 memory_region_set_size(block
->mr
, unaligned_size
);
1692 if (block
->resized
) {
1693 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1699 if (!(block
->flags
& RAM_RESIZEABLE
)) {
1700 error_setg_errno(errp
, EINVAL
,
1701 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1702 " != 0x" RAM_ADDR_FMT
, block
->idstr
,
1703 newsize
, block
->used_length
);
1707 if (block
->max_length
< newsize
) {
1708 error_setg_errno(errp
, EINVAL
,
1709 "Size too large: %s: 0x" RAM_ADDR_FMT
1710 " > 0x" RAM_ADDR_FMT
, block
->idstr
,
1711 newsize
, block
->max_length
);
1715 /* Notify before modifying the ram block and touching the bitmaps. */
1717 ram_block_notify_resize(block
->host
, oldsize
, newsize
);
1720 cpu_physical_memory_clear_dirty_range(block
->offset
, block
->used_length
);
1721 block
->used_length
= newsize
;
1722 cpu_physical_memory_set_dirty_range(block
->offset
, block
->used_length
,
1724 memory_region_set_size(block
->mr
, unaligned_size
);
1725 if (block
->resized
) {
1726 block
->resized(block
->idstr
, unaligned_size
, block
->host
);
1732 * Trigger sync on the given ram block for range [start, start + length]
1733 * with the backing store if one is available.
1735 * @Note: this is supposed to be a synchronous op.
1737 void qemu_ram_msync(RAMBlock
*block
, ram_addr_t start
, ram_addr_t length
)
1739 /* The requested range should fit in within the block range */
1740 g_assert((start
+ length
) <= block
->used_length
);
1742 #ifdef CONFIG_LIBPMEM
1743 /* The lack of support for pmem should not block the sync */
1744 if (ramblock_is_pmem(block
)) {
1745 void *addr
= ramblock_ptr(block
, start
);
1746 pmem_persist(addr
, length
);
1750 if (block
->fd
>= 0) {
1752 * Case there is no support for PMEM or the memory has not been
1753 * specified as persistent (or is not one) - use the msync.
1754 * Less optimal but still achieves the same goal
1756 void *addr
= ramblock_ptr(block
, start
);
1757 if (qemu_msync(addr
, length
, block
->fd
)) {
1758 warn_report("%s: failed to sync memory range: start: "
1759 RAM_ADDR_FMT
" length: " RAM_ADDR_FMT
,
1760 __func__
, start
, length
);
1765 /* Called with ram_list.mutex held */
1766 static void dirty_memory_extend(ram_addr_t old_ram_size
,
1767 ram_addr_t new_ram_size
)
1769 ram_addr_t old_num_blocks
= DIV_ROUND_UP(old_ram_size
,
1770 DIRTY_MEMORY_BLOCK_SIZE
);
1771 ram_addr_t new_num_blocks
= DIV_ROUND_UP(new_ram_size
,
1772 DIRTY_MEMORY_BLOCK_SIZE
);
1775 /* Only need to extend if block count increased */
1776 if (new_num_blocks
<= old_num_blocks
) {
1780 for (i
= 0; i
< DIRTY_MEMORY_NUM
; i
++) {
1781 DirtyMemoryBlocks
*old_blocks
;
1782 DirtyMemoryBlocks
*new_blocks
;
1785 old_blocks
= qatomic_rcu_read(&ram_list
.dirty_memory
[i
]);
1786 new_blocks
= g_malloc(sizeof(*new_blocks
) +
1787 sizeof(new_blocks
->blocks
[0]) * new_num_blocks
);
1789 if (old_num_blocks
) {
1790 memcpy(new_blocks
->blocks
, old_blocks
->blocks
,
1791 old_num_blocks
* sizeof(old_blocks
->blocks
[0]));
1794 for (j
= old_num_blocks
; j
< new_num_blocks
; j
++) {
1795 new_blocks
->blocks
[j
] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE
);
1798 qatomic_rcu_set(&ram_list
.dirty_memory
[i
], new_blocks
);
1801 g_free_rcu(old_blocks
, rcu
);
1806 static void ram_block_add(RAMBlock
*new_block
, Error
**errp
)
1808 const bool noreserve
= qemu_ram_is_noreserve(new_block
);
1809 const bool shared
= qemu_ram_is_shared(new_block
);
1811 RAMBlock
*last_block
= NULL
;
1812 ram_addr_t old_ram_size
, new_ram_size
;
1815 old_ram_size
= last_ram_page();
1817 qemu_mutex_lock_ramlist();
1818 new_block
->offset
= find_ram_offset(new_block
->max_length
);
1820 if (!new_block
->host
) {
1821 if (xen_enabled()) {
1822 xen_ram_alloc(new_block
->offset
, new_block
->max_length
,
1823 new_block
->mr
, &err
);
1825 error_propagate(errp
, err
);
1826 qemu_mutex_unlock_ramlist();
1830 new_block
->host
= qemu_anon_ram_alloc(new_block
->max_length
,
1831 &new_block
->mr
->align
,
1833 if (!new_block
->host
) {
1834 error_setg_errno(errp
, errno
,
1835 "cannot set up guest memory '%s'",
1836 memory_region_name(new_block
->mr
));
1837 qemu_mutex_unlock_ramlist();
1840 memory_try_enable_merging(new_block
->host
, new_block
->max_length
);
1844 new_ram_size
= MAX(old_ram_size
,
1845 (new_block
->offset
+ new_block
->max_length
) >> TARGET_PAGE_BITS
);
1846 if (new_ram_size
> old_ram_size
) {
1847 dirty_memory_extend(old_ram_size
, new_ram_size
);
1849 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1850 * QLIST (which has an RCU-friendly variant) does not have insertion at
1851 * tail, so save the last element in last_block.
1853 RAMBLOCK_FOREACH(block
) {
1855 if (block
->max_length
< new_block
->max_length
) {
1860 QLIST_INSERT_BEFORE_RCU(block
, new_block
, next
);
1861 } else if (last_block
) {
1862 QLIST_INSERT_AFTER_RCU(last_block
, new_block
, next
);
1863 } else { /* list is empty */
1864 QLIST_INSERT_HEAD_RCU(&ram_list
.blocks
, new_block
, next
);
1866 ram_list
.mru_block
= NULL
;
1868 /* Write list before version */
1871 qemu_mutex_unlock_ramlist();
1873 cpu_physical_memory_set_dirty_range(new_block
->offset
,
1874 new_block
->used_length
,
1877 if (new_block
->host
) {
1878 qemu_ram_setup_dump(new_block
->host
, new_block
->max_length
);
1879 qemu_madvise(new_block
->host
, new_block
->max_length
, QEMU_MADV_HUGEPAGE
);
1881 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
1882 * Configure it unless the machine is a qtest server, in which case
1883 * KVM is not used and it may be forked (eg for fuzzing purposes).
1885 if (!qtest_enabled()) {
1886 qemu_madvise(new_block
->host
, new_block
->max_length
,
1887 QEMU_MADV_DONTFORK
);
1889 ram_block_notify_add(new_block
->host
, new_block
->used_length
,
1890 new_block
->max_length
);
1895 RAMBlock
*qemu_ram_alloc_from_fd(ram_addr_t size
, MemoryRegion
*mr
,
1896 uint32_t ram_flags
, int fd
, off_t offset
,
1899 RAMBlock
*new_block
;
1900 Error
*local_err
= NULL
;
1901 int64_t file_size
, file_align
;
1903 /* Just support these ram flags by now. */
1904 assert((ram_flags
& ~(RAM_SHARED
| RAM_PMEM
| RAM_NORESERVE
|
1905 RAM_PROTECTED
| RAM_NAMED_FILE
| RAM_READONLY
|
1906 RAM_READONLY_FD
)) == 0);
1908 if (xen_enabled()) {
1909 error_setg(errp
, "-mem-path not supported with Xen");
1913 if (kvm_enabled() && !kvm_has_sync_mmu()) {
1915 "host lacks kvm mmu notifiers, -mem-path unsupported");
1919 size
= HOST_PAGE_ALIGN(size
);
1920 file_size
= get_file_size(fd
);
1921 if (file_size
> offset
&& file_size
< (offset
+ size
)) {
1922 error_setg(errp
, "backing store size 0x%" PRIx64
1923 " does not match 'size' option 0x" RAM_ADDR_FMT
,
1928 file_align
= get_file_align(fd
);
1929 if (file_align
> 0 && file_align
> mr
->align
) {
1930 error_setg(errp
, "backing store align 0x%" PRIx64
1931 " is larger than 'align' option 0x%" PRIx64
,
1932 file_align
, mr
->align
);
1936 new_block
= g_malloc0(sizeof(*new_block
));
1938 new_block
->used_length
= size
;
1939 new_block
->max_length
= size
;
1940 new_block
->flags
= ram_flags
;
1941 new_block
->host
= file_ram_alloc(new_block
, size
, fd
, !file_size
, offset
,
1943 if (!new_block
->host
) {
1948 ram_block_add(new_block
, &local_err
);
1951 error_propagate(errp
, local_err
);
1959 RAMBlock
*qemu_ram_alloc_from_file(ram_addr_t size
, MemoryRegion
*mr
,
1960 uint32_t ram_flags
, const char *mem_path
,
1961 off_t offset
, Error
**errp
)
1967 fd
= file_ram_open(mem_path
, memory_region_name(mr
),
1968 !!(ram_flags
& RAM_READONLY_FD
), &created
);
1970 error_setg_errno(errp
, -fd
, "can't open backing store %s for guest RAM",
1972 if (!(ram_flags
& RAM_READONLY_FD
) && !(ram_flags
& RAM_SHARED
) &&
1975 * If we can open the file R/O (note: will never create a new file)
1976 * and we are dealing with a private mapping, there are still ways
1977 * to consume such files and get RAM instead of ROM.
1979 fd
= file_ram_open(mem_path
, memory_region_name(mr
), true,
1986 error_append_hint(errp
, "Consider opening the backing store"
1987 " read-only but still creating writable RAM using"
1988 " '-object memory-backend-file,readonly=on,rom=off...'"
1989 " (see \"VM templating\" documentation)\n");
1994 block
= qemu_ram_alloc_from_fd(size
, mr
, ram_flags
, fd
, offset
, errp
);
2008 RAMBlock
*qemu_ram_alloc_internal(ram_addr_t size
, ram_addr_t max_size
,
2009 void (*resized
)(const char*,
2012 void *host
, uint32_t ram_flags
,
2013 MemoryRegion
*mr
, Error
**errp
)
2015 RAMBlock
*new_block
;
2016 Error
*local_err
= NULL
;
2018 assert((ram_flags
& ~(RAM_SHARED
| RAM_RESIZEABLE
| RAM_PREALLOC
|
2019 RAM_NORESERVE
)) == 0);
2020 assert(!host
^ (ram_flags
& RAM_PREALLOC
));
2022 size
= HOST_PAGE_ALIGN(size
);
2023 max_size
= HOST_PAGE_ALIGN(max_size
);
2024 new_block
= g_malloc0(sizeof(*new_block
));
2026 new_block
->resized
= resized
;
2027 new_block
->used_length
= size
;
2028 new_block
->max_length
= max_size
;
2029 assert(max_size
>= size
);
2031 new_block
->page_size
= qemu_real_host_page_size();
2032 new_block
->host
= host
;
2033 new_block
->flags
= ram_flags
;
2034 ram_block_add(new_block
, &local_err
);
2037 error_propagate(errp
, local_err
);
2043 RAMBlock
*qemu_ram_alloc_from_ptr(ram_addr_t size
, void *host
,
2044 MemoryRegion
*mr
, Error
**errp
)
2046 return qemu_ram_alloc_internal(size
, size
, NULL
, host
, RAM_PREALLOC
, mr
,
2050 RAMBlock
*qemu_ram_alloc(ram_addr_t size
, uint32_t ram_flags
,
2051 MemoryRegion
*mr
, Error
**errp
)
2053 assert((ram_flags
& ~(RAM_SHARED
| RAM_NORESERVE
)) == 0);
2054 return qemu_ram_alloc_internal(size
, size
, NULL
, NULL
, ram_flags
, mr
, errp
);
2057 RAMBlock
*qemu_ram_alloc_resizeable(ram_addr_t size
, ram_addr_t maxsz
,
2058 void (*resized
)(const char*,
2061 MemoryRegion
*mr
, Error
**errp
)
2063 return qemu_ram_alloc_internal(size
, maxsz
, resized
, NULL
,
2064 RAM_RESIZEABLE
, mr
, errp
);
2067 static void reclaim_ramblock(RAMBlock
*block
)
2069 if (block
->flags
& RAM_PREALLOC
) {
2071 } else if (xen_enabled()) {
2072 xen_invalidate_map_cache_entry(block
->host
);
2074 } else if (block
->fd
>= 0) {
2075 qemu_ram_munmap(block
->fd
, block
->host
, block
->max_length
);
2079 qemu_anon_ram_free(block
->host
, block
->max_length
);
2084 void qemu_ram_free(RAMBlock
*block
)
2091 ram_block_notify_remove(block
->host
, block
->used_length
,
2095 qemu_mutex_lock_ramlist();
2096 QLIST_REMOVE_RCU(block
, next
);
2097 ram_list
.mru_block
= NULL
;
2098 /* Write list before version */
2101 call_rcu(block
, reclaim_ramblock
, rcu
);
2102 qemu_mutex_unlock_ramlist();
2106 void qemu_ram_remap(ram_addr_t addr
, ram_addr_t length
)
2114 RAMBLOCK_FOREACH(block
) {
2115 offset
= addr
- block
->offset
;
2116 if (offset
< block
->max_length
) {
2117 vaddr
= ramblock_ptr(block
, offset
);
2118 if (block
->flags
& RAM_PREALLOC
) {
2120 } else if (xen_enabled()) {
2124 flags
|= block
->flags
& RAM_SHARED
?
2125 MAP_SHARED
: MAP_PRIVATE
;
2126 flags
|= block
->flags
& RAM_NORESERVE
? MAP_NORESERVE
: 0;
2128 prot
|= block
->flags
& RAM_READONLY
? 0 : PROT_WRITE
;
2129 if (block
->fd
>= 0) {
2130 area
= mmap(vaddr
, length
, prot
, flags
, block
->fd
,
2131 offset
+ block
->fd_offset
);
2133 flags
|= MAP_ANONYMOUS
;
2134 area
= mmap(vaddr
, length
, prot
, flags
, -1, 0);
2136 if (area
!= vaddr
) {
2137 error_report("Could not remap addr: "
2138 RAM_ADDR_FMT
"@" RAM_ADDR_FMT
"",
2142 memory_try_enable_merging(vaddr
, length
);
2143 qemu_ram_setup_dump(vaddr
, length
);
2148 #endif /* !_WIN32 */
2150 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2151 * This should not be used for general purpose DMA. Use address_space_map
2152 * or address_space_rw instead. For local memory (e.g. video ram) that the
2153 * device owns, use memory_region_get_ram_ptr.
2155 * Called within RCU critical section.
2157 void *qemu_map_ram_ptr(RAMBlock
*ram_block
, ram_addr_t addr
)
2159 RAMBlock
*block
= ram_block
;
2161 if (block
== NULL
) {
2162 block
= qemu_get_ram_block(addr
);
2163 addr
-= block
->offset
;
2166 if (xen_enabled() && block
->host
== NULL
) {
2167 /* We need to check if the requested address is in the RAM
2168 * because we don't want to map the entire memory in QEMU.
2169 * In that case just map until the end of the page.
2171 if (block
->offset
== 0) {
2172 return xen_map_cache(addr
, 0, 0, false);
2175 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, false);
2177 return ramblock_ptr(block
, addr
);
2180 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2181 * but takes a size argument.
2183 * Called within RCU critical section.
2185 static void *qemu_ram_ptr_length(RAMBlock
*ram_block
, ram_addr_t addr
,
2186 hwaddr
*size
, bool lock
)
2188 RAMBlock
*block
= ram_block
;
2193 if (block
== NULL
) {
2194 block
= qemu_get_ram_block(addr
);
2195 addr
-= block
->offset
;
2197 *size
= MIN(*size
, block
->max_length
- addr
);
2199 if (xen_enabled() && block
->host
== NULL
) {
2200 /* We need to check if the requested address is in the RAM
2201 * because we don't want to map the entire memory in QEMU.
2202 * In that case just map the requested area.
2204 if (block
->offset
== 0) {
2205 return xen_map_cache(addr
, *size
, lock
, lock
);
2208 block
->host
= xen_map_cache(block
->offset
, block
->max_length
, 1, lock
);
2211 return ramblock_ptr(block
, addr
);
2214 /* Return the offset of a hostpointer within a ramblock */
2215 ram_addr_t
qemu_ram_block_host_offset(RAMBlock
*rb
, void *host
)
2217 ram_addr_t res
= (uint8_t *)host
- (uint8_t *)rb
->host
;
2218 assert((uintptr_t)host
>= (uintptr_t)rb
->host
);
2219 assert(res
< rb
->max_length
);
2225 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2228 * ptr: Host pointer to look up
2229 * round_offset: If true round the result offset down to a page boundary
2230 * *ram_addr: set to result ram_addr
2231 * *offset: set to result offset within the RAMBlock
2233 * Returns: RAMBlock (or NULL if not found)
2235 * By the time this function returns, the returned pointer is not protected
2236 * by RCU anymore. If the caller is not within an RCU critical section and
2237 * does not hold the iothread lock, it must have other means of protecting the
2238 * pointer, such as a reference to the region that includes the incoming
2241 RAMBlock
*qemu_ram_block_from_host(void *ptr
, bool round_offset
,
2245 uint8_t *host
= ptr
;
2247 if (xen_enabled()) {
2248 ram_addr_t ram_addr
;
2249 RCU_READ_LOCK_GUARD();
2250 ram_addr
= xen_ram_addr_from_mapcache(ptr
);
2251 block
= qemu_get_ram_block(ram_addr
);
2253 *offset
= ram_addr
- block
->offset
;
2258 RCU_READ_LOCK_GUARD();
2259 block
= qatomic_rcu_read(&ram_list
.mru_block
);
2260 if (block
&& block
->host
&& host
- block
->host
< block
->max_length
) {
2264 RAMBLOCK_FOREACH(block
) {
2265 /* This case append when the block is not mapped. */
2266 if (block
->host
== NULL
) {
2269 if (host
- block
->host
< block
->max_length
) {
2277 *offset
= (host
- block
->host
);
2279 *offset
&= TARGET_PAGE_MASK
;
2285 * Finds the named RAMBlock
2287 * name: The name of RAMBlock to find
2289 * Returns: RAMBlock (or NULL if not found)
2291 RAMBlock
*qemu_ram_block_by_name(const char *name
)
2295 RAMBLOCK_FOREACH(block
) {
2296 if (!strcmp(name
, block
->idstr
)) {
2305 * Some of the system routines need to translate from a host pointer
2306 * (typically a TLB entry) back to a ram offset.
2308 ram_addr_t
qemu_ram_addr_from_host(void *ptr
)
2313 block
= qemu_ram_block_from_host(ptr
, false, &offset
);
2315 return RAM_ADDR_INVALID
;
2318 return block
->offset
+ offset
;
2321 ram_addr_t
qemu_ram_addr_from_host_nofail(void *ptr
)
2323 ram_addr_t ram_addr
;
2325 ram_addr
= qemu_ram_addr_from_host(ptr
);
2326 if (ram_addr
== RAM_ADDR_INVALID
) {
2327 error_report("Bad ram pointer %p", ptr
);
2333 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2334 MemTxAttrs attrs
, void *buf
, hwaddr len
);
2335 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2336 const void *buf
, hwaddr len
);
2337 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
2338 bool is_write
, MemTxAttrs attrs
);
2340 static MemTxResult
subpage_read(void *opaque
, hwaddr addr
, uint64_t *data
,
2341 unsigned len
, MemTxAttrs attrs
)
2343 subpage_t
*subpage
= opaque
;
2347 #if defined(DEBUG_SUBPAGE)
2348 printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
"\n", __func__
,
2349 subpage
, len
, addr
);
2351 res
= flatview_read(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2355 *data
= ldn_p(buf
, len
);
2359 static MemTxResult
subpage_write(void *opaque
, hwaddr addr
,
2360 uint64_t value
, unsigned len
, MemTxAttrs attrs
)
2362 subpage_t
*subpage
= opaque
;
2365 #if defined(DEBUG_SUBPAGE)
2366 printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
2367 " value %"PRIx64
"\n",
2368 __func__
, subpage
, len
, addr
, value
);
2370 stn_p(buf
, len
, value
);
2371 return flatview_write(subpage
->fv
, addr
+ subpage
->base
, attrs
, buf
, len
);
2374 static bool subpage_accepts(void *opaque
, hwaddr addr
,
2375 unsigned len
, bool is_write
,
2378 subpage_t
*subpage
= opaque
;
2379 #if defined(DEBUG_SUBPAGE)
2380 printf("%s: subpage %p %c len %u addr " HWADDR_FMT_plx
"\n",
2381 __func__
, subpage
, is_write
? 'w' : 'r', len
, addr
);
2384 return flatview_access_valid(subpage
->fv
, addr
+ subpage
->base
,
2385 len
, is_write
, attrs
);
2388 static const MemoryRegionOps subpage_ops
= {
2389 .read_with_attrs
= subpage_read
,
2390 .write_with_attrs
= subpage_write
,
2391 .impl
.min_access_size
= 1,
2392 .impl
.max_access_size
= 8,
2393 .valid
.min_access_size
= 1,
2394 .valid
.max_access_size
= 8,
2395 .valid
.accepts
= subpage_accepts
,
2396 .endianness
= DEVICE_NATIVE_ENDIAN
,
2399 static int subpage_register(subpage_t
*mmio
, uint32_t start
, uint32_t end
,
2404 if (start
>= TARGET_PAGE_SIZE
|| end
>= TARGET_PAGE_SIZE
)
2406 idx
= SUBPAGE_IDX(start
);
2407 eidx
= SUBPAGE_IDX(end
);
2408 #if defined(DEBUG_SUBPAGE)
2409 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2410 __func__
, mmio
, start
, end
, idx
, eidx
, section
);
2412 for (; idx
<= eidx
; idx
++) {
2413 mmio
->sub_section
[idx
] = section
;
2419 static subpage_t
*subpage_init(FlatView
*fv
, hwaddr base
)
2423 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2424 mmio
= g_malloc0(sizeof(subpage_t
) + TARGET_PAGE_SIZE
* sizeof(uint16_t));
2427 memory_region_init_io(&mmio
->iomem
, NULL
, &subpage_ops
, mmio
,
2428 NULL
, TARGET_PAGE_SIZE
);
2429 mmio
->iomem
.subpage
= true;
2430 #if defined(DEBUG_SUBPAGE)
2431 printf("%s: %p base " HWADDR_FMT_plx
" len %08x\n", __func__
,
2432 mmio
, base
, TARGET_PAGE_SIZE
);
2438 static uint16_t dummy_section(PhysPageMap
*map
, FlatView
*fv
, MemoryRegion
*mr
)
2441 MemoryRegionSection section
= {
2444 .offset_within_address_space
= 0,
2445 .offset_within_region
= 0,
2446 .size
= int128_2_64(),
2449 return phys_section_add(map
, §ion
);
2452 MemoryRegionSection
*iotlb_to_section(CPUState
*cpu
,
2453 hwaddr index
, MemTxAttrs attrs
)
2455 int asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
2456 CPUAddressSpace
*cpuas
= &cpu
->cpu_ases
[asidx
];
2457 AddressSpaceDispatch
*d
= cpuas
->memory_dispatch
;
2458 int section_index
= index
& ~TARGET_PAGE_MASK
;
2459 MemoryRegionSection
*ret
;
2461 assert(section_index
< d
->map
.sections_nb
);
2462 ret
= d
->map
.sections
+ section_index
;
2464 assert(ret
->mr
->ops
);
2469 static void io_mem_init(void)
2471 memory_region_init_io(&io_mem_unassigned
, NULL
, &unassigned_mem_ops
, NULL
,
2475 AddressSpaceDispatch
*address_space_dispatch_new(FlatView
*fv
)
2477 AddressSpaceDispatch
*d
= g_new0(AddressSpaceDispatch
, 1);
2480 n
= dummy_section(&d
->map
, fv
, &io_mem_unassigned
);
2481 assert(n
== PHYS_SECTION_UNASSIGNED
);
2483 d
->phys_map
= (PhysPageEntry
) { .ptr
= PHYS_MAP_NODE_NIL
, .skip
= 1 };
2488 void address_space_dispatch_free(AddressSpaceDispatch
*d
)
2490 phys_sections_free(&d
->map
);
2494 static void do_nothing(CPUState
*cpu
, run_on_cpu_data d
)
2498 static void tcg_log_global_after_sync(MemoryListener
*listener
)
2500 CPUAddressSpace
*cpuas
;
2502 /* Wait for the CPU to end the current TB. This avoids the following
2506 * ---------------------- -------------------------
2507 * TLB check -> slow path
2508 * notdirty_mem_write
2512 * TLB check -> fast path
2516 * by pushing the migration thread's memory read after the vCPU thread has
2517 * written the memory.
2519 if (replay_mode
== REPLAY_MODE_NONE
) {
2521 * VGA can make calls to this function while updating the screen.
2522 * In record/replay mode this causes a deadlock, because
2523 * run_on_cpu waits for rr mutex. Therefore no races are possible
2524 * in this case and no need for making run_on_cpu when
2525 * record/replay is enabled.
2527 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2528 run_on_cpu(cpuas
->cpu
, do_nothing
, RUN_ON_CPU_NULL
);
2532 static void tcg_commit_cpu(CPUState
*cpu
, run_on_cpu_data data
)
2534 CPUAddressSpace
*cpuas
= data
.host_ptr
;
2536 cpuas
->memory_dispatch
= address_space_to_dispatch(cpuas
->as
);
2540 static void tcg_commit(MemoryListener
*listener
)
2542 CPUAddressSpace
*cpuas
;
2545 assert(tcg_enabled());
2546 /* since each CPU stores ram addresses in its TLB cache, we must
2547 reset the modified entries */
2548 cpuas
= container_of(listener
, CPUAddressSpace
, tcg_as_listener
);
2552 * Defer changes to as->memory_dispatch until the cpu is quiescent.
2553 * Otherwise we race between (1) other cpu threads and (2) ongoing
2554 * i/o for the current cpu thread, with data cached by mmu_lookup().
2556 * In addition, queueing the work function will kick the cpu back to
2557 * the main loop, which will end the RCU critical section and reclaim
2558 * the memory data structures.
2560 * That said, the listener is also called during realize, before
2561 * all of the tcg machinery for run-on is initialized: thus halt_cond.
2563 if (cpu
->halt_cond
) {
2564 async_run_on_cpu(cpu
, tcg_commit_cpu
, RUN_ON_CPU_HOST_PTR(cpuas
));
2566 tcg_commit_cpu(cpu
, RUN_ON_CPU_HOST_PTR(cpuas
));
2570 static void memory_map_init(void)
2572 system_memory
= g_malloc(sizeof(*system_memory
));
2574 memory_region_init(system_memory
, NULL
, "system", UINT64_MAX
);
2575 address_space_init(&address_space_memory
, system_memory
, "memory");
2577 system_io
= g_malloc(sizeof(*system_io
));
2578 memory_region_init_io(system_io
, NULL
, &unassigned_io_ops
, NULL
, "io",
2580 address_space_init(&address_space_io
, system_io
, "I/O");
2583 MemoryRegion
*get_system_memory(void)
2585 return system_memory
;
2588 MemoryRegion
*get_system_io(void)
2593 static void invalidate_and_set_dirty(MemoryRegion
*mr
, hwaddr addr
,
2596 uint8_t dirty_log_mask
= memory_region_get_dirty_log_mask(mr
);
2597 addr
+= memory_region_get_ram_addr(mr
);
2599 /* No early return if dirty_log_mask is or becomes 0, because
2600 * cpu_physical_memory_set_dirty_range will still call
2601 * xen_modified_memory.
2603 if (dirty_log_mask
) {
2605 cpu_physical_memory_range_includes_clean(addr
, length
, dirty_log_mask
);
2607 if (dirty_log_mask
& (1 << DIRTY_MEMORY_CODE
)) {
2608 assert(tcg_enabled());
2609 tb_invalidate_phys_range(addr
, addr
+ length
- 1);
2610 dirty_log_mask
&= ~(1 << DIRTY_MEMORY_CODE
);
2612 cpu_physical_memory_set_dirty_range(addr
, length
, dirty_log_mask
);
2615 void memory_region_flush_rom_device(MemoryRegion
*mr
, hwaddr addr
, hwaddr size
)
2618 * In principle this function would work on other memory region types too,
2619 * but the ROM device use case is the only one where this operation is
2620 * necessary. Other memory regions should use the
2621 * address_space_read/write() APIs.
2623 assert(memory_region_is_romd(mr
));
2625 invalidate_and_set_dirty(mr
, addr
, size
);
2628 int memory_access_size(MemoryRegion
*mr
, unsigned l
, hwaddr addr
)
2630 unsigned access_size_max
= mr
->ops
->valid
.max_access_size
;
2632 /* Regions are assumed to support 1-4 byte accesses unless
2633 otherwise specified. */
2634 if (access_size_max
== 0) {
2635 access_size_max
= 4;
2638 /* Bound the maximum access by the alignment of the address. */
2639 if (!mr
->ops
->impl
.unaligned
) {
2640 unsigned align_size_max
= addr
& -addr
;
2641 if (align_size_max
!= 0 && align_size_max
< access_size_max
) {
2642 access_size_max
= align_size_max
;
2646 /* Don't attempt accesses larger than the maximum. */
2647 if (l
> access_size_max
) {
2648 l
= access_size_max
;
2655 bool prepare_mmio_access(MemoryRegion
*mr
)
2657 bool release_lock
= false;
2659 if (!qemu_mutex_iothread_locked()) {
2660 qemu_mutex_lock_iothread();
2661 release_lock
= true;
2663 if (mr
->flush_coalesced_mmio
) {
2664 qemu_flush_coalesced_mmio_buffer();
2667 return release_lock
;
2671 * flatview_access_allowed
2672 * @mr: #MemoryRegion to be accessed
2673 * @attrs: memory transaction attributes
2674 * @addr: address within that memory region
2675 * @len: the number of bytes to access
2677 * Check if a memory transaction is allowed.
2679 * Returns: true if transaction is allowed, false if denied.
2681 static bool flatview_access_allowed(MemoryRegion
*mr
, MemTxAttrs attrs
,
2682 hwaddr addr
, hwaddr len
)
2684 if (likely(!attrs
.memory
)) {
2687 if (memory_region_is_ram(mr
)) {
2690 qemu_log_mask(LOG_GUEST_ERROR
,
2691 "Invalid access to non-RAM device at "
2692 "addr 0x%" HWADDR_PRIX
", size %" HWADDR_PRIu
", "
2693 "region '%s'\n", addr
, len
, memory_region_name(mr
));
2697 /* Called within RCU critical section. */
2698 static MemTxResult
flatview_write_continue(FlatView
*fv
, hwaddr addr
,
2701 hwaddr len
, hwaddr addr1
,
2702 hwaddr l
, MemoryRegion
*mr
)
2706 MemTxResult result
= MEMTX_OK
;
2707 bool release_lock
= false;
2708 const uint8_t *buf
= ptr
;
2711 if (!flatview_access_allowed(mr
, attrs
, addr1
, l
)) {
2712 result
|= MEMTX_ACCESS_ERROR
;
2714 } else if (!memory_access_is_direct(mr
, true)) {
2715 release_lock
|= prepare_mmio_access(mr
);
2716 l
= memory_access_size(mr
, l
, addr1
);
2717 /* XXX: could force current_cpu to NULL to avoid
2719 val
= ldn_he_p(buf
, l
);
2720 result
|= memory_region_dispatch_write(mr
, addr1
, val
,
2721 size_memop(l
), attrs
);
2724 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2725 memmove(ram_ptr
, buf
, l
);
2726 invalidate_and_set_dirty(mr
, addr1
, l
);
2730 qemu_mutex_unlock_iothread();
2731 release_lock
= false;
2743 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2749 /* Called from RCU critical section. */
2750 static MemTxResult
flatview_write(FlatView
*fv
, hwaddr addr
, MemTxAttrs attrs
,
2751 const void *buf
, hwaddr len
)
2758 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, true, attrs
);
2759 if (!flatview_access_allowed(mr
, attrs
, addr
, len
)) {
2760 return MEMTX_ACCESS_ERROR
;
2762 return flatview_write_continue(fv
, addr
, attrs
, buf
, len
,
2766 /* Called within RCU critical section. */
2767 MemTxResult
flatview_read_continue(FlatView
*fv
, hwaddr addr
,
2768 MemTxAttrs attrs
, void *ptr
,
2769 hwaddr len
, hwaddr addr1
, hwaddr l
,
2774 MemTxResult result
= MEMTX_OK
;
2775 bool release_lock
= false;
2778 fuzz_dma_read_cb(addr
, len
, mr
);
2780 if (!flatview_access_allowed(mr
, attrs
, addr1
, l
)) {
2781 result
|= MEMTX_ACCESS_ERROR
;
2783 } else if (!memory_access_is_direct(mr
, false)) {
2785 release_lock
|= prepare_mmio_access(mr
);
2786 l
= memory_access_size(mr
, l
, addr1
);
2787 result
|= memory_region_dispatch_read(mr
, addr1
, &val
,
2788 size_memop(l
), attrs
);
2789 stn_he_p(buf
, l
, val
);
2792 ram_ptr
= qemu_ram_ptr_length(mr
->ram_block
, addr1
, &l
, false);
2793 memcpy(buf
, ram_ptr
, l
);
2797 qemu_mutex_unlock_iothread();
2798 release_lock
= false;
2810 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2816 /* Called from RCU critical section. */
2817 static MemTxResult
flatview_read(FlatView
*fv
, hwaddr addr
,
2818 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2825 mr
= flatview_translate(fv
, addr
, &addr1
, &l
, false, attrs
);
2826 if (!flatview_access_allowed(mr
, attrs
, addr
, len
)) {
2827 return MEMTX_ACCESS_ERROR
;
2829 return flatview_read_continue(fv
, addr
, attrs
, buf
, len
,
2833 MemTxResult
address_space_read_full(AddressSpace
*as
, hwaddr addr
,
2834 MemTxAttrs attrs
, void *buf
, hwaddr len
)
2836 MemTxResult result
= MEMTX_OK
;
2840 RCU_READ_LOCK_GUARD();
2841 fv
= address_space_to_flatview(as
);
2842 result
= flatview_read(fv
, addr
, attrs
, buf
, len
);
2848 MemTxResult
address_space_write(AddressSpace
*as
, hwaddr addr
,
2850 const void *buf
, hwaddr len
)
2852 MemTxResult result
= MEMTX_OK
;
2856 RCU_READ_LOCK_GUARD();
2857 fv
= address_space_to_flatview(as
);
2858 result
= flatview_write(fv
, addr
, attrs
, buf
, len
);
2864 MemTxResult
address_space_rw(AddressSpace
*as
, hwaddr addr
, MemTxAttrs attrs
,
2865 void *buf
, hwaddr len
, bool is_write
)
2868 return address_space_write(as
, addr
, attrs
, buf
, len
);
2870 return address_space_read_full(as
, addr
, attrs
, buf
, len
);
2874 MemTxResult
address_space_set(AddressSpace
*as
, hwaddr addr
,
2875 uint8_t c
, hwaddr len
, MemTxAttrs attrs
)
2877 #define FILLBUF_SIZE 512
2878 uint8_t fillbuf
[FILLBUF_SIZE
];
2880 MemTxResult error
= MEMTX_OK
;
2882 memset(fillbuf
, c
, FILLBUF_SIZE
);
2884 l
= len
< FILLBUF_SIZE
? len
: FILLBUF_SIZE
;
2885 error
|= address_space_write(as
, addr
, attrs
, fillbuf
, l
);
2893 void cpu_physical_memory_rw(hwaddr addr
, void *buf
,
2894 hwaddr len
, bool is_write
)
2896 address_space_rw(&address_space_memory
, addr
, MEMTXATTRS_UNSPECIFIED
,
2897 buf
, len
, is_write
);
2900 enum write_rom_type
{
2905 static inline MemTxResult
address_space_write_rom_internal(AddressSpace
*as
,
2910 enum write_rom_type type
)
2916 const uint8_t *buf
= ptr
;
2918 RCU_READ_LOCK_GUARD();
2921 mr
= address_space_translate(as
, addr
, &addr1
, &l
, true, attrs
);
2923 if (!(memory_region_is_ram(mr
) ||
2924 memory_region_is_romd(mr
))) {
2925 l
= memory_access_size(mr
, l
, addr1
);
2928 ram_ptr
= qemu_map_ram_ptr(mr
->ram_block
, addr1
);
2931 memcpy(ram_ptr
, buf
, l
);
2932 invalidate_and_set_dirty(mr
, addr1
, l
);
2935 flush_idcache_range((uintptr_t)ram_ptr
, (uintptr_t)ram_ptr
, l
);
2946 /* used for ROM loading : can write in RAM and ROM */
2947 MemTxResult
address_space_write_rom(AddressSpace
*as
, hwaddr addr
,
2949 const void *buf
, hwaddr len
)
2951 return address_space_write_rom_internal(as
, addr
, attrs
,
2952 buf
, len
, WRITE_DATA
);
2955 void cpu_flush_icache_range(hwaddr start
, hwaddr len
)
2958 * This function should do the same thing as an icache flush that was
2959 * triggered from within the guest. For TCG we are always cache coherent,
2960 * so there is no need to flush anything. For KVM / Xen we need to flush
2961 * the host's instruction cache at least.
2963 if (tcg_enabled()) {
2967 address_space_write_rom_internal(&address_space_memory
,
2968 start
, MEMTXATTRS_UNSPECIFIED
,
2969 NULL
, len
, FLUSH_CACHE
);
2980 static BounceBuffer bounce
;
2982 typedef struct MapClient
{
2984 QLIST_ENTRY(MapClient
) link
;
2987 QemuMutex map_client_list_lock
;
2988 static QLIST_HEAD(, MapClient
) map_client_list
2989 = QLIST_HEAD_INITIALIZER(map_client_list
);
2991 static void cpu_unregister_map_client_do(MapClient
*client
)
2993 QLIST_REMOVE(client
, link
);
2997 static void cpu_notify_map_clients_locked(void)
3001 while (!QLIST_EMPTY(&map_client_list
)) {
3002 client
= QLIST_FIRST(&map_client_list
);
3003 qemu_bh_schedule(client
->bh
);
3004 cpu_unregister_map_client_do(client
);
3008 void cpu_register_map_client(QEMUBH
*bh
)
3010 MapClient
*client
= g_malloc(sizeof(*client
));
3012 qemu_mutex_lock(&map_client_list_lock
);
3014 QLIST_INSERT_HEAD(&map_client_list
, client
, link
);
3015 /* Write map_client_list before reading in_use. */
3017 if (!qatomic_read(&bounce
.in_use
)) {
3018 cpu_notify_map_clients_locked();
3020 qemu_mutex_unlock(&map_client_list_lock
);
3023 void cpu_exec_init_all(void)
3025 qemu_mutex_init(&ram_list
.mutex
);
3026 /* The data structures we set up here depend on knowing the page size,
3027 * so no more changes can be made after this point.
3028 * In an ideal world, nothing we did before we had finished the
3029 * machine setup would care about the target page size, and we could
3030 * do this much later, rather than requiring board models to state
3031 * up front what their requirements are.
3033 finalize_target_page_bits();
3036 qemu_mutex_init(&map_client_list_lock
);
3039 void cpu_unregister_map_client(QEMUBH
*bh
)
3043 qemu_mutex_lock(&map_client_list_lock
);
3044 QLIST_FOREACH(client
, &map_client_list
, link
) {
3045 if (client
->bh
== bh
) {
3046 cpu_unregister_map_client_do(client
);
3050 qemu_mutex_unlock(&map_client_list_lock
);
3053 static void cpu_notify_map_clients(void)
3055 qemu_mutex_lock(&map_client_list_lock
);
3056 cpu_notify_map_clients_locked();
3057 qemu_mutex_unlock(&map_client_list_lock
);
3060 static bool flatview_access_valid(FlatView
*fv
, hwaddr addr
, hwaddr len
,
3061 bool is_write
, MemTxAttrs attrs
)
3068 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3069 if (!memory_access_is_direct(mr
, is_write
)) {
3070 l
= memory_access_size(mr
, l
, addr
);
3071 if (!memory_region_access_valid(mr
, xlat
, l
, is_write
, attrs
)) {
3082 bool address_space_access_valid(AddressSpace
*as
, hwaddr addr
,
3083 hwaddr len
, bool is_write
,
3088 RCU_READ_LOCK_GUARD();
3089 fv
= address_space_to_flatview(as
);
3090 return flatview_access_valid(fv
, addr
, len
, is_write
, attrs
);
3094 flatview_extend_translation(FlatView
*fv
, hwaddr addr
,
3096 MemoryRegion
*mr
, hwaddr base
, hwaddr len
,
3097 bool is_write
, MemTxAttrs attrs
)
3101 MemoryRegion
*this_mr
;
3107 if (target_len
== 0) {
3112 this_mr
= flatview_translate(fv
, addr
, &xlat
,
3113 &len
, is_write
, attrs
);
3114 if (this_mr
!= mr
|| xlat
!= base
+ done
) {
3120 /* Map a physical memory region into a host virtual address.
3121 * May map a subset of the requested range, given by and returned in *plen.
3122 * May return NULL if resources needed to perform the mapping are exhausted.
3123 * Use only for reads OR writes - not for read-modify-write operations.
3124 * Use cpu_register_map_client() to know when retrying the map operation is
3125 * likely to succeed.
3127 void *address_space_map(AddressSpace
*as
,
3143 RCU_READ_LOCK_GUARD();
3144 fv
= address_space_to_flatview(as
);
3145 mr
= flatview_translate(fv
, addr
, &xlat
, &l
, is_write
, attrs
);
3147 if (!memory_access_is_direct(mr
, is_write
)) {
3148 if (qatomic_xchg(&bounce
.in_use
, true)) {
3152 /* Avoid unbounded allocations */
3153 l
= MIN(l
, TARGET_PAGE_SIZE
);
3154 bounce
.buffer
= qemu_memalign(TARGET_PAGE_SIZE
, l
);
3158 memory_region_ref(mr
);
3161 flatview_read(fv
, addr
, MEMTXATTRS_UNSPECIFIED
,
3166 return bounce
.buffer
;
3170 memory_region_ref(mr
);
3171 *plen
= flatview_extend_translation(fv
, addr
, len
, mr
, xlat
,
3172 l
, is_write
, attrs
);
3173 fuzz_dma_read_cb(addr
, *plen
, mr
);
3174 return qemu_ram_ptr_length(mr
->ram_block
, xlat
, plen
, true);
3177 /* Unmaps a memory region previously mapped by address_space_map().
3178 * Will also mark the memory as dirty if is_write is true. access_len gives
3179 * the amount of memory that was actually read or written by the caller.
3181 void address_space_unmap(AddressSpace
*as
, void *buffer
, hwaddr len
,
3182 bool is_write
, hwaddr access_len
)
3184 if (buffer
!= bounce
.buffer
) {
3188 mr
= memory_region_from_host(buffer
, &addr1
);
3191 invalidate_and_set_dirty(mr
, addr1
, access_len
);
3193 if (xen_enabled()) {
3194 xen_invalidate_map_cache_entry(buffer
);
3196 memory_region_unref(mr
);
3200 address_space_write(as
, bounce
.addr
, MEMTXATTRS_UNSPECIFIED
,
3201 bounce
.buffer
, access_len
);
3203 qemu_vfree(bounce
.buffer
);
3204 bounce
.buffer
= NULL
;
3205 memory_region_unref(bounce
.mr
);
3206 /* Clear in_use before reading map_client_list. */
3207 qatomic_set_mb(&bounce
.in_use
, false);
3208 cpu_notify_map_clients();
3211 void *cpu_physical_memory_map(hwaddr addr
,
3215 return address_space_map(&address_space_memory
, addr
, plen
, is_write
,
3216 MEMTXATTRS_UNSPECIFIED
);
3219 void cpu_physical_memory_unmap(void *buffer
, hwaddr len
,
3220 bool is_write
, hwaddr access_len
)
3222 return address_space_unmap(&address_space_memory
, buffer
, len
, is_write
, access_len
);
3225 #define ARG1_DECL AddressSpace *as
3228 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3229 #define RCU_READ_LOCK(...) rcu_read_lock()
3230 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3231 #include "memory_ldst.c.inc"
3233 int64_t address_space_cache_init(MemoryRegionCache
*cache
,
3239 AddressSpaceDispatch
*d
;
3247 cache
->fv
= address_space_get_flatview(as
);
3248 d
= flatview_to_dispatch(cache
->fv
);
3249 cache
->mrs
= *address_space_translate_internal(d
, addr
, &cache
->xlat
, &l
, true);
3252 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3253 * Take that into account to compute how many bytes are there between
3254 * cache->xlat and the end of the section.
3256 diff
= int128_sub(cache
->mrs
.size
,
3257 int128_make64(cache
->xlat
- cache
->mrs
.offset_within_region
));
3258 l
= int128_get64(int128_min(diff
, int128_make64(l
)));
3261 memory_region_ref(mr
);
3262 if (memory_access_is_direct(mr
, is_write
)) {
3263 /* We don't care about the memory attributes here as we're only
3264 * doing this if we found actual RAM, which behaves the same
3265 * regardless of attributes; so UNSPECIFIED is fine.
3267 l
= flatview_extend_translation(cache
->fv
, addr
, len
, mr
,
3268 cache
->xlat
, l
, is_write
,
3269 MEMTXATTRS_UNSPECIFIED
);
3270 cache
->ptr
= qemu_ram_ptr_length(mr
->ram_block
, cache
->xlat
, &l
, true);
3276 cache
->is_write
= is_write
;
3280 void address_space_cache_invalidate(MemoryRegionCache
*cache
,
3284 assert(cache
->is_write
);
3285 if (likely(cache
->ptr
)) {
3286 invalidate_and_set_dirty(cache
->mrs
.mr
, addr
+ cache
->xlat
, access_len
);
3290 void address_space_cache_destroy(MemoryRegionCache
*cache
)
3292 if (!cache
->mrs
.mr
) {
3296 if (xen_enabled()) {
3297 xen_invalidate_map_cache_entry(cache
->ptr
);
3299 memory_region_unref(cache
->mrs
.mr
);
3300 flatview_unref(cache
->fv
);
3301 cache
->mrs
.mr
= NULL
;
3305 /* Called from RCU critical section. This function has the same
3306 * semantics as address_space_translate, but it only works on a
3307 * predefined range of a MemoryRegion that was mapped with
3308 * address_space_cache_init.
3310 static inline MemoryRegion
*address_space_translate_cached(
3311 MemoryRegionCache
*cache
, hwaddr addr
, hwaddr
*xlat
,
3312 hwaddr
*plen
, bool is_write
, MemTxAttrs attrs
)
3314 MemoryRegionSection section
;
3316 IOMMUMemoryRegion
*iommu_mr
;
3317 AddressSpace
*target_as
;
3319 assert(!cache
->ptr
);
3320 *xlat
= addr
+ cache
->xlat
;
3323 iommu_mr
= memory_region_get_iommu(mr
);
3329 section
= address_space_translate_iommu(iommu_mr
, xlat
, plen
,
3330 NULL
, is_write
, true,
3335 /* Called from RCU critical section. address_space_read_cached uses this
3336 * out of line function when the target is an MMIO or IOMMU region.
3339 address_space_read_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3340 void *buf
, hwaddr len
)
3346 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, false,
3347 MEMTXATTRS_UNSPECIFIED
);
3348 return flatview_read_continue(cache
->fv
,
3349 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3353 /* Called from RCU critical section. address_space_write_cached uses this
3354 * out of line function when the target is an MMIO or IOMMU region.
3357 address_space_write_cached_slow(MemoryRegionCache
*cache
, hwaddr addr
,
3358 const void *buf
, hwaddr len
)
3364 mr
= address_space_translate_cached(cache
, addr
, &addr1
, &l
, true,
3365 MEMTXATTRS_UNSPECIFIED
);
3366 return flatview_write_continue(cache
->fv
,
3367 addr
, MEMTXATTRS_UNSPECIFIED
, buf
, len
,
3371 #define ARG1_DECL MemoryRegionCache *cache
3373 #define SUFFIX _cached_slow
3374 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3375 #define RCU_READ_LOCK() ((void)0)
3376 #define RCU_READ_UNLOCK() ((void)0)
3377 #include "memory_ldst.c.inc"
3379 /* virtual memory access for debug (includes writing to ROM) */
3380 int cpu_memory_rw_debug(CPUState
*cpu
, vaddr addr
,
3381 void *ptr
, size_t len
, bool is_write
)
3387 cpu_synchronize_state(cpu
);
3393 page
= addr
& TARGET_PAGE_MASK
;
3394 phys_addr
= cpu_get_phys_page_attrs_debug(cpu
, page
, &attrs
);
3395 asidx
= cpu_asidx_from_attrs(cpu
, attrs
);
3396 /* if no physical page mapped, return an error */
3397 if (phys_addr
== -1)
3399 l
= (page
+ TARGET_PAGE_SIZE
) - addr
;
3402 phys_addr
+= (addr
& ~TARGET_PAGE_MASK
);
3404 res
= address_space_write_rom(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3407 res
= address_space_read(cpu
->cpu_ases
[asidx
].as
, phys_addr
,
3410 if (res
!= MEMTX_OK
) {
3421 * Allows code that needs to deal with migration bitmaps etc to still be built
3422 * target independent.
3424 size_t qemu_target_page_size(void)
3426 return TARGET_PAGE_SIZE
;
3429 int qemu_target_page_mask(void)
3431 return TARGET_PAGE_MASK
;
3434 int qemu_target_page_bits(void)
3436 return TARGET_PAGE_BITS
;
3439 int qemu_target_page_bits_min(void)
3441 return TARGET_PAGE_BITS_MIN
;
3444 /* Convert target pages to MiB (2**20). */
3445 size_t qemu_target_pages_to_MiB(size_t pages
)
3447 int page_bits
= TARGET_PAGE_BITS
;
3449 /* So far, the largest (non-huge) page size is 64k, i.e. 16 bits. */
3450 g_assert(page_bits
< 20);
3452 return pages
>> (20 - page_bits
);
3455 bool cpu_physical_memory_is_io(hwaddr phys_addr
)
3460 RCU_READ_LOCK_GUARD();
3461 mr
= address_space_translate(&address_space_memory
,
3462 phys_addr
, &phys_addr
, &l
, false,
3463 MEMTXATTRS_UNSPECIFIED
);
3465 return !(memory_region_is_ram(mr
) || memory_region_is_romd(mr
));
3468 int qemu_ram_foreach_block(RAMBlockIterFunc func
, void *opaque
)
3473 RCU_READ_LOCK_GUARD();
3474 RAMBLOCK_FOREACH(block
) {
3475 ret
= func(block
, opaque
);
3484 * Unmap pages of memory from start to start+length such that
3485 * they a) read as 0, b) Trigger whatever fault mechanism
3486 * the OS provides for postcopy.
3487 * The pages must be unmapped by the end of the function.
3488 * Returns: 0 on success, none-0 on failure
3491 int ram_block_discard_range(RAMBlock
*rb
, uint64_t start
, size_t length
)
3495 uint8_t *host_startaddr
= rb
->host
+ start
;
3497 if (!QEMU_PTR_IS_ALIGNED(host_startaddr
, rb
->page_size
)) {
3498 error_report("ram_block_discard_range: Unaligned start address: %p",
3503 if ((start
+ length
) <= rb
->max_length
) {
3504 bool need_madvise
, need_fallocate
;
3505 if (!QEMU_IS_ALIGNED(length
, rb
->page_size
)) {
3506 error_report("ram_block_discard_range: Unaligned length: %zx",
3511 errno
= ENOTSUP
; /* If we are missing MADVISE etc */
3513 /* The logic here is messy;
3514 * madvise DONTNEED fails for hugepages
3515 * fallocate works on hugepages and shmem
3516 * shared anonymous memory requires madvise REMOVE
3518 need_madvise
= (rb
->page_size
== qemu_host_page_size
);
3519 need_fallocate
= rb
->fd
!= -1;
3520 if (need_fallocate
) {
3521 /* For a file, this causes the area of the file to be zero'd
3522 * if read, and for hugetlbfs also causes it to be unmapped
3523 * so a userfault will trigger.
3525 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3527 * fallocate() will fail with readonly files. Let's print a
3528 * proper error message.
3530 if (rb
->flags
& RAM_READONLY_FD
) {
3531 error_report("ram_block_discard_range: Discarding RAM"
3532 " with readonly files is not supported");
3537 * We'll discard data from the actual file, even though we only
3538 * have a MAP_PRIVATE mapping, possibly messing with other
3539 * MAP_PRIVATE/MAP_SHARED mappings. There is no easy way to
3540 * change that behavior whithout violating the promised
3541 * semantics of ram_block_discard_range().
3543 * Only warn, because it works as long as nobody else uses that
3546 if (!qemu_ram_is_shared(rb
)) {
3547 warn_report_once("ram_block_discard_range: Discarding RAM"
3548 " in private file mappings is possibly"
3549 " dangerous, because it will modify the"
3550 " underlying file and will affect other"
3551 " users of the file");
3554 ret
= fallocate(rb
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
3558 error_report("ram_block_discard_range: Failed to fallocate "
3559 "%s:%" PRIx64
" +%zx (%d)",
3560 rb
->idstr
, start
, length
, ret
);
3565 error_report("ram_block_discard_range: fallocate not available/file"
3566 "%s:%" PRIx64
" +%zx (%d)",
3567 rb
->idstr
, start
, length
, ret
);
3572 /* For normal RAM this causes it to be unmapped,
3573 * for shared memory it causes the local mapping to disappear
3574 * and to fall back on the file contents (which we just
3575 * fallocate'd away).
3577 #if defined(CONFIG_MADVISE)
3578 if (qemu_ram_is_shared(rb
) && rb
->fd
< 0) {
3579 ret
= madvise(host_startaddr
, length
, QEMU_MADV_REMOVE
);
3581 ret
= madvise(host_startaddr
, length
, QEMU_MADV_DONTNEED
);
3585 error_report("ram_block_discard_range: Failed to discard range "
3586 "%s:%" PRIx64
" +%zx (%d)",
3587 rb
->idstr
, start
, length
, ret
);
3592 error_report("ram_block_discard_range: MADVISE not available"
3593 "%s:%" PRIx64
" +%zx (%d)",
3594 rb
->idstr
, start
, length
, ret
);
3598 trace_ram_block_discard_range(rb
->idstr
, host_startaddr
, length
,
3599 need_madvise
, need_fallocate
, ret
);
3601 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3602 "/%zx/" RAM_ADDR_FMT
")",
3603 rb
->idstr
, start
, length
, rb
->max_length
);
3610 bool ramblock_is_pmem(RAMBlock
*rb
)
3612 return rb
->flags
& RAM_PMEM
;
3615 static void mtree_print_phys_entries(int start
, int end
, int skip
, int ptr
)
3617 if (start
== end
- 1) {
3618 qemu_printf("\t%3d ", start
);
3620 qemu_printf("\t%3d..%-3d ", start
, end
- 1);
3622 qemu_printf(" skip=%d ", skip
);
3623 if (ptr
== PHYS_MAP_NODE_NIL
) {
3624 qemu_printf(" ptr=NIL");
3626 qemu_printf(" ptr=#%d", ptr
);
3628 qemu_printf(" ptr=[%d]", ptr
);
3633 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3634 int128_sub((size), int128_one())) : 0)
3636 void mtree_print_dispatch(AddressSpaceDispatch
*d
, MemoryRegion
*root
)
3640 qemu_printf(" Dispatch\n");
3641 qemu_printf(" Physical sections\n");
3643 for (i
= 0; i
< d
->map
.sections_nb
; ++i
) {
3644 MemoryRegionSection
*s
= d
->map
.sections
+ i
;
3645 const char *names
[] = { " [unassigned]", " [not dirty]",
3646 " [ROM]", " [watch]" };
3648 qemu_printf(" #%d @" HWADDR_FMT_plx
".." HWADDR_FMT_plx
3651 s
->offset_within_address_space
,
3652 s
->offset_within_address_space
+ MR_SIZE(s
->size
),
3653 s
->mr
->name
? s
->mr
->name
: "(noname)",
3654 i
< ARRAY_SIZE(names
) ? names
[i
] : "",
3655 s
->mr
== root
? " [ROOT]" : "",
3656 s
== d
->mru_section
? " [MRU]" : "",
3657 s
->mr
->is_iommu
? " [iommu]" : "");
3660 qemu_printf(" alias=%s", s
->mr
->alias
->name
?
3661 s
->mr
->alias
->name
: "noname");
3666 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3667 P_L2_BITS
, P_L2_LEVELS
, d
->phys_map
.ptr
, d
->phys_map
.skip
);
3668 for (i
= 0; i
< d
->map
.nodes_nb
; ++i
) {
3671 Node
*n
= d
->map
.nodes
+ i
;
3673 qemu_printf(" [%d]\n", i
);
3675 for (j
= 0, jprev
= 0, prev
= *n
[0]; j
< ARRAY_SIZE(*n
); ++j
) {
3676 PhysPageEntry
*pe
= *n
+ j
;
3678 if (pe
->ptr
== prev
.ptr
&& pe
->skip
== prev
.skip
) {
3682 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3688 if (jprev
!= ARRAY_SIZE(*n
)) {
3689 mtree_print_phys_entries(jprev
, j
, prev
.skip
, prev
.ptr
);
3694 /* Require any discards to work. */
3695 static unsigned int ram_block_discard_required_cnt
;
3696 /* Require only coordinated discards to work. */
3697 static unsigned int ram_block_coordinated_discard_required_cnt
;
3698 /* Disable any discards. */
3699 static unsigned int ram_block_discard_disabled_cnt
;
3700 /* Disable only uncoordinated discards. */
3701 static unsigned int ram_block_uncoordinated_discard_disabled_cnt
;
3702 static QemuMutex ram_block_discard_disable_mutex
;
3704 static void ram_block_discard_disable_mutex_lock(void)
3706 static gsize initialized
;
3708 if (g_once_init_enter(&initialized
)) {
3709 qemu_mutex_init(&ram_block_discard_disable_mutex
);
3710 g_once_init_leave(&initialized
, 1);
3712 qemu_mutex_lock(&ram_block_discard_disable_mutex
);
3715 static void ram_block_discard_disable_mutex_unlock(void)
3717 qemu_mutex_unlock(&ram_block_discard_disable_mutex
);
3720 int ram_block_discard_disable(bool state
)
3724 ram_block_discard_disable_mutex_lock();
3726 ram_block_discard_disabled_cnt
--;
3727 } else if (ram_block_discard_required_cnt
||
3728 ram_block_coordinated_discard_required_cnt
) {
3731 ram_block_discard_disabled_cnt
++;
3733 ram_block_discard_disable_mutex_unlock();
3737 int ram_block_uncoordinated_discard_disable(bool state
)
3741 ram_block_discard_disable_mutex_lock();
3743 ram_block_uncoordinated_discard_disabled_cnt
--;
3744 } else if (ram_block_discard_required_cnt
) {
3747 ram_block_uncoordinated_discard_disabled_cnt
++;
3749 ram_block_discard_disable_mutex_unlock();
3753 int ram_block_discard_require(bool state
)
3757 ram_block_discard_disable_mutex_lock();
3759 ram_block_discard_required_cnt
--;
3760 } else if (ram_block_discard_disabled_cnt
||
3761 ram_block_uncoordinated_discard_disabled_cnt
) {
3764 ram_block_discard_required_cnt
++;
3766 ram_block_discard_disable_mutex_unlock();
3770 int ram_block_coordinated_discard_require(bool state
)
3774 ram_block_discard_disable_mutex_lock();
3776 ram_block_coordinated_discard_required_cnt
--;
3777 } else if (ram_block_discard_disabled_cnt
) {
3780 ram_block_coordinated_discard_required_cnt
++;
3782 ram_block_discard_disable_mutex_unlock();
3786 bool ram_block_discard_is_disabled(void)
3788 return qatomic_read(&ram_block_discard_disabled_cnt
) ||
3789 qatomic_read(&ram_block_uncoordinated_discard_disabled_cnt
);
3792 bool ram_block_discard_is_required(void)
3794 return qatomic_read(&ram_block_discard_required_cnt
) ||
3795 qatomic_read(&ram_block_coordinated_discard_required_cnt
);