tests/acpi: allow updates for expected data files
[qemu/ar7.git] / softmmu / physmem.c
blobe319fb2a1e995b1070060e3f6ed165aa521e00e0
1 /*
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 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 #include "qemu/osdep.h"
21 #include "qemu-common.h"
22 #include "qapi/error.h"
24 #include "qemu/cutils.h"
25 #include "cpu.h"
26 #include "exec/exec-all.h"
27 #include "exec/target_page.h"
28 #include "tcg/tcg.h"
29 #include "hw/qdev-core.h"
30 #include "hw/qdev-properties.h"
31 #include "hw/boards.h"
32 #include "hw/xen/xen.h"
33 #include "sysemu/kvm.h"
34 #include "sysemu/sysemu.h"
35 #include "sysemu/tcg.h"
36 #include "sysemu/qtest.h"
37 #include "qemu/timer.h"
38 #include "qemu/config-file.h"
39 #include "qemu/error-report.h"
40 #include "qemu/qemu-print.h"
41 #include "exec/memory.h"
42 #include "exec/ioport.h"
43 #include "sysemu/dma.h"
44 #include "sysemu/hostmem.h"
45 #include "sysemu/hw_accel.h"
46 #include "exec/address-spaces.h"
47 #include "sysemu/xen-mapcache.h"
48 #include "trace/trace-root.h"
50 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
51 #include <linux/falloc.h>
52 #endif
54 #include "qemu/rcu_queue.h"
55 #include "qemu/main-loop.h"
56 #include "translate-all.h"
57 #include "sysemu/replay.h"
59 #include "exec/memory-internal.h"
60 #include "exec/ram_addr.h"
61 #include "exec/log.h"
63 #include "qemu/pmem.h"
65 #include "migration/vmstate.h"
67 #include "qemu/range.h"
68 #ifndef _WIN32
69 #include "qemu/mmap-alloc.h"
70 #endif
72 #include "monitor/monitor.h"
74 #ifdef CONFIG_LIBDAXCTL
75 #include <daxctl/libdaxctl.h>
76 #endif
78 //#define DEBUG_SUBPAGE
80 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
81 * are protected by the ramlist lock.
83 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
85 static MemoryRegion *system_memory;
86 static MemoryRegion *system_io;
88 AddressSpace address_space_io;
89 AddressSpace address_space_memory;
91 static MemoryRegion io_mem_unassigned;
93 typedef struct PhysPageEntry PhysPageEntry;
95 struct PhysPageEntry {
96 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
97 uint32_t skip : 6;
98 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
99 uint32_t ptr : 26;
102 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
104 /* Size of the L2 (and L3, etc) page tables. */
105 #define ADDR_SPACE_BITS 64
107 #define P_L2_BITS 9
108 #define P_L2_SIZE (1 << P_L2_BITS)
110 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
112 typedef PhysPageEntry Node[P_L2_SIZE];
114 typedef struct PhysPageMap {
115 struct rcu_head rcu;
117 unsigned sections_nb;
118 unsigned sections_nb_alloc;
119 unsigned nodes_nb;
120 unsigned nodes_nb_alloc;
121 Node *nodes;
122 MemoryRegionSection *sections;
123 } PhysPageMap;
125 struct AddressSpaceDispatch {
126 MemoryRegionSection *mru_section;
127 /* This is a multi-level map on the physical address space.
128 * The bottom level has pointers to MemoryRegionSections.
130 PhysPageEntry phys_map;
131 PhysPageMap map;
134 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
135 typedef struct subpage_t {
136 MemoryRegion iomem;
137 FlatView *fv;
138 hwaddr base;
139 uint16_t sub_section[];
140 } subpage_t;
142 #define PHYS_SECTION_UNASSIGNED 0
144 static void io_mem_init(void);
145 static void memory_map_init(void);
146 static void tcg_log_global_after_sync(MemoryListener *listener);
147 static void tcg_commit(MemoryListener *listener);
150 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
151 * @cpu: the CPU whose AddressSpace this is
152 * @as: the AddressSpace itself
153 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
154 * @tcg_as_listener: listener for tracking changes to the AddressSpace
156 struct CPUAddressSpace {
157 CPUState *cpu;
158 AddressSpace *as;
159 struct AddressSpaceDispatch *memory_dispatch;
160 MemoryListener tcg_as_listener;
163 struct DirtyBitmapSnapshot {
164 ram_addr_t start;
165 ram_addr_t end;
166 unsigned long dirty[];
169 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
171 static unsigned alloc_hint = 16;
172 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
173 map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
174 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
175 alloc_hint = map->nodes_nb_alloc;
179 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
181 unsigned i;
182 uint32_t ret;
183 PhysPageEntry e;
184 PhysPageEntry *p;
186 ret = map->nodes_nb++;
187 p = map->nodes[ret];
188 assert(ret != PHYS_MAP_NODE_NIL);
189 assert(ret != map->nodes_nb_alloc);
191 e.skip = leaf ? 0 : 1;
192 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
193 for (i = 0; i < P_L2_SIZE; ++i) {
194 memcpy(&p[i], &e, sizeof(e));
196 return ret;
199 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
200 hwaddr *index, uint64_t *nb, uint16_t leaf,
201 int level)
203 PhysPageEntry *p;
204 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
206 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
207 lp->ptr = phys_map_node_alloc(map, level == 0);
209 p = map->nodes[lp->ptr];
210 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
212 while (*nb && lp < &p[P_L2_SIZE]) {
213 if ((*index & (step - 1)) == 0 && *nb >= step) {
214 lp->skip = 0;
215 lp->ptr = leaf;
216 *index += step;
217 *nb -= step;
218 } else {
219 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
221 ++lp;
225 static void phys_page_set(AddressSpaceDispatch *d,
226 hwaddr index, uint64_t nb,
227 uint16_t leaf)
229 /* Wildly overreserve - it doesn't matter much. */
230 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
232 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
235 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
236 * and update our entry so we can skip it and go directly to the destination.
238 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
240 unsigned valid_ptr = P_L2_SIZE;
241 int valid = 0;
242 PhysPageEntry *p;
243 int i;
245 if (lp->ptr == PHYS_MAP_NODE_NIL) {
246 return;
249 p = nodes[lp->ptr];
250 for (i = 0; i < P_L2_SIZE; i++) {
251 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
252 continue;
255 valid_ptr = i;
256 valid++;
257 if (p[i].skip) {
258 phys_page_compact(&p[i], nodes);
262 /* We can only compress if there's only one child. */
263 if (valid != 1) {
264 return;
267 assert(valid_ptr < P_L2_SIZE);
269 /* Don't compress if it won't fit in the # of bits we have. */
270 if (P_L2_LEVELS >= (1 << 6) &&
271 lp->skip + p[valid_ptr].skip >= (1 << 6)) {
272 return;
275 lp->ptr = p[valid_ptr].ptr;
276 if (!p[valid_ptr].skip) {
277 /* If our only child is a leaf, make this a leaf. */
278 /* By design, we should have made this node a leaf to begin with so we
279 * should never reach here.
280 * But since it's so simple to handle this, let's do it just in case we
281 * change this rule.
283 lp->skip = 0;
284 } else {
285 lp->skip += p[valid_ptr].skip;
289 void address_space_dispatch_compact(AddressSpaceDispatch *d)
291 if (d->phys_map.skip) {
292 phys_page_compact(&d->phys_map, d->map.nodes);
296 static inline bool section_covers_addr(const MemoryRegionSection *section,
297 hwaddr addr)
299 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
300 * the section must cover the entire address space.
302 return int128_gethi(section->size) ||
303 range_covers_byte(section->offset_within_address_space,
304 int128_getlo(section->size), addr);
307 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
309 PhysPageEntry lp = d->phys_map, *p;
310 Node *nodes = d->map.nodes;
311 MemoryRegionSection *sections = d->map.sections;
312 hwaddr index = addr >> TARGET_PAGE_BITS;
313 int i;
315 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
316 if (lp.ptr == PHYS_MAP_NODE_NIL) {
317 return &sections[PHYS_SECTION_UNASSIGNED];
319 p = nodes[lp.ptr];
320 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
323 if (section_covers_addr(&sections[lp.ptr], addr)) {
324 return &sections[lp.ptr];
325 } else {
326 return &sections[PHYS_SECTION_UNASSIGNED];
330 /* Called from RCU critical section */
331 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
332 hwaddr addr,
333 bool resolve_subpage)
335 MemoryRegionSection *section = qatomic_read(&d->mru_section);
336 subpage_t *subpage;
338 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
339 !section_covers_addr(section, addr)) {
340 section = phys_page_find(d, addr);
341 qatomic_set(&d->mru_section, section);
343 if (resolve_subpage && section->mr->subpage) {
344 subpage = container_of(section->mr, subpage_t, iomem);
345 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
347 return section;
350 /* Called from RCU critical section */
351 static MemoryRegionSection *
352 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
353 hwaddr *plen, bool resolve_subpage)
355 MemoryRegionSection *section;
356 MemoryRegion *mr;
357 Int128 diff;
359 section = address_space_lookup_region(d, addr, resolve_subpage);
360 /* Compute offset within MemoryRegionSection */
361 addr -= section->offset_within_address_space;
363 /* Compute offset within MemoryRegion */
364 *xlat = addr + section->offset_within_region;
366 mr = section->mr;
368 /* MMIO registers can be expected to perform full-width accesses based only
369 * on their address, without considering adjacent registers that could
370 * decode to completely different MemoryRegions. When such registers
371 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
372 * regions overlap wildly. For this reason we cannot clamp the accesses
373 * here.
375 * If the length is small (as is the case for address_space_ldl/stl),
376 * everything works fine. If the incoming length is large, however,
377 * the caller really has to do the clamping through memory_access_size.
379 if (memory_region_is_ram(mr)) {
380 diff = int128_sub(section->size, int128_make64(addr));
381 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
383 return section;
387 * address_space_translate_iommu - translate an address through an IOMMU
388 * memory region and then through the target address space.
390 * @iommu_mr: the IOMMU memory region that we start the translation from
391 * @addr: the address to be translated through the MMU
392 * @xlat: the translated address offset within the destination memory region.
393 * It cannot be %NULL.
394 * @plen_out: valid read/write length of the translated address. It
395 * cannot be %NULL.
396 * @page_mask_out: page mask for the translated address. This
397 * should only be meaningful for IOMMU translated
398 * addresses, since there may be huge pages that this bit
399 * would tell. It can be %NULL if we don't care about it.
400 * @is_write: whether the translation operation is for write
401 * @is_mmio: whether this can be MMIO, set true if it can
402 * @target_as: the address space targeted by the IOMMU
403 * @attrs: transaction attributes
405 * This function is called from RCU critical section. It is the common
406 * part of flatview_do_translate and address_space_translate_cached.
408 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
409 hwaddr *xlat,
410 hwaddr *plen_out,
411 hwaddr *page_mask_out,
412 bool is_write,
413 bool is_mmio,
414 AddressSpace **target_as,
415 MemTxAttrs attrs)
417 MemoryRegionSection *section;
418 hwaddr page_mask = (hwaddr)-1;
420 do {
421 hwaddr addr = *xlat;
422 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
423 int iommu_idx = 0;
424 IOMMUTLBEntry iotlb;
426 if (imrc->attrs_to_index) {
427 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
430 iotlb = imrc->translate(iommu_mr, addr, is_write ?
431 IOMMU_WO : IOMMU_RO, iommu_idx);
433 if (!(iotlb.perm & (1 << is_write))) {
434 goto unassigned;
437 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
438 | (addr & iotlb.addr_mask));
439 page_mask &= iotlb.addr_mask;
440 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
441 *target_as = iotlb.target_as;
443 section = address_space_translate_internal(
444 address_space_to_dispatch(iotlb.target_as), addr, xlat,
445 plen_out, is_mmio);
447 iommu_mr = memory_region_get_iommu(section->mr);
448 } while (unlikely(iommu_mr));
450 if (page_mask_out) {
451 *page_mask_out = page_mask;
453 return *section;
455 unassigned:
456 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
460 * flatview_do_translate - translate an address in FlatView
462 * @fv: the flat view that we want to translate on
463 * @addr: the address to be translated in above address space
464 * @xlat: the translated address offset within memory region. It
465 * cannot be @NULL.
466 * @plen_out: valid read/write length of the translated address. It
467 * can be @NULL when we don't care about it.
468 * @page_mask_out: page mask for the translated address. This
469 * should only be meaningful for IOMMU translated
470 * addresses, since there may be huge pages that this bit
471 * would tell. It can be @NULL if we don't care about it.
472 * @is_write: whether the translation operation is for write
473 * @is_mmio: whether this can be MMIO, set true if it can
474 * @target_as: the address space targeted by the IOMMU
475 * @attrs: memory transaction attributes
477 * This function is called from RCU critical section
479 static MemoryRegionSection flatview_do_translate(FlatView *fv,
480 hwaddr addr,
481 hwaddr *xlat,
482 hwaddr *plen_out,
483 hwaddr *page_mask_out,
484 bool is_write,
485 bool is_mmio,
486 AddressSpace **target_as,
487 MemTxAttrs attrs)
489 MemoryRegionSection *section;
490 IOMMUMemoryRegion *iommu_mr;
491 hwaddr plen = (hwaddr)(-1);
493 if (!plen_out) {
494 plen_out = &plen;
497 section = address_space_translate_internal(
498 flatview_to_dispatch(fv), addr, xlat,
499 plen_out, is_mmio);
501 iommu_mr = memory_region_get_iommu(section->mr);
502 if (unlikely(iommu_mr)) {
503 return address_space_translate_iommu(iommu_mr, xlat,
504 plen_out, page_mask_out,
505 is_write, is_mmio,
506 target_as, attrs);
508 if (page_mask_out) {
509 /* Not behind an IOMMU, use default page size. */
510 *page_mask_out = ~TARGET_PAGE_MASK;
513 return *section;
516 /* Called from RCU critical section */
517 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
518 bool is_write, MemTxAttrs attrs)
520 MemoryRegionSection section;
521 hwaddr xlat, page_mask;
524 * This can never be MMIO, and we don't really care about plen,
525 * but page mask.
527 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
528 NULL, &page_mask, is_write, false, &as,
529 attrs);
531 /* Illegal translation */
532 if (section.mr == &io_mem_unassigned) {
533 goto iotlb_fail;
536 /* Convert memory region offset into address space offset */
537 xlat += section.offset_within_address_space -
538 section.offset_within_region;
540 return (IOMMUTLBEntry) {
541 .target_as = as,
542 .iova = addr & ~page_mask,
543 .translated_addr = xlat & ~page_mask,
544 .addr_mask = page_mask,
545 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
546 .perm = IOMMU_RW,
549 iotlb_fail:
550 return (IOMMUTLBEntry) {0};
553 /* Called from RCU critical section */
554 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
555 hwaddr *plen, bool is_write,
556 MemTxAttrs attrs)
558 MemoryRegion *mr;
559 MemoryRegionSection section;
560 AddressSpace *as = NULL;
562 /* This can be MMIO, so setup MMIO bit. */
563 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
564 is_write, true, &as, attrs);
565 mr = section.mr;
567 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
568 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
569 *plen = MIN(page, *plen);
572 return mr;
575 typedef struct TCGIOMMUNotifier {
576 IOMMUNotifier n;
577 MemoryRegion *mr;
578 CPUState *cpu;
579 int iommu_idx;
580 bool active;
581 } TCGIOMMUNotifier;
583 static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
585 TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
587 if (!notifier->active) {
588 return;
590 tlb_flush(notifier->cpu);
591 notifier->active = false;
592 /* We leave the notifier struct on the list to avoid reallocating it later.
593 * Generally the number of IOMMUs a CPU deals with will be small.
594 * In any case we can't unregister the iommu notifier from a notify
595 * callback.
599 static void tcg_register_iommu_notifier(CPUState *cpu,
600 IOMMUMemoryRegion *iommu_mr,
601 int iommu_idx)
603 /* Make sure this CPU has an IOMMU notifier registered for this
604 * IOMMU/IOMMU index combination, so that we can flush its TLB
605 * when the IOMMU tells us the mappings we've cached have changed.
607 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
608 TCGIOMMUNotifier *notifier;
609 int i;
611 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
612 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
613 if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
614 break;
617 if (i == cpu->iommu_notifiers->len) {
618 /* Not found, add a new entry at the end of the array */
619 cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
620 notifier = g_new0(TCGIOMMUNotifier, 1);
621 g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
623 notifier->mr = mr;
624 notifier->iommu_idx = iommu_idx;
625 notifier->cpu = cpu;
626 /* Rather than trying to register interest in the specific part
627 * of the iommu's address space that we've accessed and then
628 * expand it later as subsequent accesses touch more of it, we
629 * just register interest in the whole thing, on the assumption
630 * that iommu reconfiguration will be rare.
632 iommu_notifier_init(&notifier->n,
633 tcg_iommu_unmap_notify,
634 IOMMU_NOTIFIER_UNMAP,
636 HWADDR_MAX,
637 iommu_idx);
638 memory_region_register_iommu_notifier(notifier->mr, &notifier->n,
639 &error_fatal);
642 if (!notifier->active) {
643 notifier->active = true;
647 void tcg_iommu_free_notifier_list(CPUState *cpu)
649 /* Destroy the CPU's notifier list */
650 int i;
651 TCGIOMMUNotifier *notifier;
653 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
654 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
655 memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
656 g_free(notifier);
658 g_array_free(cpu->iommu_notifiers, true);
661 void tcg_iommu_init_notifier_list(CPUState *cpu)
663 cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
666 /* Called from RCU critical section */
667 MemoryRegionSection *
668 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
669 hwaddr *xlat, hwaddr *plen,
670 MemTxAttrs attrs, int *prot)
672 MemoryRegionSection *section;
673 IOMMUMemoryRegion *iommu_mr;
674 IOMMUMemoryRegionClass *imrc;
675 IOMMUTLBEntry iotlb;
676 int iommu_idx;
677 AddressSpaceDispatch *d =
678 qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
680 for (;;) {
681 section = address_space_translate_internal(d, addr, &addr, plen, false);
683 iommu_mr = memory_region_get_iommu(section->mr);
684 if (!iommu_mr) {
685 break;
688 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
690 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
691 tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
692 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
693 * doesn't short-cut its translation table walk.
695 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
696 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
697 | (addr & iotlb.addr_mask));
698 /* Update the caller's prot bits to remove permissions the IOMMU
699 * is giving us a failure response for. If we get down to no
700 * permissions left at all we can give up now.
702 if (!(iotlb.perm & IOMMU_RO)) {
703 *prot &= ~(PAGE_READ | PAGE_EXEC);
705 if (!(iotlb.perm & IOMMU_WO)) {
706 *prot &= ~PAGE_WRITE;
709 if (!*prot) {
710 goto translate_fail;
713 d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
716 assert(!memory_region_is_iommu(section->mr));
717 *xlat = addr;
718 return section;
720 translate_fail:
721 return &d->map.sections[PHYS_SECTION_UNASSIGNED];
724 void cpu_address_space_init(CPUState *cpu, int asidx,
725 const char *prefix, MemoryRegion *mr)
727 CPUAddressSpace *newas;
728 AddressSpace *as = g_new0(AddressSpace, 1);
729 char *as_name;
731 assert(mr);
732 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
733 address_space_init(as, mr, as_name);
734 g_free(as_name);
736 /* Target code should have set num_ases before calling us */
737 assert(asidx < cpu->num_ases);
739 if (asidx == 0) {
740 /* address space 0 gets the convenience alias */
741 cpu->as = as;
744 /* KVM cannot currently support multiple address spaces. */
745 assert(asidx == 0 || !kvm_enabled());
747 if (!cpu->cpu_ases) {
748 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
751 newas = &cpu->cpu_ases[asidx];
752 newas->cpu = cpu;
753 newas->as = as;
754 if (tcg_enabled()) {
755 newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
756 newas->tcg_as_listener.commit = tcg_commit;
757 memory_listener_register(&newas->tcg_as_listener, as);
761 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
763 /* Return the AddressSpace corresponding to the specified index */
764 return cpu->cpu_ases[asidx].as;
767 /* Add a watchpoint. */
768 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
769 int flags, CPUWatchpoint **watchpoint)
771 CPUWatchpoint *wp;
772 vaddr in_page;
774 /* forbid ranges which are empty or run off the end of the address space */
775 if (len == 0 || (addr + len - 1) < addr) {
776 error_report("tried to set invalid watchpoint at %"
777 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
778 return -EINVAL;
780 wp = g_malloc(sizeof(*wp));
782 wp->vaddr = addr;
783 wp->len = len;
784 wp->flags = flags;
786 /* keep all GDB-injected watchpoints in front */
787 if (flags & BP_GDB) {
788 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
789 } else {
790 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
793 in_page = -(addr | TARGET_PAGE_MASK);
794 if (len <= in_page) {
795 tlb_flush_page(cpu, addr);
796 } else {
797 tlb_flush(cpu);
800 if (watchpoint)
801 *watchpoint = wp;
802 return 0;
805 /* Remove a specific watchpoint. */
806 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
807 int flags)
809 CPUWatchpoint *wp;
811 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
812 if (addr == wp->vaddr && len == wp->len
813 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
814 cpu_watchpoint_remove_by_ref(cpu, wp);
815 return 0;
818 return -ENOENT;
821 /* Remove a specific watchpoint by reference. */
822 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
824 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
826 tlb_flush_page(cpu, watchpoint->vaddr);
828 g_free(watchpoint);
831 /* Remove all matching watchpoints. */
832 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
834 CPUWatchpoint *wp, *next;
836 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
837 if (wp->flags & mask) {
838 cpu_watchpoint_remove_by_ref(cpu, wp);
843 /* Return true if this watchpoint address matches the specified
844 * access (ie the address range covered by the watchpoint overlaps
845 * partially or completely with the address range covered by the
846 * access).
848 static inline bool watchpoint_address_matches(CPUWatchpoint *wp,
849 vaddr addr, vaddr len)
851 /* We know the lengths are non-zero, but a little caution is
852 * required to avoid errors in the case where the range ends
853 * exactly at the top of the address space and so addr + len
854 * wraps round to zero.
856 vaddr wpend = wp->vaddr + wp->len - 1;
857 vaddr addrend = addr + len - 1;
859 return !(addr > wpend || wp->vaddr > addrend);
862 /* Return flags for watchpoints that match addr + prot. */
863 int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len)
865 CPUWatchpoint *wp;
866 int ret = 0;
868 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
869 if (watchpoint_address_matches(wp, addr, len)) {
870 ret |= wp->flags;
873 return ret;
876 /* Called from RCU critical section */
877 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
879 RAMBlock *block;
881 block = qatomic_rcu_read(&ram_list.mru_block);
882 if (block && addr - block->offset < block->max_length) {
883 return block;
885 RAMBLOCK_FOREACH(block) {
886 if (addr - block->offset < block->max_length) {
887 goto found;
891 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
892 abort();
894 found:
895 /* It is safe to write mru_block outside the iothread lock. This
896 * is what happens:
898 * mru_block = xxx
899 * rcu_read_unlock()
900 * xxx removed from list
901 * rcu_read_lock()
902 * read mru_block
903 * mru_block = NULL;
904 * call_rcu(reclaim_ramblock, xxx);
905 * rcu_read_unlock()
907 * qatomic_rcu_set is not needed here. The block was already published
908 * when it was placed into the list. Here we're just making an extra
909 * copy of the pointer.
911 ram_list.mru_block = block;
912 return block;
915 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
917 CPUState *cpu;
918 ram_addr_t start1;
919 RAMBlock *block;
920 ram_addr_t end;
922 assert(tcg_enabled());
923 end = TARGET_PAGE_ALIGN(start + length);
924 start &= TARGET_PAGE_MASK;
926 RCU_READ_LOCK_GUARD();
927 block = qemu_get_ram_block(start);
928 assert(block == qemu_get_ram_block(end - 1));
929 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
930 CPU_FOREACH(cpu) {
931 tlb_reset_dirty(cpu, start1, length);
935 /* Note: start and end must be within the same ram block. */
936 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
937 ram_addr_t length,
938 unsigned client)
940 DirtyMemoryBlocks *blocks;
941 unsigned long end, page, start_page;
942 bool dirty = false;
943 RAMBlock *ramblock;
944 uint64_t mr_offset, mr_size;
946 if (length == 0) {
947 return false;
950 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
951 start_page = start >> TARGET_PAGE_BITS;
952 page = start_page;
954 WITH_RCU_READ_LOCK_GUARD() {
955 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
956 ramblock = qemu_get_ram_block(start);
957 /* Range sanity check on the ramblock */
958 assert(start >= ramblock->offset &&
959 start + length <= ramblock->offset + ramblock->used_length);
961 while (page < end) {
962 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
963 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
964 unsigned long num = MIN(end - page,
965 DIRTY_MEMORY_BLOCK_SIZE - offset);
967 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
968 offset, num);
969 page += num;
972 mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
973 mr_size = (end - start_page) << TARGET_PAGE_BITS;
974 memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
977 if (dirty && tcg_enabled()) {
978 tlb_reset_dirty_range_all(start, length);
981 return dirty;
984 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
985 (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
987 DirtyMemoryBlocks *blocks;
988 ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
989 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
990 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
991 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
992 DirtyBitmapSnapshot *snap;
993 unsigned long page, end, dest;
995 snap = g_malloc0(sizeof(*snap) +
996 ((last - first) >> (TARGET_PAGE_BITS + 3)));
997 snap->start = first;
998 snap->end = last;
1000 page = first >> TARGET_PAGE_BITS;
1001 end = last >> TARGET_PAGE_BITS;
1002 dest = 0;
1004 WITH_RCU_READ_LOCK_GUARD() {
1005 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1007 while (page < end) {
1008 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1009 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1010 unsigned long num = MIN(end - page,
1011 DIRTY_MEMORY_BLOCK_SIZE - offset);
1013 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1014 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1015 offset >>= BITS_PER_LEVEL;
1017 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1018 blocks->blocks[idx] + offset,
1019 num);
1020 page += num;
1021 dest += num >> BITS_PER_LEVEL;
1025 if (tcg_enabled()) {
1026 tlb_reset_dirty_range_all(start, length);
1029 memory_region_clear_dirty_bitmap(mr, offset, length);
1031 return snap;
1034 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1035 ram_addr_t start,
1036 ram_addr_t length)
1038 unsigned long page, end;
1040 assert(start >= snap->start);
1041 assert(start + length <= snap->end);
1043 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1044 page = (start - snap->start) >> TARGET_PAGE_BITS;
1046 while (page < end) {
1047 if (test_bit(page, snap->dirty)) {
1048 return true;
1050 page++;
1052 return false;
1055 /* Called from RCU critical section */
1056 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1057 MemoryRegionSection *section)
1059 AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
1060 return section - d->map.sections;
1063 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
1064 uint16_t section);
1065 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1067 static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
1068 qemu_anon_ram_alloc;
1071 * Set a custom physical guest memory alloator.
1072 * Accelerators with unusual needs may need this. Hopefully, we can
1073 * get rid of it eventually.
1075 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
1077 phys_mem_alloc = alloc;
1080 static uint16_t phys_section_add(PhysPageMap *map,
1081 MemoryRegionSection *section)
1083 /* The physical section number is ORed with a page-aligned
1084 * pointer to produce the iotlb entries. Thus it should
1085 * never overflow into the page-aligned value.
1087 assert(map->sections_nb < TARGET_PAGE_SIZE);
1089 if (map->sections_nb == map->sections_nb_alloc) {
1090 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1091 map->sections = g_renew(MemoryRegionSection, map->sections,
1092 map->sections_nb_alloc);
1094 map->sections[map->sections_nb] = *section;
1095 memory_region_ref(section->mr);
1096 return map->sections_nb++;
1099 static void phys_section_destroy(MemoryRegion *mr)
1101 bool have_sub_page = mr->subpage;
1103 memory_region_unref(mr);
1105 if (have_sub_page) {
1106 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1107 object_unref(OBJECT(&subpage->iomem));
1108 g_free(subpage);
1112 static void phys_sections_free(PhysPageMap *map)
1114 while (map->sections_nb > 0) {
1115 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1116 phys_section_destroy(section->mr);
1118 g_free(map->sections);
1119 g_free(map->nodes);
1122 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1124 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1125 subpage_t *subpage;
1126 hwaddr base = section->offset_within_address_space
1127 & TARGET_PAGE_MASK;
1128 MemoryRegionSection *existing = phys_page_find(d, base);
1129 MemoryRegionSection subsection = {
1130 .offset_within_address_space = base,
1131 .size = int128_make64(TARGET_PAGE_SIZE),
1133 hwaddr start, end;
1135 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1137 if (!(existing->mr->subpage)) {
1138 subpage = subpage_init(fv, base);
1139 subsection.fv = fv;
1140 subsection.mr = &subpage->iomem;
1141 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1142 phys_section_add(&d->map, &subsection));
1143 } else {
1144 subpage = container_of(existing->mr, subpage_t, iomem);
1146 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1147 end = start + int128_get64(section->size) - 1;
1148 subpage_register(subpage, start, end,
1149 phys_section_add(&d->map, section));
1153 static void register_multipage(FlatView *fv,
1154 MemoryRegionSection *section)
1156 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1157 hwaddr start_addr = section->offset_within_address_space;
1158 uint16_t section_index = phys_section_add(&d->map, section);
1159 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1160 TARGET_PAGE_BITS));
1162 assert(num_pages);
1163 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1167 * The range in *section* may look like this:
1169 * |s|PPPPPPP|s|
1171 * where s stands for subpage and P for page.
1173 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1175 MemoryRegionSection remain = *section;
1176 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1178 /* register first subpage */
1179 if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1180 uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1181 - remain.offset_within_address_space;
1183 MemoryRegionSection now = remain;
1184 now.size = int128_min(int128_make64(left), now.size);
1185 register_subpage(fv, &now);
1186 if (int128_eq(remain.size, now.size)) {
1187 return;
1189 remain.size = int128_sub(remain.size, now.size);
1190 remain.offset_within_address_space += int128_get64(now.size);
1191 remain.offset_within_region += int128_get64(now.size);
1194 /* register whole pages */
1195 if (int128_ge(remain.size, page_size)) {
1196 MemoryRegionSection now = remain;
1197 now.size = int128_and(now.size, int128_neg(page_size));
1198 register_multipage(fv, &now);
1199 if (int128_eq(remain.size, now.size)) {
1200 return;
1202 remain.size = int128_sub(remain.size, now.size);
1203 remain.offset_within_address_space += int128_get64(now.size);
1204 remain.offset_within_region += int128_get64(now.size);
1207 /* register last subpage */
1208 register_subpage(fv, &remain);
1211 void qemu_flush_coalesced_mmio_buffer(void)
1213 if (kvm_enabled())
1214 kvm_flush_coalesced_mmio_buffer();
1217 void qemu_mutex_lock_ramlist(void)
1219 qemu_mutex_lock(&ram_list.mutex);
1222 void qemu_mutex_unlock_ramlist(void)
1224 qemu_mutex_unlock(&ram_list.mutex);
1227 void ram_block_dump(Monitor *mon)
1229 RAMBlock *block;
1230 char *psize;
1232 RCU_READ_LOCK_GUARD();
1233 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1234 "Block Name", "PSize", "Offset", "Used", "Total");
1235 RAMBLOCK_FOREACH(block) {
1236 psize = size_to_str(block->page_size);
1237 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1238 " 0x%016" PRIx64 "\n", block->idstr, psize,
1239 (uint64_t)block->offset,
1240 (uint64_t)block->used_length,
1241 (uint64_t)block->max_length);
1242 g_free(psize);
1246 #ifdef __linux__
1248 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1249 * may or may not name the same files / on the same filesystem now as
1250 * when we actually open and map them. Iterate over the file
1251 * descriptors instead, and use qemu_fd_getpagesize().
1253 static int find_min_backend_pagesize(Object *obj, void *opaque)
1255 long *hpsize_min = opaque;
1257 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1258 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1259 long hpsize = host_memory_backend_pagesize(backend);
1261 if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
1262 *hpsize_min = hpsize;
1266 return 0;
1269 static int find_max_backend_pagesize(Object *obj, void *opaque)
1271 long *hpsize_max = opaque;
1273 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1274 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1275 long hpsize = host_memory_backend_pagesize(backend);
1277 if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1278 *hpsize_max = hpsize;
1282 return 0;
1286 * TODO: We assume right now that all mapped host memory backends are
1287 * used as RAM, however some might be used for different purposes.
1289 long qemu_minrampagesize(void)
1291 long hpsize = LONG_MAX;
1292 Object *memdev_root = object_resolve_path("/objects", NULL);
1294 object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
1295 return hpsize;
1298 long qemu_maxrampagesize(void)
1300 long pagesize = 0;
1301 Object *memdev_root = object_resolve_path("/objects", NULL);
1303 object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
1304 return pagesize;
1306 #else
1307 long qemu_minrampagesize(void)
1309 return qemu_real_host_page_size;
1311 long qemu_maxrampagesize(void)
1313 return qemu_real_host_page_size;
1315 #endif
1317 #ifdef CONFIG_POSIX
1318 static int64_t get_file_size(int fd)
1320 int64_t size;
1321 #if defined(__linux__)
1322 struct stat st;
1324 if (fstat(fd, &st) < 0) {
1325 return -errno;
1328 /* Special handling for devdax character devices */
1329 if (S_ISCHR(st.st_mode)) {
1330 g_autofree char *subsystem_path = NULL;
1331 g_autofree char *subsystem = NULL;
1333 subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1334 major(st.st_rdev), minor(st.st_rdev));
1335 subsystem = g_file_read_link(subsystem_path, NULL);
1337 if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
1338 g_autofree char *size_path = NULL;
1339 g_autofree char *size_str = NULL;
1341 size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
1342 major(st.st_rdev), minor(st.st_rdev));
1344 if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
1345 return g_ascii_strtoll(size_str, NULL, 0);
1349 #endif /* defined(__linux__) */
1351 /* st.st_size may be zero for special files yet lseek(2) works */
1352 size = lseek(fd, 0, SEEK_END);
1353 if (size < 0) {
1354 return -errno;
1356 return size;
1359 static int64_t get_file_align(int fd)
1361 int64_t align = -1;
1362 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1363 struct stat st;
1365 if (fstat(fd, &st) < 0) {
1366 return -errno;
1369 /* Special handling for devdax character devices */
1370 if (S_ISCHR(st.st_mode)) {
1371 g_autofree char *path = NULL;
1372 g_autofree char *rpath = NULL;
1373 struct daxctl_ctx *ctx;
1374 struct daxctl_region *region;
1375 int rc = 0;
1377 path = g_strdup_printf("/sys/dev/char/%d:%d",
1378 major(st.st_rdev), minor(st.st_rdev));
1379 rpath = realpath(path, NULL);
1381 rc = daxctl_new(&ctx);
1382 if (rc) {
1383 return -1;
1386 daxctl_region_foreach(ctx, region) {
1387 if (strstr(rpath, daxctl_region_get_path(region))) {
1388 align = daxctl_region_get_align(region);
1389 break;
1392 daxctl_unref(ctx);
1394 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1396 return align;
1399 static int file_ram_open(const char *path,
1400 const char *region_name,
1401 bool *created,
1402 Error **errp)
1404 char *filename;
1405 char *sanitized_name;
1406 char *c;
1407 int fd = -1;
1409 *created = false;
1410 for (;;) {
1411 fd = open(path, O_RDWR);
1412 if (fd >= 0) {
1413 /* @path names an existing file, use it */
1414 break;
1416 if (errno == ENOENT) {
1417 /* @path names a file that doesn't exist, create it */
1418 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1419 if (fd >= 0) {
1420 *created = true;
1421 break;
1423 } else if (errno == EISDIR) {
1424 /* @path names a directory, create a file there */
1425 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1426 sanitized_name = g_strdup(region_name);
1427 for (c = sanitized_name; *c != '\0'; c++) {
1428 if (*c == '/') {
1429 *c = '_';
1433 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1434 sanitized_name);
1435 g_free(sanitized_name);
1437 fd = mkstemp(filename);
1438 if (fd >= 0) {
1439 unlink(filename);
1440 g_free(filename);
1441 break;
1443 g_free(filename);
1445 if (errno != EEXIST && errno != EINTR) {
1446 error_setg_errno(errp, errno,
1447 "can't open backing store %s for guest RAM",
1448 path);
1449 return -1;
1452 * Try again on EINTR and EEXIST. The latter happens when
1453 * something else creates the file between our two open().
1457 return fd;
1460 static void *file_ram_alloc(RAMBlock *block,
1461 ram_addr_t memory,
1462 int fd,
1463 bool truncate,
1464 Error **errp)
1466 void *area;
1468 block->page_size = qemu_fd_getpagesize(fd);
1469 if (block->mr->align % block->page_size) {
1470 error_setg(errp, "alignment 0x%" PRIx64
1471 " must be multiples of page size 0x%zx",
1472 block->mr->align, block->page_size);
1473 return NULL;
1474 } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1475 error_setg(errp, "alignment 0x%" PRIx64
1476 " must be a power of two", block->mr->align);
1477 return NULL;
1479 block->mr->align = MAX(block->page_size, block->mr->align);
1480 #if defined(__s390x__)
1481 if (kvm_enabled()) {
1482 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1484 #endif
1486 if (memory < block->page_size) {
1487 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1488 "or larger than page size 0x%zx",
1489 memory, block->page_size);
1490 return NULL;
1493 memory = ROUND_UP(memory, block->page_size);
1496 * ftruncate is not supported by hugetlbfs in older
1497 * hosts, so don't bother bailing out on errors.
1498 * If anything goes wrong with it under other filesystems,
1499 * mmap will fail.
1501 * Do not truncate the non-empty backend file to avoid corrupting
1502 * the existing data in the file. Disabling shrinking is not
1503 * enough. For example, the current vNVDIMM implementation stores
1504 * the guest NVDIMM labels at the end of the backend file. If the
1505 * backend file is later extended, QEMU will not be able to find
1506 * those labels. Therefore, extending the non-empty backend file
1507 * is disabled as well.
1509 if (truncate && ftruncate(fd, memory)) {
1510 perror("ftruncate");
1513 area = qemu_ram_mmap(fd, memory, block->mr->align,
1514 block->flags & RAM_SHARED, block->flags & RAM_PMEM);
1515 if (area == MAP_FAILED) {
1516 error_setg_errno(errp, errno,
1517 "unable to map backing store for guest RAM");
1518 return NULL;
1521 block->fd = fd;
1522 return area;
1524 #endif
1526 /* Allocate space within the ram_addr_t space that governs the
1527 * dirty bitmaps.
1528 * Called with the ramlist lock held.
1530 static ram_addr_t find_ram_offset(ram_addr_t size)
1532 RAMBlock *block, *next_block;
1533 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1535 assert(size != 0); /* it would hand out same offset multiple times */
1537 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1538 return 0;
1541 RAMBLOCK_FOREACH(block) {
1542 ram_addr_t candidate, next = RAM_ADDR_MAX;
1544 /* Align blocks to start on a 'long' in the bitmap
1545 * which makes the bitmap sync'ing take the fast path.
1547 candidate = block->offset + block->max_length;
1548 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1550 /* Search for the closest following block
1551 * and find the gap.
1553 RAMBLOCK_FOREACH(next_block) {
1554 if (next_block->offset >= candidate) {
1555 next = MIN(next, next_block->offset);
1559 /* If it fits remember our place and remember the size
1560 * of gap, but keep going so that we might find a smaller
1561 * gap to fill so avoiding fragmentation.
1563 if (next - candidate >= size && next - candidate < mingap) {
1564 offset = candidate;
1565 mingap = next - candidate;
1568 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1571 if (offset == RAM_ADDR_MAX) {
1572 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1573 (uint64_t)size);
1574 abort();
1577 trace_find_ram_offset(size, offset);
1579 return offset;
1582 static unsigned long last_ram_page(void)
1584 RAMBlock *block;
1585 ram_addr_t last = 0;
1587 RCU_READ_LOCK_GUARD();
1588 RAMBLOCK_FOREACH(block) {
1589 last = MAX(last, block->offset + block->max_length);
1591 return last >> TARGET_PAGE_BITS;
1594 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1596 int ret;
1598 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1599 if (!machine_dump_guest_core(current_machine)) {
1600 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1601 if (ret) {
1602 perror("qemu_madvise");
1603 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1604 "but dump_guest_core=off specified\n");
1609 const char *qemu_ram_get_idstr(RAMBlock *rb)
1611 return rb->idstr;
1614 void *qemu_ram_get_host_addr(RAMBlock *rb)
1616 return rb->host;
1619 ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
1621 return rb->offset;
1624 ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
1626 return rb->used_length;
1629 bool qemu_ram_is_shared(RAMBlock *rb)
1631 return rb->flags & RAM_SHARED;
1634 /* Note: Only set at the start of postcopy */
1635 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1637 return rb->flags & RAM_UF_ZEROPAGE;
1640 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1642 rb->flags |= RAM_UF_ZEROPAGE;
1645 bool qemu_ram_is_migratable(RAMBlock *rb)
1647 return rb->flags & RAM_MIGRATABLE;
1650 void qemu_ram_set_migratable(RAMBlock *rb)
1652 rb->flags |= RAM_MIGRATABLE;
1655 void qemu_ram_unset_migratable(RAMBlock *rb)
1657 rb->flags &= ~RAM_MIGRATABLE;
1660 /* Called with iothread lock held. */
1661 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1663 RAMBlock *block;
1665 assert(new_block);
1666 assert(!new_block->idstr[0]);
1668 if (dev) {
1669 char *id = qdev_get_dev_path(dev);
1670 if (id) {
1671 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1672 g_free(id);
1675 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1677 RCU_READ_LOCK_GUARD();
1678 RAMBLOCK_FOREACH(block) {
1679 if (block != new_block &&
1680 !strcmp(block->idstr, new_block->idstr)) {
1681 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1682 new_block->idstr);
1683 abort();
1688 /* Called with iothread lock held. */
1689 void qemu_ram_unset_idstr(RAMBlock *block)
1691 /* FIXME: arch_init.c assumes that this is not called throughout
1692 * migration. Ignore the problem since hot-unplug during migration
1693 * does not work anyway.
1695 if (block) {
1696 memset(block->idstr, 0, sizeof(block->idstr));
1700 size_t qemu_ram_pagesize(RAMBlock *rb)
1702 return rb->page_size;
1705 /* Returns the largest size of page in use */
1706 size_t qemu_ram_pagesize_largest(void)
1708 RAMBlock *block;
1709 size_t largest = 0;
1711 RAMBLOCK_FOREACH(block) {
1712 largest = MAX(largest, qemu_ram_pagesize(block));
1715 return largest;
1718 static int memory_try_enable_merging(void *addr, size_t len)
1720 if (!machine_mem_merge(current_machine)) {
1721 /* disabled by the user */
1722 return 0;
1725 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1728 /* Only legal before guest might have detected the memory size: e.g. on
1729 * incoming migration, or right after reset.
1731 * As memory core doesn't know how is memory accessed, it is up to
1732 * resize callback to update device state and/or add assertions to detect
1733 * misuse, if necessary.
1735 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1737 const ram_addr_t unaligned_size = newsize;
1739 assert(block);
1741 newsize = HOST_PAGE_ALIGN(newsize);
1743 if (block->used_length == newsize) {
1745 * We don't have to resize the ram block (which only knows aligned
1746 * sizes), however, we have to notify if the unaligned size changed.
1748 if (unaligned_size != memory_region_size(block->mr)) {
1749 memory_region_set_size(block->mr, unaligned_size);
1750 if (block->resized) {
1751 block->resized(block->idstr, unaligned_size, block->host);
1754 return 0;
1757 if (!(block->flags & RAM_RESIZEABLE)) {
1758 error_setg_errno(errp, EINVAL,
1759 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1760 " in != 0x" RAM_ADDR_FMT, block->idstr,
1761 newsize, block->used_length);
1762 return -EINVAL;
1765 if (block->max_length < newsize) {
1766 error_setg_errno(errp, EINVAL,
1767 "Length too large: %s: 0x" RAM_ADDR_FMT
1768 " > 0x" RAM_ADDR_FMT, block->idstr,
1769 newsize, block->max_length);
1770 return -EINVAL;
1773 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1774 block->used_length = newsize;
1775 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1776 DIRTY_CLIENTS_ALL);
1777 memory_region_set_size(block->mr, unaligned_size);
1778 if (block->resized) {
1779 block->resized(block->idstr, unaligned_size, block->host);
1781 return 0;
1785 * Trigger sync on the given ram block for range [start, start + length]
1786 * with the backing store if one is available.
1787 * Otherwise no-op.
1788 * @Note: this is supposed to be a synchronous op.
1790 void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
1792 /* The requested range should fit in within the block range */
1793 g_assert((start + length) <= block->used_length);
1795 #ifdef CONFIG_LIBPMEM
1796 /* The lack of support for pmem should not block the sync */
1797 if (ramblock_is_pmem(block)) {
1798 void *addr = ramblock_ptr(block, start);
1799 pmem_persist(addr, length);
1800 return;
1802 #endif
1803 if (block->fd >= 0) {
1805 * Case there is no support for PMEM or the memory has not been
1806 * specified as persistent (or is not one) - use the msync.
1807 * Less optimal but still achieves the same goal
1809 void *addr = ramblock_ptr(block, start);
1810 if (qemu_msync(addr, length, block->fd)) {
1811 warn_report("%s: failed to sync memory range: start: "
1812 RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
1813 __func__, start, length);
1818 /* Called with ram_list.mutex held */
1819 static void dirty_memory_extend(ram_addr_t old_ram_size,
1820 ram_addr_t new_ram_size)
1822 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1823 DIRTY_MEMORY_BLOCK_SIZE);
1824 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1825 DIRTY_MEMORY_BLOCK_SIZE);
1826 int i;
1828 /* Only need to extend if block count increased */
1829 if (new_num_blocks <= old_num_blocks) {
1830 return;
1833 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1834 DirtyMemoryBlocks *old_blocks;
1835 DirtyMemoryBlocks *new_blocks;
1836 int j;
1838 old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
1839 new_blocks = g_malloc(sizeof(*new_blocks) +
1840 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1842 if (old_num_blocks) {
1843 memcpy(new_blocks->blocks, old_blocks->blocks,
1844 old_num_blocks * sizeof(old_blocks->blocks[0]));
1847 for (j = old_num_blocks; j < new_num_blocks; j++) {
1848 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1851 qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1853 if (old_blocks) {
1854 g_free_rcu(old_blocks, rcu);
1859 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
1861 RAMBlock *block;
1862 RAMBlock *last_block = NULL;
1863 ram_addr_t old_ram_size, new_ram_size;
1864 Error *err = NULL;
1866 old_ram_size = last_ram_page();
1868 qemu_mutex_lock_ramlist();
1869 new_block->offset = find_ram_offset(new_block->max_length);
1871 if (!new_block->host) {
1872 if (xen_enabled()) {
1873 xen_ram_alloc(new_block->offset, new_block->max_length,
1874 new_block->mr, &err);
1875 if (err) {
1876 error_propagate(errp, err);
1877 qemu_mutex_unlock_ramlist();
1878 return;
1880 } else {
1881 new_block->host = phys_mem_alloc(new_block->max_length,
1882 &new_block->mr->align, shared);
1883 if (!new_block->host) {
1884 error_setg_errno(errp, errno,
1885 "cannot set up guest memory '%s'",
1886 memory_region_name(new_block->mr));
1887 qemu_mutex_unlock_ramlist();
1888 return;
1890 memory_try_enable_merging(new_block->host, new_block->max_length);
1894 new_ram_size = MAX(old_ram_size,
1895 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1896 if (new_ram_size > old_ram_size) {
1897 dirty_memory_extend(old_ram_size, new_ram_size);
1899 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1900 * QLIST (which has an RCU-friendly variant) does not have insertion at
1901 * tail, so save the last element in last_block.
1903 RAMBLOCK_FOREACH(block) {
1904 last_block = block;
1905 if (block->max_length < new_block->max_length) {
1906 break;
1909 if (block) {
1910 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1911 } else if (last_block) {
1912 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
1913 } else { /* list is empty */
1914 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1916 ram_list.mru_block = NULL;
1918 /* Write list before version */
1919 smp_wmb();
1920 ram_list.version++;
1921 qemu_mutex_unlock_ramlist();
1923 cpu_physical_memory_set_dirty_range(new_block->offset,
1924 new_block->used_length,
1925 DIRTY_CLIENTS_ALL);
1927 if (new_block->host) {
1928 qemu_ram_setup_dump(new_block->host, new_block->max_length);
1929 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
1931 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
1932 * Configure it unless the machine is a qtest server, in which case
1933 * KVM is not used and it may be forked (eg for fuzzing purposes).
1935 if (!qtest_enabled()) {
1936 qemu_madvise(new_block->host, new_block->max_length,
1937 QEMU_MADV_DONTFORK);
1939 ram_block_notify_add(new_block->host, new_block->max_length);
1943 #ifdef CONFIG_POSIX
1944 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
1945 uint32_t ram_flags, int fd,
1946 Error **errp)
1948 RAMBlock *new_block;
1949 Error *local_err = NULL;
1950 int64_t file_size, file_align;
1952 /* Just support these ram flags by now. */
1953 assert((ram_flags & ~(RAM_SHARED | RAM_PMEM)) == 0);
1955 if (xen_enabled()) {
1956 error_setg(errp, "-mem-path not supported with Xen");
1957 return NULL;
1960 if (kvm_enabled() && !kvm_has_sync_mmu()) {
1961 error_setg(errp,
1962 "host lacks kvm mmu notifiers, -mem-path unsupported");
1963 return NULL;
1966 if (phys_mem_alloc != qemu_anon_ram_alloc) {
1968 * file_ram_alloc() needs to allocate just like
1969 * phys_mem_alloc, but we haven't bothered to provide
1970 * a hook there.
1972 error_setg(errp,
1973 "-mem-path not supported with this accelerator");
1974 return NULL;
1977 size = HOST_PAGE_ALIGN(size);
1978 file_size = get_file_size(fd);
1979 if (file_size > 0 && file_size < size) {
1980 error_setg(errp, "backing store size 0x%" PRIx64
1981 " does not match 'size' option 0x" RAM_ADDR_FMT,
1982 file_size, size);
1983 return NULL;
1986 file_align = get_file_align(fd);
1987 if (file_align > 0 && mr && file_align > mr->align) {
1988 error_setg(errp, "backing store align 0x%" PRIx64
1989 " is larger than 'align' option 0x%" PRIx64,
1990 file_align, mr->align);
1991 return NULL;
1994 new_block = g_malloc0(sizeof(*new_block));
1995 new_block->mr = mr;
1996 new_block->used_length = size;
1997 new_block->max_length = size;
1998 new_block->flags = ram_flags;
1999 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
2000 if (!new_block->host) {
2001 g_free(new_block);
2002 return NULL;
2005 ram_block_add(new_block, &local_err, ram_flags & RAM_SHARED);
2006 if (local_err) {
2007 g_free(new_block);
2008 error_propagate(errp, local_err);
2009 return NULL;
2011 return new_block;
2016 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2017 uint32_t ram_flags, const char *mem_path,
2018 Error **errp)
2020 int fd;
2021 bool created;
2022 RAMBlock *block;
2024 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2025 if (fd < 0) {
2026 return NULL;
2029 block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, errp);
2030 if (!block) {
2031 if (created) {
2032 unlink(mem_path);
2034 close(fd);
2035 return NULL;
2038 return block;
2040 #endif
2042 static
2043 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2044 void (*resized)(const char*,
2045 uint64_t length,
2046 void *host),
2047 void *host, bool resizeable, bool share,
2048 MemoryRegion *mr, Error **errp)
2050 RAMBlock *new_block;
2051 Error *local_err = NULL;
2053 size = HOST_PAGE_ALIGN(size);
2054 max_size = HOST_PAGE_ALIGN(max_size);
2055 new_block = g_malloc0(sizeof(*new_block));
2056 new_block->mr = mr;
2057 new_block->resized = resized;
2058 new_block->used_length = size;
2059 new_block->max_length = max_size;
2060 assert(max_size >= size);
2061 new_block->fd = -1;
2062 new_block->page_size = qemu_real_host_page_size;
2063 new_block->host = host;
2064 if (host) {
2065 new_block->flags |= RAM_PREALLOC;
2067 if (resizeable) {
2068 new_block->flags |= RAM_RESIZEABLE;
2070 ram_block_add(new_block, &local_err, share);
2071 if (local_err) {
2072 g_free(new_block);
2073 error_propagate(errp, local_err);
2074 return NULL;
2076 return new_block;
2079 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2080 MemoryRegion *mr, Error **errp)
2082 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2083 false, mr, errp);
2086 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2087 MemoryRegion *mr, Error **errp)
2089 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2090 share, mr, errp);
2093 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2094 void (*resized)(const char*,
2095 uint64_t length,
2096 void *host),
2097 MemoryRegion *mr, Error **errp)
2099 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2100 false, mr, errp);
2103 static void reclaim_ramblock(RAMBlock *block)
2105 if (block->flags & RAM_PREALLOC) {
2107 } else if (xen_enabled()) {
2108 xen_invalidate_map_cache_entry(block->host);
2109 #ifndef _WIN32
2110 } else if (block->fd >= 0) {
2111 qemu_ram_munmap(block->fd, block->host, block->max_length);
2112 close(block->fd);
2113 #endif
2114 } else {
2115 qemu_anon_ram_free(block->host, block->max_length);
2117 g_free(block);
2120 void qemu_ram_free(RAMBlock *block)
2122 if (!block) {
2123 return;
2126 if (block->host) {
2127 ram_block_notify_remove(block->host, block->max_length);
2130 qemu_mutex_lock_ramlist();
2131 QLIST_REMOVE_RCU(block, next);
2132 ram_list.mru_block = NULL;
2133 /* Write list before version */
2134 smp_wmb();
2135 ram_list.version++;
2136 call_rcu(block, reclaim_ramblock, rcu);
2137 qemu_mutex_unlock_ramlist();
2140 #ifndef _WIN32
2141 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2143 RAMBlock *block;
2144 ram_addr_t offset;
2145 int flags;
2146 void *area, *vaddr;
2148 RAMBLOCK_FOREACH(block) {
2149 offset = addr - block->offset;
2150 if (offset < block->max_length) {
2151 vaddr = ramblock_ptr(block, offset);
2152 if (block->flags & RAM_PREALLOC) {
2154 } else if (xen_enabled()) {
2155 abort();
2156 } else {
2157 flags = MAP_FIXED;
2158 if (block->fd >= 0) {
2159 flags |= (block->flags & RAM_SHARED ?
2160 MAP_SHARED : MAP_PRIVATE);
2161 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2162 flags, block->fd, offset);
2163 } else {
2165 * Remap needs to match alloc. Accelerators that
2166 * set phys_mem_alloc never remap. If they did,
2167 * we'd need a remap hook here.
2169 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2171 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2172 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2173 flags, -1, 0);
2175 if (area != vaddr) {
2176 error_report("Could not remap addr: "
2177 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2178 length, addr);
2179 exit(1);
2181 memory_try_enable_merging(vaddr, length);
2182 qemu_ram_setup_dump(vaddr, length);
2187 #endif /* !_WIN32 */
2189 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2190 * This should not be used for general purpose DMA. Use address_space_map
2191 * or address_space_rw instead. For local memory (e.g. video ram) that the
2192 * device owns, use memory_region_get_ram_ptr.
2194 * Called within RCU critical section.
2196 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2198 RAMBlock *block = ram_block;
2200 if (block == NULL) {
2201 block = qemu_get_ram_block(addr);
2202 addr -= block->offset;
2205 if (xen_enabled() && block->host == NULL) {
2206 /* We need to check if the requested address is in the RAM
2207 * because we don't want to map the entire memory in QEMU.
2208 * In that case just map until the end of the page.
2210 if (block->offset == 0) {
2211 return xen_map_cache(addr, 0, 0, false);
2214 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2216 return ramblock_ptr(block, addr);
2219 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2220 * but takes a size argument.
2222 * Called within RCU critical section.
2224 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2225 hwaddr *size, bool lock)
2227 RAMBlock *block = ram_block;
2228 if (*size == 0) {
2229 return NULL;
2232 if (block == NULL) {
2233 block = qemu_get_ram_block(addr);
2234 addr -= block->offset;
2236 *size = MIN(*size, block->max_length - addr);
2238 if (xen_enabled() && block->host == NULL) {
2239 /* We need to check if the requested address is in the RAM
2240 * because we don't want to map the entire memory in QEMU.
2241 * In that case just map the requested area.
2243 if (block->offset == 0) {
2244 return xen_map_cache(addr, *size, lock, lock);
2247 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2250 return ramblock_ptr(block, addr);
2253 /* Return the offset of a hostpointer within a ramblock */
2254 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2256 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2257 assert((uintptr_t)host >= (uintptr_t)rb->host);
2258 assert(res < rb->max_length);
2260 return res;
2264 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2265 * in that RAMBlock.
2267 * ptr: Host pointer to look up
2268 * round_offset: If true round the result offset down to a page boundary
2269 * *ram_addr: set to result ram_addr
2270 * *offset: set to result offset within the RAMBlock
2272 * Returns: RAMBlock (or NULL if not found)
2274 * By the time this function returns, the returned pointer is not protected
2275 * by RCU anymore. If the caller is not within an RCU critical section and
2276 * does not hold the iothread lock, it must have other means of protecting the
2277 * pointer, such as a reference to the region that includes the incoming
2278 * ram_addr_t.
2280 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2281 ram_addr_t *offset)
2283 RAMBlock *block;
2284 uint8_t *host = ptr;
2286 if (xen_enabled()) {
2287 ram_addr_t ram_addr;
2288 RCU_READ_LOCK_GUARD();
2289 ram_addr = xen_ram_addr_from_mapcache(ptr);
2290 block = qemu_get_ram_block(ram_addr);
2291 if (block) {
2292 *offset = ram_addr - block->offset;
2294 return block;
2297 RCU_READ_LOCK_GUARD();
2298 block = qatomic_rcu_read(&ram_list.mru_block);
2299 if (block && block->host && host - block->host < block->max_length) {
2300 goto found;
2303 RAMBLOCK_FOREACH(block) {
2304 /* This case append when the block is not mapped. */
2305 if (block->host == NULL) {
2306 continue;
2308 if (host - block->host < block->max_length) {
2309 goto found;
2313 return NULL;
2315 found:
2316 *offset = (host - block->host);
2317 if (round_offset) {
2318 *offset &= TARGET_PAGE_MASK;
2320 return block;
2324 * Finds the named RAMBlock
2326 * name: The name of RAMBlock to find
2328 * Returns: RAMBlock (or NULL if not found)
2330 RAMBlock *qemu_ram_block_by_name(const char *name)
2332 RAMBlock *block;
2334 RAMBLOCK_FOREACH(block) {
2335 if (!strcmp(name, block->idstr)) {
2336 return block;
2340 return NULL;
2343 /* Some of the softmmu routines need to translate from a host pointer
2344 (typically a TLB entry) back to a ram offset. */
2345 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2347 RAMBlock *block;
2348 ram_addr_t offset;
2350 block = qemu_ram_block_from_host(ptr, false, &offset);
2351 if (!block) {
2352 return RAM_ADDR_INVALID;
2355 return block->offset + offset;
2358 /* Generate a debug exception if a watchpoint has been hit. */
2359 void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
2360 MemTxAttrs attrs, int flags, uintptr_t ra)
2362 CPUClass *cc = CPU_GET_CLASS(cpu);
2363 CPUWatchpoint *wp;
2365 assert(tcg_enabled());
2366 if (cpu->watchpoint_hit) {
2368 * We re-entered the check after replacing the TB.
2369 * Now raise the debug interrupt so that it will
2370 * trigger after the current instruction.
2372 qemu_mutex_lock_iothread();
2373 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2374 qemu_mutex_unlock_iothread();
2375 return;
2378 addr = cc->adjust_watchpoint_address(cpu, addr, len);
2379 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2380 if (watchpoint_address_matches(wp, addr, len)
2381 && (wp->flags & flags)) {
2382 if (replay_running_debug()) {
2384 * Don't process the watchpoints when we are
2385 * in a reverse debugging operation.
2387 replay_breakpoint();
2388 return;
2390 if (flags == BP_MEM_READ) {
2391 wp->flags |= BP_WATCHPOINT_HIT_READ;
2392 } else {
2393 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2395 wp->hitaddr = MAX(addr, wp->vaddr);
2396 wp->hitattrs = attrs;
2397 if (!cpu->watchpoint_hit) {
2398 if (wp->flags & BP_CPU &&
2399 !cc->debug_check_watchpoint(cpu, wp)) {
2400 wp->flags &= ~BP_WATCHPOINT_HIT;
2401 continue;
2403 cpu->watchpoint_hit = wp;
2405 mmap_lock();
2406 tb_check_watchpoint(cpu, ra);
2407 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2408 cpu->exception_index = EXCP_DEBUG;
2409 mmap_unlock();
2410 cpu_loop_exit_restore(cpu, ra);
2411 } else {
2412 /* Force execution of one insn next time. */
2413 cpu->cflags_next_tb = 1 | curr_cflags();
2414 mmap_unlock();
2415 if (ra) {
2416 cpu_restore_state(cpu, ra, true);
2418 cpu_loop_exit_noexc(cpu);
2421 } else {
2422 wp->flags &= ~BP_WATCHPOINT_HIT;
2427 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2428 MemTxAttrs attrs, void *buf, hwaddr len);
2429 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2430 const void *buf, hwaddr len);
2431 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2432 bool is_write, MemTxAttrs attrs);
2434 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2435 unsigned len, MemTxAttrs attrs)
2437 subpage_t *subpage = opaque;
2438 uint8_t buf[8];
2439 MemTxResult res;
2441 #if defined(DEBUG_SUBPAGE)
2442 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2443 subpage, len, addr);
2444 #endif
2445 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2446 if (res) {
2447 return res;
2449 *data = ldn_p(buf, len);
2450 return MEMTX_OK;
2453 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2454 uint64_t value, unsigned len, MemTxAttrs attrs)
2456 subpage_t *subpage = opaque;
2457 uint8_t buf[8];
2459 #if defined(DEBUG_SUBPAGE)
2460 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2461 " value %"PRIx64"\n",
2462 __func__, subpage, len, addr, value);
2463 #endif
2464 stn_p(buf, len, value);
2465 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2468 static bool subpage_accepts(void *opaque, hwaddr addr,
2469 unsigned len, bool is_write,
2470 MemTxAttrs attrs)
2472 subpage_t *subpage = opaque;
2473 #if defined(DEBUG_SUBPAGE)
2474 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2475 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2476 #endif
2478 return flatview_access_valid(subpage->fv, addr + subpage->base,
2479 len, is_write, attrs);
2482 static const MemoryRegionOps subpage_ops = {
2483 .read_with_attrs = subpage_read,
2484 .write_with_attrs = subpage_write,
2485 .impl.min_access_size = 1,
2486 .impl.max_access_size = 8,
2487 .valid.min_access_size = 1,
2488 .valid.max_access_size = 8,
2489 .valid.accepts = subpage_accepts,
2490 .endianness = DEVICE_NATIVE_ENDIAN,
2493 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2494 uint16_t section)
2496 int idx, eidx;
2498 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2499 return -1;
2500 idx = SUBPAGE_IDX(start);
2501 eidx = SUBPAGE_IDX(end);
2502 #if defined(DEBUG_SUBPAGE)
2503 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2504 __func__, mmio, start, end, idx, eidx, section);
2505 #endif
2506 for (; idx <= eidx; idx++) {
2507 mmio->sub_section[idx] = section;
2510 return 0;
2513 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2515 subpage_t *mmio;
2517 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2518 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2519 mmio->fv = fv;
2520 mmio->base = base;
2521 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2522 NULL, TARGET_PAGE_SIZE);
2523 mmio->iomem.subpage = true;
2524 #if defined(DEBUG_SUBPAGE)
2525 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2526 mmio, base, TARGET_PAGE_SIZE);
2527 #endif
2529 return mmio;
2532 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2534 assert(fv);
2535 MemoryRegionSection section = {
2536 .fv = fv,
2537 .mr = mr,
2538 .offset_within_address_space = 0,
2539 .offset_within_region = 0,
2540 .size = int128_2_64(),
2543 return phys_section_add(map, &section);
2546 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2547 hwaddr index, MemTxAttrs attrs)
2549 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2550 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2551 AddressSpaceDispatch *d = qatomic_rcu_read(&cpuas->memory_dispatch);
2552 MemoryRegionSection *sections = d->map.sections;
2554 return &sections[index & ~TARGET_PAGE_MASK];
2557 static void io_mem_init(void)
2559 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2560 NULL, UINT64_MAX);
2563 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2565 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2566 uint16_t n;
2568 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2569 assert(n == PHYS_SECTION_UNASSIGNED);
2571 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2573 return d;
2576 void address_space_dispatch_free(AddressSpaceDispatch *d)
2578 phys_sections_free(&d->map);
2579 g_free(d);
2582 static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2586 static void tcg_log_global_after_sync(MemoryListener *listener)
2588 CPUAddressSpace *cpuas;
2590 /* Wait for the CPU to end the current TB. This avoids the following
2591 * incorrect race:
2593 * vCPU migration
2594 * ---------------------- -------------------------
2595 * TLB check -> slow path
2596 * notdirty_mem_write
2597 * write to RAM
2598 * mark dirty
2599 * clear dirty flag
2600 * TLB check -> fast path
2601 * read memory
2602 * write to RAM
2604 * by pushing the migration thread's memory read after the vCPU thread has
2605 * written the memory.
2607 if (replay_mode == REPLAY_MODE_NONE) {
2609 * VGA can make calls to this function while updating the screen.
2610 * In record/replay mode this causes a deadlock, because
2611 * run_on_cpu waits for rr mutex. Therefore no races are possible
2612 * in this case and no need for making run_on_cpu when
2613 * record/replay is not enabled.
2615 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2616 run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2620 static void tcg_commit(MemoryListener *listener)
2622 CPUAddressSpace *cpuas;
2623 AddressSpaceDispatch *d;
2625 assert(tcg_enabled());
2626 /* since each CPU stores ram addresses in its TLB cache, we must
2627 reset the modified entries */
2628 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2629 cpu_reloading_memory_map();
2630 /* The CPU and TLB are protected by the iothread lock.
2631 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2632 * may have split the RCU critical section.
2634 d = address_space_to_dispatch(cpuas->as);
2635 qatomic_rcu_set(&cpuas->memory_dispatch, d);
2636 tlb_flush(cpuas->cpu);
2639 static void memory_map_init(void)
2641 system_memory = g_malloc(sizeof(*system_memory));
2643 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2644 address_space_init(&address_space_memory, system_memory, "memory");
2646 system_io = g_malloc(sizeof(*system_io));
2647 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2648 65536);
2649 address_space_init(&address_space_io, system_io, "I/O");
2652 MemoryRegion *get_system_memory(void)
2654 return system_memory;
2657 MemoryRegion *get_system_io(void)
2659 return system_io;
2662 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2663 hwaddr length)
2665 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2666 addr += memory_region_get_ram_addr(mr);
2668 /* No early return if dirty_log_mask is or becomes 0, because
2669 * cpu_physical_memory_set_dirty_range will still call
2670 * xen_modified_memory.
2672 if (dirty_log_mask) {
2673 dirty_log_mask =
2674 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2676 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2677 assert(tcg_enabled());
2678 tb_invalidate_phys_range(addr, addr + length);
2679 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2681 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2684 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
2687 * In principle this function would work on other memory region types too,
2688 * but the ROM device use case is the only one where this operation is
2689 * necessary. Other memory regions should use the
2690 * address_space_read/write() APIs.
2692 assert(memory_region_is_romd(mr));
2694 invalidate_and_set_dirty(mr, addr, size);
2697 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2699 unsigned access_size_max = mr->ops->valid.max_access_size;
2701 /* Regions are assumed to support 1-4 byte accesses unless
2702 otherwise specified. */
2703 if (access_size_max == 0) {
2704 access_size_max = 4;
2707 /* Bound the maximum access by the alignment of the address. */
2708 if (!mr->ops->impl.unaligned) {
2709 unsigned align_size_max = addr & -addr;
2710 if (align_size_max != 0 && align_size_max < access_size_max) {
2711 access_size_max = align_size_max;
2715 /* Don't attempt accesses larger than the maximum. */
2716 if (l > access_size_max) {
2717 l = access_size_max;
2719 l = pow2floor(l);
2721 return l;
2724 static bool prepare_mmio_access(MemoryRegion *mr)
2726 bool unlocked = !qemu_mutex_iothread_locked();
2727 bool release_lock = false;
2729 if (unlocked) {
2730 qemu_mutex_lock_iothread();
2731 unlocked = false;
2732 release_lock = true;
2734 if (mr->flush_coalesced_mmio) {
2735 if (unlocked) {
2736 qemu_mutex_lock_iothread();
2738 qemu_flush_coalesced_mmio_buffer();
2739 if (unlocked) {
2740 qemu_mutex_unlock_iothread();
2744 return release_lock;
2747 /* Called within RCU critical section. */
2748 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
2749 MemTxAttrs attrs,
2750 const void *ptr,
2751 hwaddr len, hwaddr addr1,
2752 hwaddr l, MemoryRegion *mr)
2754 uint8_t *ram_ptr;
2755 uint64_t val;
2756 MemTxResult result = MEMTX_OK;
2757 bool release_lock = false;
2758 const uint8_t *buf = ptr;
2760 for (;;) {
2761 if (!memory_access_is_direct(mr, true)) {
2762 release_lock |= prepare_mmio_access(mr);
2763 l = memory_access_size(mr, l, addr1);
2764 /* XXX: could force current_cpu to NULL to avoid
2765 potential bugs */
2766 val = ldn_he_p(buf, l);
2767 result |= memory_region_dispatch_write(mr, addr1, val,
2768 size_memop(l), attrs);
2769 } else {
2770 /* RAM case */
2771 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2772 memcpy(ram_ptr, buf, l);
2773 invalidate_and_set_dirty(mr, addr1, l);
2776 if (release_lock) {
2777 qemu_mutex_unlock_iothread();
2778 release_lock = false;
2781 len -= l;
2782 buf += l;
2783 addr += l;
2785 if (!len) {
2786 break;
2789 l = len;
2790 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2793 return result;
2796 /* Called from RCU critical section. */
2797 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2798 const void *buf, hwaddr len)
2800 hwaddr l;
2801 hwaddr addr1;
2802 MemoryRegion *mr;
2803 MemTxResult result = MEMTX_OK;
2805 l = len;
2806 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2807 result = flatview_write_continue(fv, addr, attrs, buf, len,
2808 addr1, l, mr);
2810 return result;
2813 /* Called within RCU critical section. */
2814 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
2815 MemTxAttrs attrs, void *ptr,
2816 hwaddr len, hwaddr addr1, hwaddr l,
2817 MemoryRegion *mr)
2819 uint8_t *ram_ptr;
2820 uint64_t val;
2821 MemTxResult result = MEMTX_OK;
2822 bool release_lock = false;
2823 uint8_t *buf = ptr;
2825 for (;;) {
2826 if (!memory_access_is_direct(mr, false)) {
2827 /* I/O case */
2828 release_lock |= prepare_mmio_access(mr);
2829 l = memory_access_size(mr, l, addr1);
2830 result |= memory_region_dispatch_read(mr, addr1, &val,
2831 size_memop(l), attrs);
2832 stn_he_p(buf, l, val);
2833 } else {
2834 /* RAM case */
2835 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2836 memcpy(buf, ram_ptr, l);
2839 if (release_lock) {
2840 qemu_mutex_unlock_iothread();
2841 release_lock = false;
2844 len -= l;
2845 buf += l;
2846 addr += l;
2848 if (!len) {
2849 break;
2852 l = len;
2853 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2856 return result;
2859 /* Called from RCU critical section. */
2860 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2861 MemTxAttrs attrs, void *buf, hwaddr len)
2863 hwaddr l;
2864 hwaddr addr1;
2865 MemoryRegion *mr;
2867 l = len;
2868 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2869 return flatview_read_continue(fv, addr, attrs, buf, len,
2870 addr1, l, mr);
2873 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2874 MemTxAttrs attrs, void *buf, hwaddr len)
2876 MemTxResult result = MEMTX_OK;
2877 FlatView *fv;
2879 if (len > 0) {
2880 RCU_READ_LOCK_GUARD();
2881 fv = address_space_to_flatview(as);
2882 result = flatview_read(fv, addr, attrs, buf, len);
2885 return result;
2888 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2889 MemTxAttrs attrs,
2890 const void *buf, hwaddr len)
2892 MemTxResult result = MEMTX_OK;
2893 FlatView *fv;
2895 if (len > 0) {
2896 RCU_READ_LOCK_GUARD();
2897 fv = address_space_to_flatview(as);
2898 result = flatview_write(fv, addr, attrs, buf, len);
2901 return result;
2904 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2905 void *buf, hwaddr len, bool is_write)
2907 if (is_write) {
2908 return address_space_write(as, addr, attrs, buf, len);
2909 } else {
2910 return address_space_read_full(as, addr, attrs, buf, len);
2914 void cpu_physical_memory_rw(hwaddr addr, void *buf,
2915 hwaddr len, bool is_write)
2917 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
2918 buf, len, is_write);
2921 enum write_rom_type {
2922 WRITE_DATA,
2923 FLUSH_CACHE,
2926 static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
2927 hwaddr addr,
2928 MemTxAttrs attrs,
2929 const void *ptr,
2930 hwaddr len,
2931 enum write_rom_type type)
2933 hwaddr l;
2934 uint8_t *ram_ptr;
2935 hwaddr addr1;
2936 MemoryRegion *mr;
2937 const uint8_t *buf = ptr;
2939 RCU_READ_LOCK_GUARD();
2940 while (len > 0) {
2941 l = len;
2942 mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
2944 if (!(memory_region_is_ram(mr) ||
2945 memory_region_is_romd(mr))) {
2946 l = memory_access_size(mr, l, addr1);
2947 } else {
2948 /* ROM/RAM case */
2949 ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2950 switch (type) {
2951 case WRITE_DATA:
2952 memcpy(ram_ptr, buf, l);
2953 invalidate_and_set_dirty(mr, addr1, l);
2954 break;
2955 case FLUSH_CACHE:
2956 flush_icache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr + l);
2957 break;
2960 len -= l;
2961 buf += l;
2962 addr += l;
2964 return MEMTX_OK;
2967 /* used for ROM loading : can write in RAM and ROM */
2968 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
2969 MemTxAttrs attrs,
2970 const void *buf, hwaddr len)
2972 return address_space_write_rom_internal(as, addr, attrs,
2973 buf, len, WRITE_DATA);
2976 void cpu_flush_icache_range(hwaddr start, hwaddr len)
2979 * This function should do the same thing as an icache flush that was
2980 * triggered from within the guest. For TCG we are always cache coherent,
2981 * so there is no need to flush anything. For KVM / Xen we need to flush
2982 * the host's instruction cache at least.
2984 if (tcg_enabled()) {
2985 return;
2988 address_space_write_rom_internal(&address_space_memory,
2989 start, MEMTXATTRS_UNSPECIFIED,
2990 NULL, len, FLUSH_CACHE);
2993 typedef struct {
2994 MemoryRegion *mr;
2995 void *buffer;
2996 hwaddr addr;
2997 hwaddr len;
2998 bool in_use;
2999 } BounceBuffer;
3001 static BounceBuffer bounce;
3003 typedef struct MapClient {
3004 QEMUBH *bh;
3005 QLIST_ENTRY(MapClient) link;
3006 } MapClient;
3008 QemuMutex map_client_list_lock;
3009 static QLIST_HEAD(, MapClient) map_client_list
3010 = QLIST_HEAD_INITIALIZER(map_client_list);
3012 static void cpu_unregister_map_client_do(MapClient *client)
3014 QLIST_REMOVE(client, link);
3015 g_free(client);
3018 static void cpu_notify_map_clients_locked(void)
3020 MapClient *client;
3022 while (!QLIST_EMPTY(&map_client_list)) {
3023 client = QLIST_FIRST(&map_client_list);
3024 qemu_bh_schedule(client->bh);
3025 cpu_unregister_map_client_do(client);
3029 void cpu_register_map_client(QEMUBH *bh)
3031 MapClient *client = g_malloc(sizeof(*client));
3033 qemu_mutex_lock(&map_client_list_lock);
3034 client->bh = bh;
3035 QLIST_INSERT_HEAD(&map_client_list, client, link);
3036 if (!qatomic_read(&bounce.in_use)) {
3037 cpu_notify_map_clients_locked();
3039 qemu_mutex_unlock(&map_client_list_lock);
3042 void cpu_exec_init_all(void)
3044 qemu_mutex_init(&ram_list.mutex);
3045 /* The data structures we set up here depend on knowing the page size,
3046 * so no more changes can be made after this point.
3047 * In an ideal world, nothing we did before we had finished the
3048 * machine setup would care about the target page size, and we could
3049 * do this much later, rather than requiring board models to state
3050 * up front what their requirements are.
3052 finalize_target_page_bits();
3053 io_mem_init();
3054 memory_map_init();
3055 qemu_mutex_init(&map_client_list_lock);
3058 void cpu_unregister_map_client(QEMUBH *bh)
3060 MapClient *client;
3062 qemu_mutex_lock(&map_client_list_lock);
3063 QLIST_FOREACH(client, &map_client_list, link) {
3064 if (client->bh == bh) {
3065 cpu_unregister_map_client_do(client);
3066 break;
3069 qemu_mutex_unlock(&map_client_list_lock);
3072 static void cpu_notify_map_clients(void)
3074 qemu_mutex_lock(&map_client_list_lock);
3075 cpu_notify_map_clients_locked();
3076 qemu_mutex_unlock(&map_client_list_lock);
3079 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
3080 bool is_write, MemTxAttrs attrs)
3082 MemoryRegion *mr;
3083 hwaddr l, xlat;
3085 while (len > 0) {
3086 l = len;
3087 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3088 if (!memory_access_is_direct(mr, is_write)) {
3089 l = memory_access_size(mr, l, addr);
3090 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3091 return false;
3095 len -= l;
3096 addr += l;
3098 return true;
3101 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3102 hwaddr len, bool is_write,
3103 MemTxAttrs attrs)
3105 FlatView *fv;
3106 bool result;
3108 RCU_READ_LOCK_GUARD();
3109 fv = address_space_to_flatview(as);
3110 result = flatview_access_valid(fv, addr, len, is_write, attrs);
3111 return result;
3114 static hwaddr
3115 flatview_extend_translation(FlatView *fv, hwaddr addr,
3116 hwaddr target_len,
3117 MemoryRegion *mr, hwaddr base, hwaddr len,
3118 bool is_write, MemTxAttrs attrs)
3120 hwaddr done = 0;
3121 hwaddr xlat;
3122 MemoryRegion *this_mr;
3124 for (;;) {
3125 target_len -= len;
3126 addr += len;
3127 done += len;
3128 if (target_len == 0) {
3129 return done;
3132 len = target_len;
3133 this_mr = flatview_translate(fv, addr, &xlat,
3134 &len, is_write, attrs);
3135 if (this_mr != mr || xlat != base + done) {
3136 return done;
3141 /* Map a physical memory region into a host virtual address.
3142 * May map a subset of the requested range, given by and returned in *plen.
3143 * May return NULL if resources needed to perform the mapping are exhausted.
3144 * Use only for reads OR writes - not for read-modify-write operations.
3145 * Use cpu_register_map_client() to know when retrying the map operation is
3146 * likely to succeed.
3148 void *address_space_map(AddressSpace *as,
3149 hwaddr addr,
3150 hwaddr *plen,
3151 bool is_write,
3152 MemTxAttrs attrs)
3154 hwaddr len = *plen;
3155 hwaddr l, xlat;
3156 MemoryRegion *mr;
3157 void *ptr;
3158 FlatView *fv;
3160 if (len == 0) {
3161 return NULL;
3164 l = len;
3165 RCU_READ_LOCK_GUARD();
3166 fv = address_space_to_flatview(as);
3167 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3169 if (!memory_access_is_direct(mr, is_write)) {
3170 if (qatomic_xchg(&bounce.in_use, true)) {
3171 *plen = 0;
3172 return NULL;
3174 /* Avoid unbounded allocations */
3175 l = MIN(l, TARGET_PAGE_SIZE);
3176 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3177 bounce.addr = addr;
3178 bounce.len = l;
3180 memory_region_ref(mr);
3181 bounce.mr = mr;
3182 if (!is_write) {
3183 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3184 bounce.buffer, l);
3187 *plen = l;
3188 return bounce.buffer;
3192 memory_region_ref(mr);
3193 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3194 l, is_write, attrs);
3195 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3197 return ptr;
3200 /* Unmaps a memory region previously mapped by address_space_map().
3201 * Will also mark the memory as dirty if is_write is true. access_len gives
3202 * the amount of memory that was actually read or written by the caller.
3204 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3205 bool is_write, hwaddr access_len)
3207 if (buffer != bounce.buffer) {
3208 MemoryRegion *mr;
3209 ram_addr_t addr1;
3211 mr = memory_region_from_host(buffer, &addr1);
3212 assert(mr != NULL);
3213 if (is_write) {
3214 invalidate_and_set_dirty(mr, addr1, access_len);
3216 if (xen_enabled()) {
3217 xen_invalidate_map_cache_entry(buffer);
3219 memory_region_unref(mr);
3220 return;
3222 if (is_write) {
3223 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3224 bounce.buffer, access_len);
3226 qemu_vfree(bounce.buffer);
3227 bounce.buffer = NULL;
3228 memory_region_unref(bounce.mr);
3229 qatomic_mb_set(&bounce.in_use, false);
3230 cpu_notify_map_clients();
3233 void *cpu_physical_memory_map(hwaddr addr,
3234 hwaddr *plen,
3235 bool is_write)
3237 return address_space_map(&address_space_memory, addr, plen, is_write,
3238 MEMTXATTRS_UNSPECIFIED);
3241 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3242 bool is_write, hwaddr access_len)
3244 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3247 #define ARG1_DECL AddressSpace *as
3248 #define ARG1 as
3249 #define SUFFIX
3250 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3251 #define RCU_READ_LOCK(...) rcu_read_lock()
3252 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3253 #include "memory_ldst.c.inc"
3255 int64_t address_space_cache_init(MemoryRegionCache *cache,
3256 AddressSpace *as,
3257 hwaddr addr,
3258 hwaddr len,
3259 bool is_write)
3261 AddressSpaceDispatch *d;
3262 hwaddr l;
3263 MemoryRegion *mr;
3265 assert(len > 0);
3267 l = len;
3268 cache->fv = address_space_get_flatview(as);
3269 d = flatview_to_dispatch(cache->fv);
3270 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3272 mr = cache->mrs.mr;
3273 memory_region_ref(mr);
3274 if (memory_access_is_direct(mr, is_write)) {
3275 /* We don't care about the memory attributes here as we're only
3276 * doing this if we found actual RAM, which behaves the same
3277 * regardless of attributes; so UNSPECIFIED is fine.
3279 l = flatview_extend_translation(cache->fv, addr, len, mr,
3280 cache->xlat, l, is_write,
3281 MEMTXATTRS_UNSPECIFIED);
3282 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3283 } else {
3284 cache->ptr = NULL;
3287 cache->len = l;
3288 cache->is_write = is_write;
3289 return l;
3292 void address_space_cache_invalidate(MemoryRegionCache *cache,
3293 hwaddr addr,
3294 hwaddr access_len)
3296 assert(cache->is_write);
3297 if (likely(cache->ptr)) {
3298 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3302 void address_space_cache_destroy(MemoryRegionCache *cache)
3304 if (!cache->mrs.mr) {
3305 return;
3308 if (xen_enabled()) {
3309 xen_invalidate_map_cache_entry(cache->ptr);
3311 memory_region_unref(cache->mrs.mr);
3312 flatview_unref(cache->fv);
3313 cache->mrs.mr = NULL;
3314 cache->fv = NULL;
3317 /* Called from RCU critical section. This function has the same
3318 * semantics as address_space_translate, but it only works on a
3319 * predefined range of a MemoryRegion that was mapped with
3320 * address_space_cache_init.
3322 static inline MemoryRegion *address_space_translate_cached(
3323 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3324 hwaddr *plen, bool is_write, MemTxAttrs attrs)
3326 MemoryRegionSection section;
3327 MemoryRegion *mr;
3328 IOMMUMemoryRegion *iommu_mr;
3329 AddressSpace *target_as;
3331 assert(!cache->ptr);
3332 *xlat = addr + cache->xlat;
3334 mr = cache->mrs.mr;
3335 iommu_mr = memory_region_get_iommu(mr);
3336 if (!iommu_mr) {
3337 /* MMIO region. */
3338 return mr;
3341 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3342 NULL, is_write, true,
3343 &target_as, attrs);
3344 return section.mr;
3347 /* Called from RCU critical section. address_space_read_cached uses this
3348 * out of line function when the target is an MMIO or IOMMU region.
3350 MemTxResult
3351 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3352 void *buf, hwaddr len)
3354 hwaddr addr1, l;
3355 MemoryRegion *mr;
3357 l = len;
3358 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3359 MEMTXATTRS_UNSPECIFIED);
3360 return flatview_read_continue(cache->fv,
3361 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3362 addr1, l, mr);
3365 /* Called from RCU critical section. address_space_write_cached uses this
3366 * out of line function when the target is an MMIO or IOMMU region.
3368 MemTxResult
3369 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3370 const void *buf, hwaddr len)
3372 hwaddr addr1, l;
3373 MemoryRegion *mr;
3375 l = len;
3376 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3377 MEMTXATTRS_UNSPECIFIED);
3378 return flatview_write_continue(cache->fv,
3379 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3380 addr1, l, mr);
3383 #define ARG1_DECL MemoryRegionCache *cache
3384 #define ARG1 cache
3385 #define SUFFIX _cached_slow
3386 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3387 #define RCU_READ_LOCK() ((void)0)
3388 #define RCU_READ_UNLOCK() ((void)0)
3389 #include "memory_ldst.c.inc"
3391 /* virtual memory access for debug (includes writing to ROM) */
3392 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3393 void *ptr, target_ulong len, bool is_write)
3395 hwaddr phys_addr;
3396 target_ulong l, page;
3397 uint8_t *buf = ptr;
3399 cpu_synchronize_state(cpu);
3400 while (len > 0) {
3401 int asidx;
3402 MemTxAttrs attrs;
3403 MemTxResult res;
3405 page = addr & TARGET_PAGE_MASK;
3406 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3407 asidx = cpu_asidx_from_attrs(cpu, attrs);
3408 /* if no physical page mapped, return an error */
3409 if (phys_addr == -1)
3410 return -1;
3411 l = (page + TARGET_PAGE_SIZE) - addr;
3412 if (l > len)
3413 l = len;
3414 phys_addr += (addr & ~TARGET_PAGE_MASK);
3415 if (is_write) {
3416 res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3417 attrs, buf, l);
3418 } else {
3419 res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3420 attrs, buf, l);
3422 if (res != MEMTX_OK) {
3423 return -1;
3425 len -= l;
3426 buf += l;
3427 addr += l;
3429 return 0;
3433 * Allows code that needs to deal with migration bitmaps etc to still be built
3434 * target independent.
3436 size_t qemu_target_page_size(void)
3438 return TARGET_PAGE_SIZE;
3441 int qemu_target_page_bits(void)
3443 return TARGET_PAGE_BITS;
3446 int qemu_target_page_bits_min(void)
3448 return TARGET_PAGE_BITS_MIN;
3451 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3453 MemoryRegion*mr;
3454 hwaddr l = 1;
3455 bool res;
3457 RCU_READ_LOCK_GUARD();
3458 mr = address_space_translate(&address_space_memory,
3459 phys_addr, &phys_addr, &l, false,
3460 MEMTXATTRS_UNSPECIFIED);
3462 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3463 return res;
3466 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3468 RAMBlock *block;
3469 int ret = 0;
3471 RCU_READ_LOCK_GUARD();
3472 RAMBLOCK_FOREACH(block) {
3473 ret = func(block, opaque);
3474 if (ret) {
3475 break;
3478 return ret;
3482 * Unmap pages of memory from start to start+length such that
3483 * they a) read as 0, b) Trigger whatever fault mechanism
3484 * the OS provides for postcopy.
3485 * The pages must be unmapped by the end of the function.
3486 * Returns: 0 on success, none-0 on failure
3489 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3491 int ret = -1;
3493 uint8_t *host_startaddr = rb->host + start;
3495 if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
3496 error_report("ram_block_discard_range: Unaligned start address: %p",
3497 host_startaddr);
3498 goto err;
3501 if ((start + length) <= rb->used_length) {
3502 bool need_madvise, need_fallocate;
3503 if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
3504 error_report("ram_block_discard_range: Unaligned length: %zx",
3505 length);
3506 goto err;
3509 errno = ENOTSUP; /* If we are missing MADVISE etc */
3511 /* The logic here is messy;
3512 * madvise DONTNEED fails for hugepages
3513 * fallocate works on hugepages and shmem
3515 need_madvise = (rb->page_size == qemu_host_page_size);
3516 need_fallocate = rb->fd != -1;
3517 if (need_fallocate) {
3518 /* For a file, this causes the area of the file to be zero'd
3519 * if read, and for hugetlbfs also causes it to be unmapped
3520 * so a userfault will trigger.
3522 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3523 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3524 start, length);
3525 if (ret) {
3526 ret = -errno;
3527 error_report("ram_block_discard_range: Failed to fallocate "
3528 "%s:%" PRIx64 " +%zx (%d)",
3529 rb->idstr, start, length, ret);
3530 goto err;
3532 #else
3533 ret = -ENOSYS;
3534 error_report("ram_block_discard_range: fallocate not available/file"
3535 "%s:%" PRIx64 " +%zx (%d)",
3536 rb->idstr, start, length, ret);
3537 goto err;
3538 #endif
3540 if (need_madvise) {
3541 /* For normal RAM this causes it to be unmapped,
3542 * for shared memory it causes the local mapping to disappear
3543 * and to fall back on the file contents (which we just
3544 * fallocate'd away).
3546 #if defined(CONFIG_MADVISE)
3547 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3548 if (ret) {
3549 ret = -errno;
3550 error_report("ram_block_discard_range: Failed to discard range "
3551 "%s:%" PRIx64 " +%zx (%d)",
3552 rb->idstr, start, length, ret);
3553 goto err;
3555 #else
3556 ret = -ENOSYS;
3557 error_report("ram_block_discard_range: MADVISE not available"
3558 "%s:%" PRIx64 " +%zx (%d)",
3559 rb->idstr, start, length, ret);
3560 goto err;
3561 #endif
3563 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3564 need_madvise, need_fallocate, ret);
3565 } else {
3566 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3567 "/%zx/" RAM_ADDR_FMT")",
3568 rb->idstr, start, length, rb->used_length);
3571 err:
3572 return ret;
3575 bool ramblock_is_pmem(RAMBlock *rb)
3577 return rb->flags & RAM_PMEM;
3580 static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
3582 if (start == end - 1) {
3583 qemu_printf("\t%3d ", start);
3584 } else {
3585 qemu_printf("\t%3d..%-3d ", start, end - 1);
3587 qemu_printf(" skip=%d ", skip);
3588 if (ptr == PHYS_MAP_NODE_NIL) {
3589 qemu_printf(" ptr=NIL");
3590 } else if (!skip) {
3591 qemu_printf(" ptr=#%d", ptr);
3592 } else {
3593 qemu_printf(" ptr=[%d]", ptr);
3595 qemu_printf("\n");
3598 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3599 int128_sub((size), int128_one())) : 0)
3601 void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
3603 int i;
3605 qemu_printf(" Dispatch\n");
3606 qemu_printf(" Physical sections\n");
3608 for (i = 0; i < d->map.sections_nb; ++i) {
3609 MemoryRegionSection *s = d->map.sections + i;
3610 const char *names[] = { " [unassigned]", " [not dirty]",
3611 " [ROM]", " [watch]" };
3613 qemu_printf(" #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx
3614 " %s%s%s%s%s",
3616 s->offset_within_address_space,
3617 s->offset_within_address_space + MR_SIZE(s->mr->size),
3618 s->mr->name ? s->mr->name : "(noname)",
3619 i < ARRAY_SIZE(names) ? names[i] : "",
3620 s->mr == root ? " [ROOT]" : "",
3621 s == d->mru_section ? " [MRU]" : "",
3622 s->mr->is_iommu ? " [iommu]" : "");
3624 if (s->mr->alias) {
3625 qemu_printf(" alias=%s", s->mr->alias->name ?
3626 s->mr->alias->name : "noname");
3628 qemu_printf("\n");
3631 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3632 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3633 for (i = 0; i < d->map.nodes_nb; ++i) {
3634 int j, jprev;
3635 PhysPageEntry prev;
3636 Node *n = d->map.nodes + i;
3638 qemu_printf(" [%d]\n", i);
3640 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3641 PhysPageEntry *pe = *n + j;
3643 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3644 continue;
3647 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3649 jprev = j;
3650 prev = *pe;
3653 if (jprev != ARRAY_SIZE(*n)) {
3654 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3660 * If positive, discarding RAM is disabled. If negative, discarding RAM is
3661 * required to work and cannot be disabled.
3663 static int ram_block_discard_disabled;
3665 int ram_block_discard_disable(bool state)
3667 int old;
3669 if (!state) {
3670 qatomic_dec(&ram_block_discard_disabled);
3671 return 0;
3674 do {
3675 old = qatomic_read(&ram_block_discard_disabled);
3676 if (old < 0) {
3677 return -EBUSY;
3679 } while (qatomic_cmpxchg(&ram_block_discard_disabled,
3680 old, old + 1) != old);
3681 return 0;
3684 int ram_block_discard_require(bool state)
3686 int old;
3688 if (!state) {
3689 qatomic_inc(&ram_block_discard_disabled);
3690 return 0;
3693 do {
3694 old = qatomic_read(&ram_block_discard_disabled);
3695 if (old > 0) {
3696 return -EBUSY;
3698 } while (qatomic_cmpxchg(&ram_block_discard_disabled,
3699 old, old - 1) != old);
3700 return 0;
3703 bool ram_block_discard_is_disabled(void)
3705 return qatomic_read(&ram_block_discard_disabled) > 0;
3708 bool ram_block_discard_is_required(void)
3710 return qatomic_read(&ram_block_discard_disabled) < 0;