Do not include hw/boards.h if it's not really necessary
[qemu/ar7.git] / softmmu / physmem.c
blob7ed276b9b5f948a95cd93daaae8c32fa4c6362c5
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.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 #include "qemu/osdep.h"
21 #include "qemu-common.h"
22 #include "qapi/error.h"
24 #include "qemu/cutils.h"
25 #include "qemu/cacheflush.h"
26 #include "cpu.h"
28 #ifdef CONFIG_TCG
29 #include "hw/core/tcg-cpu-ops.h"
30 #endif /* CONFIG_TCG */
32 #include "exec/exec-all.h"
33 #include "exec/target_page.h"
34 #include "hw/qdev-core.h"
35 #include "hw/qdev-properties.h"
36 #include "hw/boards.h"
37 #include "hw/xen/xen.h"
38 #include "sysemu/kvm.h"
39 #include "sysemu/tcg.h"
40 #include "sysemu/qtest.h"
41 #include "qemu/timer.h"
42 #include "qemu/config-file.h"
43 #include "qemu/error-report.h"
44 #include "qemu/qemu-print.h"
45 #include "exec/memory.h"
46 #include "exec/ioport.h"
47 #include "sysemu/dma.h"
48 #include "sysemu/hostmem.h"
49 #include "sysemu/hw_accel.h"
50 #include "exec/address-spaces.h"
51 #include "sysemu/xen-mapcache.h"
52 #include "trace/trace-root.h"
54 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
55 #include <linux/falloc.h>
56 #endif
58 #include "qemu/rcu_queue.h"
59 #include "qemu/main-loop.h"
60 #include "exec/translate-all.h"
61 #include "sysemu/replay.h"
63 #include "exec/memory-internal.h"
64 #include "exec/ram_addr.h"
65 #include "exec/log.h"
67 #include "qemu/pmem.h"
69 #include "migration/vmstate.h"
71 #include "qemu/range.h"
72 #ifndef _WIN32
73 #include "qemu/mmap-alloc.h"
74 #endif
76 #include "monitor/monitor.h"
78 #ifdef CONFIG_LIBDAXCTL
79 #include <daxctl/libdaxctl.h>
80 #endif
82 //#define DEBUG_SUBPAGE
84 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
85 * are protected by the ramlist lock.
87 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
89 static MemoryRegion *system_memory;
90 static MemoryRegion *system_io;
92 AddressSpace address_space_io;
93 AddressSpace address_space_memory;
95 static MemoryRegion io_mem_unassigned;
97 typedef struct PhysPageEntry PhysPageEntry;
99 struct PhysPageEntry {
100 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
101 uint32_t skip : 6;
102 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
103 uint32_t ptr : 26;
106 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
108 /* Size of the L2 (and L3, etc) page tables. */
109 #define ADDR_SPACE_BITS 64
111 #define P_L2_BITS 9
112 #define P_L2_SIZE (1 << P_L2_BITS)
114 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
116 typedef PhysPageEntry Node[P_L2_SIZE];
118 typedef struct PhysPageMap {
119 struct rcu_head rcu;
121 unsigned sections_nb;
122 unsigned sections_nb_alloc;
123 unsigned nodes_nb;
124 unsigned nodes_nb_alloc;
125 Node *nodes;
126 MemoryRegionSection *sections;
127 } PhysPageMap;
129 struct AddressSpaceDispatch {
130 MemoryRegionSection *mru_section;
131 /* This is a multi-level map on the physical address space.
132 * The bottom level has pointers to MemoryRegionSections.
134 PhysPageEntry phys_map;
135 PhysPageMap map;
138 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
139 typedef struct subpage_t {
140 MemoryRegion iomem;
141 FlatView *fv;
142 hwaddr base;
143 uint16_t sub_section[];
144 } subpage_t;
146 #define PHYS_SECTION_UNASSIGNED 0
148 static void io_mem_init(void);
149 static void memory_map_init(void);
150 static void tcg_log_global_after_sync(MemoryListener *listener);
151 static void tcg_commit(MemoryListener *listener);
154 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
155 * @cpu: the CPU whose AddressSpace this is
156 * @as: the AddressSpace itself
157 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
158 * @tcg_as_listener: listener for tracking changes to the AddressSpace
160 struct CPUAddressSpace {
161 CPUState *cpu;
162 AddressSpace *as;
163 struct AddressSpaceDispatch *memory_dispatch;
164 MemoryListener tcg_as_listener;
167 struct DirtyBitmapSnapshot {
168 ram_addr_t start;
169 ram_addr_t end;
170 unsigned long dirty[];
173 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
175 static unsigned alloc_hint = 16;
176 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
177 map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
178 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
179 alloc_hint = map->nodes_nb_alloc;
183 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
185 unsigned i;
186 uint32_t ret;
187 PhysPageEntry e;
188 PhysPageEntry *p;
190 ret = map->nodes_nb++;
191 p = map->nodes[ret];
192 assert(ret != PHYS_MAP_NODE_NIL);
193 assert(ret != map->nodes_nb_alloc);
195 e.skip = leaf ? 0 : 1;
196 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
197 for (i = 0; i < P_L2_SIZE; ++i) {
198 memcpy(&p[i], &e, sizeof(e));
200 return ret;
203 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
204 hwaddr *index, uint64_t *nb, uint16_t leaf,
205 int level)
207 PhysPageEntry *p;
208 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
210 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
211 lp->ptr = phys_map_node_alloc(map, level == 0);
213 p = map->nodes[lp->ptr];
214 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
216 while (*nb && lp < &p[P_L2_SIZE]) {
217 if ((*index & (step - 1)) == 0 && *nb >= step) {
218 lp->skip = 0;
219 lp->ptr = leaf;
220 *index += step;
221 *nb -= step;
222 } else {
223 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
225 ++lp;
229 static void phys_page_set(AddressSpaceDispatch *d,
230 hwaddr index, uint64_t nb,
231 uint16_t leaf)
233 /* Wildly overreserve - it doesn't matter much. */
234 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
236 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
239 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
240 * and update our entry so we can skip it and go directly to the destination.
242 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
244 unsigned valid_ptr = P_L2_SIZE;
245 int valid = 0;
246 PhysPageEntry *p;
247 int i;
249 if (lp->ptr == PHYS_MAP_NODE_NIL) {
250 return;
253 p = nodes[lp->ptr];
254 for (i = 0; i < P_L2_SIZE; i++) {
255 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
256 continue;
259 valid_ptr = i;
260 valid++;
261 if (p[i].skip) {
262 phys_page_compact(&p[i], nodes);
266 /* We can only compress if there's only one child. */
267 if (valid != 1) {
268 return;
271 assert(valid_ptr < P_L2_SIZE);
273 /* Don't compress if it won't fit in the # of bits we have. */
274 if (P_L2_LEVELS >= (1 << 6) &&
275 lp->skip + p[valid_ptr].skip >= (1 << 6)) {
276 return;
279 lp->ptr = p[valid_ptr].ptr;
280 if (!p[valid_ptr].skip) {
281 /* If our only child is a leaf, make this a leaf. */
282 /* By design, we should have made this node a leaf to begin with so we
283 * should never reach here.
284 * But since it's so simple to handle this, let's do it just in case we
285 * change this rule.
287 lp->skip = 0;
288 } else {
289 lp->skip += p[valid_ptr].skip;
293 void address_space_dispatch_compact(AddressSpaceDispatch *d)
295 if (d->phys_map.skip) {
296 phys_page_compact(&d->phys_map, d->map.nodes);
300 static inline bool section_covers_addr(const MemoryRegionSection *section,
301 hwaddr addr)
303 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
304 * the section must cover the entire address space.
306 return int128_gethi(section->size) ||
307 range_covers_byte(section->offset_within_address_space,
308 int128_getlo(section->size), addr);
311 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
313 PhysPageEntry lp = d->phys_map, *p;
314 Node *nodes = d->map.nodes;
315 MemoryRegionSection *sections = d->map.sections;
316 hwaddr index = addr >> TARGET_PAGE_BITS;
317 int i;
319 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
320 if (lp.ptr == PHYS_MAP_NODE_NIL) {
321 return &sections[PHYS_SECTION_UNASSIGNED];
323 p = nodes[lp.ptr];
324 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
327 if (section_covers_addr(&sections[lp.ptr], addr)) {
328 return &sections[lp.ptr];
329 } else {
330 return &sections[PHYS_SECTION_UNASSIGNED];
334 /* Called from RCU critical section */
335 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
336 hwaddr addr,
337 bool resolve_subpage)
339 MemoryRegionSection *section = qatomic_read(&d->mru_section);
340 subpage_t *subpage;
342 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
343 !section_covers_addr(section, addr)) {
344 section = phys_page_find(d, addr);
345 qatomic_set(&d->mru_section, section);
347 if (resolve_subpage && section->mr->subpage) {
348 subpage = container_of(section->mr, subpage_t, iomem);
349 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
351 return section;
354 /* Called from RCU critical section */
355 static MemoryRegionSection *
356 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
357 hwaddr *plen, bool resolve_subpage)
359 MemoryRegionSection *section;
360 MemoryRegion *mr;
361 Int128 diff;
363 section = address_space_lookup_region(d, addr, resolve_subpage);
364 /* Compute offset within MemoryRegionSection */
365 addr -= section->offset_within_address_space;
367 /* Compute offset within MemoryRegion */
368 *xlat = addr + section->offset_within_region;
370 mr = section->mr;
372 /* MMIO registers can be expected to perform full-width accesses based only
373 * on their address, without considering adjacent registers that could
374 * decode to completely different MemoryRegions. When such registers
375 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
376 * regions overlap wildly. For this reason we cannot clamp the accesses
377 * here.
379 * If the length is small (as is the case for address_space_ldl/stl),
380 * everything works fine. If the incoming length is large, however,
381 * the caller really has to do the clamping through memory_access_size.
383 if (memory_region_is_ram(mr)) {
384 diff = int128_sub(section->size, int128_make64(addr));
385 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
387 return section;
391 * address_space_translate_iommu - translate an address through an IOMMU
392 * memory region and then through the target address space.
394 * @iommu_mr: the IOMMU memory region that we start the translation from
395 * @addr: the address to be translated through the MMU
396 * @xlat: the translated address offset within the destination memory region.
397 * It cannot be %NULL.
398 * @plen_out: valid read/write length of the translated address. It
399 * cannot be %NULL.
400 * @page_mask_out: page mask for the translated address. This
401 * should only be meaningful for IOMMU translated
402 * addresses, since there may be huge pages that this bit
403 * would tell. It can be %NULL if we don't care about it.
404 * @is_write: whether the translation operation is for write
405 * @is_mmio: whether this can be MMIO, set true if it can
406 * @target_as: the address space targeted by the IOMMU
407 * @attrs: transaction attributes
409 * This function is called from RCU critical section. It is the common
410 * part of flatview_do_translate and address_space_translate_cached.
412 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
413 hwaddr *xlat,
414 hwaddr *plen_out,
415 hwaddr *page_mask_out,
416 bool is_write,
417 bool is_mmio,
418 AddressSpace **target_as,
419 MemTxAttrs attrs)
421 MemoryRegionSection *section;
422 hwaddr page_mask = (hwaddr)-1;
424 do {
425 hwaddr addr = *xlat;
426 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
427 int iommu_idx = 0;
428 IOMMUTLBEntry iotlb;
430 if (imrc->attrs_to_index) {
431 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
434 iotlb = imrc->translate(iommu_mr, addr, is_write ?
435 IOMMU_WO : IOMMU_RO, iommu_idx);
437 if (!(iotlb.perm & (1 << is_write))) {
438 goto unassigned;
441 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
442 | (addr & iotlb.addr_mask));
443 page_mask &= iotlb.addr_mask;
444 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
445 *target_as = iotlb.target_as;
447 section = address_space_translate_internal(
448 address_space_to_dispatch(iotlb.target_as), addr, xlat,
449 plen_out, is_mmio);
451 iommu_mr = memory_region_get_iommu(section->mr);
452 } while (unlikely(iommu_mr));
454 if (page_mask_out) {
455 *page_mask_out = page_mask;
457 return *section;
459 unassigned:
460 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
464 * flatview_do_translate - translate an address in FlatView
466 * @fv: the flat view that we want to translate on
467 * @addr: the address to be translated in above address space
468 * @xlat: the translated address offset within memory region. It
469 * cannot be @NULL.
470 * @plen_out: valid read/write length of the translated address. It
471 * can be @NULL when we don't care about it.
472 * @page_mask_out: page mask for the translated address. This
473 * should only be meaningful for IOMMU translated
474 * addresses, since there may be huge pages that this bit
475 * would tell. It can be @NULL if we don't care about it.
476 * @is_write: whether the translation operation is for write
477 * @is_mmio: whether this can be MMIO, set true if it can
478 * @target_as: the address space targeted by the IOMMU
479 * @attrs: memory transaction attributes
481 * This function is called from RCU critical section
483 static MemoryRegionSection flatview_do_translate(FlatView *fv,
484 hwaddr addr,
485 hwaddr *xlat,
486 hwaddr *plen_out,
487 hwaddr *page_mask_out,
488 bool is_write,
489 bool is_mmio,
490 AddressSpace **target_as,
491 MemTxAttrs attrs)
493 MemoryRegionSection *section;
494 IOMMUMemoryRegion *iommu_mr;
495 hwaddr plen = (hwaddr)(-1);
497 if (!plen_out) {
498 plen_out = &plen;
501 section = address_space_translate_internal(
502 flatview_to_dispatch(fv), addr, xlat,
503 plen_out, is_mmio);
505 iommu_mr = memory_region_get_iommu(section->mr);
506 if (unlikely(iommu_mr)) {
507 return address_space_translate_iommu(iommu_mr, xlat,
508 plen_out, page_mask_out,
509 is_write, is_mmio,
510 target_as, attrs);
512 if (page_mask_out) {
513 /* Not behind an IOMMU, use default page size. */
514 *page_mask_out = ~TARGET_PAGE_MASK;
517 return *section;
520 /* Called from RCU critical section */
521 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
522 bool is_write, MemTxAttrs attrs)
524 MemoryRegionSection section;
525 hwaddr xlat, page_mask;
528 * This can never be MMIO, and we don't really care about plen,
529 * but page mask.
531 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
532 NULL, &page_mask, is_write, false, &as,
533 attrs);
535 /* Illegal translation */
536 if (section.mr == &io_mem_unassigned) {
537 goto iotlb_fail;
540 /* Convert memory region offset into address space offset */
541 xlat += section.offset_within_address_space -
542 section.offset_within_region;
544 return (IOMMUTLBEntry) {
545 .target_as = as,
546 .iova = addr & ~page_mask,
547 .translated_addr = xlat & ~page_mask,
548 .addr_mask = page_mask,
549 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
550 .perm = IOMMU_RW,
553 iotlb_fail:
554 return (IOMMUTLBEntry) {0};
557 /* Called from RCU critical section */
558 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
559 hwaddr *plen, bool is_write,
560 MemTxAttrs attrs)
562 MemoryRegion *mr;
563 MemoryRegionSection section;
564 AddressSpace *as = NULL;
566 /* This can be MMIO, so setup MMIO bit. */
567 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
568 is_write, true, &as, attrs);
569 mr = section.mr;
571 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
572 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
573 *plen = MIN(page, *plen);
576 return mr;
579 typedef struct TCGIOMMUNotifier {
580 IOMMUNotifier n;
581 MemoryRegion *mr;
582 CPUState *cpu;
583 int iommu_idx;
584 bool active;
585 } TCGIOMMUNotifier;
587 static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
589 TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
591 if (!notifier->active) {
592 return;
594 tlb_flush(notifier->cpu);
595 notifier->active = false;
596 /* We leave the notifier struct on the list to avoid reallocating it later.
597 * Generally the number of IOMMUs a CPU deals with will be small.
598 * In any case we can't unregister the iommu notifier from a notify
599 * callback.
603 static void tcg_register_iommu_notifier(CPUState *cpu,
604 IOMMUMemoryRegion *iommu_mr,
605 int iommu_idx)
607 /* Make sure this CPU has an IOMMU notifier registered for this
608 * IOMMU/IOMMU index combination, so that we can flush its TLB
609 * when the IOMMU tells us the mappings we've cached have changed.
611 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
612 TCGIOMMUNotifier *notifier = NULL;
613 int i;
615 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
616 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
617 if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
618 break;
621 if (i == cpu->iommu_notifiers->len) {
622 /* Not found, add a new entry at the end of the array */
623 cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
624 notifier = g_new0(TCGIOMMUNotifier, 1);
625 g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
627 notifier->mr = mr;
628 notifier->iommu_idx = iommu_idx;
629 notifier->cpu = cpu;
630 /* Rather than trying to register interest in the specific part
631 * of the iommu's address space that we've accessed and then
632 * expand it later as subsequent accesses touch more of it, we
633 * just register interest in the whole thing, on the assumption
634 * that iommu reconfiguration will be rare.
636 iommu_notifier_init(&notifier->n,
637 tcg_iommu_unmap_notify,
638 IOMMU_NOTIFIER_UNMAP,
640 HWADDR_MAX,
641 iommu_idx);
642 memory_region_register_iommu_notifier(notifier->mr, &notifier->n,
643 &error_fatal);
646 if (!notifier->active) {
647 notifier->active = true;
651 void tcg_iommu_free_notifier_list(CPUState *cpu)
653 /* Destroy the CPU's notifier list */
654 int i;
655 TCGIOMMUNotifier *notifier;
657 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
658 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
659 memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
660 g_free(notifier);
662 g_array_free(cpu->iommu_notifiers, true);
665 void tcg_iommu_init_notifier_list(CPUState *cpu)
667 cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
670 /* Called from RCU critical section */
671 MemoryRegionSection *
672 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
673 hwaddr *xlat, hwaddr *plen,
674 MemTxAttrs attrs, int *prot)
676 MemoryRegionSection *section;
677 IOMMUMemoryRegion *iommu_mr;
678 IOMMUMemoryRegionClass *imrc;
679 IOMMUTLBEntry iotlb;
680 int iommu_idx;
681 AddressSpaceDispatch *d =
682 qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
684 for (;;) {
685 section = address_space_translate_internal(d, addr, &addr, plen, false);
687 iommu_mr = memory_region_get_iommu(section->mr);
688 if (!iommu_mr) {
689 break;
692 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
694 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
695 tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
696 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
697 * doesn't short-cut its translation table walk.
699 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
700 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
701 | (addr & iotlb.addr_mask));
702 /* Update the caller's prot bits to remove permissions the IOMMU
703 * is giving us a failure response for. If we get down to no
704 * permissions left at all we can give up now.
706 if (!(iotlb.perm & IOMMU_RO)) {
707 *prot &= ~(PAGE_READ | PAGE_EXEC);
709 if (!(iotlb.perm & IOMMU_WO)) {
710 *prot &= ~PAGE_WRITE;
713 if (!*prot) {
714 goto translate_fail;
717 d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
720 assert(!memory_region_is_iommu(section->mr));
721 *xlat = addr;
722 return section;
724 translate_fail:
725 return &d->map.sections[PHYS_SECTION_UNASSIGNED];
728 void cpu_address_space_init(CPUState *cpu, int asidx,
729 const char *prefix, MemoryRegion *mr)
731 CPUAddressSpace *newas;
732 AddressSpace *as = g_new0(AddressSpace, 1);
733 char *as_name;
735 assert(mr);
736 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
737 address_space_init(as, mr, as_name);
738 g_free(as_name);
740 /* Target code should have set num_ases before calling us */
741 assert(asidx < cpu->num_ases);
743 if (asidx == 0) {
744 /* address space 0 gets the convenience alias */
745 cpu->as = as;
748 /* KVM cannot currently support multiple address spaces. */
749 assert(asidx == 0 || !kvm_enabled());
751 if (!cpu->cpu_ases) {
752 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
755 newas = &cpu->cpu_ases[asidx];
756 newas->cpu = cpu;
757 newas->as = as;
758 if (tcg_enabled()) {
759 newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
760 newas->tcg_as_listener.commit = tcg_commit;
761 memory_listener_register(&newas->tcg_as_listener, as);
765 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
767 /* Return the AddressSpace corresponding to the specified index */
768 return cpu->cpu_ases[asidx].as;
771 /* Add a watchpoint. */
772 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
773 int flags, CPUWatchpoint **watchpoint)
775 CPUWatchpoint *wp;
776 vaddr in_page;
778 /* forbid ranges which are empty or run off the end of the address space */
779 if (len == 0 || (addr + len - 1) < addr) {
780 error_report("tried to set invalid watchpoint at %"
781 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
782 return -EINVAL;
784 wp = g_malloc(sizeof(*wp));
786 wp->vaddr = addr;
787 wp->len = len;
788 wp->flags = flags;
790 /* keep all GDB-injected watchpoints in front */
791 if (flags & BP_GDB) {
792 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
793 } else {
794 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
797 in_page = -(addr | TARGET_PAGE_MASK);
798 if (len <= in_page) {
799 tlb_flush_page(cpu, addr);
800 } else {
801 tlb_flush(cpu);
804 if (watchpoint)
805 *watchpoint = wp;
806 return 0;
809 /* Remove a specific watchpoint. */
810 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
811 int flags)
813 CPUWatchpoint *wp;
815 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
816 if (addr == wp->vaddr && len == wp->len
817 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
818 cpu_watchpoint_remove_by_ref(cpu, wp);
819 return 0;
822 return -ENOENT;
825 /* Remove a specific watchpoint by reference. */
826 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
828 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
830 tlb_flush_page(cpu, watchpoint->vaddr);
832 g_free(watchpoint);
835 /* Remove all matching watchpoints. */
836 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
838 CPUWatchpoint *wp, *next;
840 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
841 if (wp->flags & mask) {
842 cpu_watchpoint_remove_by_ref(cpu, wp);
847 #ifdef CONFIG_TCG
848 /* Return true if this watchpoint address matches the specified
849 * access (ie the address range covered by the watchpoint overlaps
850 * partially or completely with the address range covered by the
851 * access).
853 static inline bool watchpoint_address_matches(CPUWatchpoint *wp,
854 vaddr addr, vaddr len)
856 /* We know the lengths are non-zero, but a little caution is
857 * required to avoid errors in the case where the range ends
858 * exactly at the top of the address space and so addr + len
859 * wraps round to zero.
861 vaddr wpend = wp->vaddr + wp->len - 1;
862 vaddr addrend = addr + len - 1;
864 return !(addr > wpend || wp->vaddr > addrend);
867 /* Return flags for watchpoints that match addr + prot. */
868 int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len)
870 CPUWatchpoint *wp;
871 int ret = 0;
873 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
874 if (watchpoint_address_matches(wp, addr, len)) {
875 ret |= wp->flags;
878 return ret;
881 /* Generate a debug exception if a watchpoint has been hit. */
882 void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
883 MemTxAttrs attrs, int flags, uintptr_t ra)
885 CPUClass *cc = CPU_GET_CLASS(cpu);
886 CPUWatchpoint *wp;
888 assert(tcg_enabled());
889 if (cpu->watchpoint_hit) {
891 * We re-entered the check after replacing the TB.
892 * Now raise the debug interrupt so that it will
893 * trigger after the current instruction.
895 qemu_mutex_lock_iothread();
896 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
897 qemu_mutex_unlock_iothread();
898 return;
901 if (cc->tcg_ops->adjust_watchpoint_address) {
902 /* this is currently used only by ARM BE32 */
903 addr = cc->tcg_ops->adjust_watchpoint_address(cpu, addr, len);
905 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
906 if (watchpoint_address_matches(wp, addr, len)
907 && (wp->flags & flags)) {
908 if (replay_running_debug()) {
910 * Don't process the watchpoints when we are
911 * in a reverse debugging operation.
913 replay_breakpoint();
914 return;
916 if (flags == BP_MEM_READ) {
917 wp->flags |= BP_WATCHPOINT_HIT_READ;
918 } else {
919 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
921 wp->hitaddr = MAX(addr, wp->vaddr);
922 wp->hitattrs = attrs;
923 if (!cpu->watchpoint_hit) {
924 if (wp->flags & BP_CPU && cc->tcg_ops->debug_check_watchpoint &&
925 !cc->tcg_ops->debug_check_watchpoint(cpu, wp)) {
926 wp->flags &= ~BP_WATCHPOINT_HIT;
927 continue;
929 cpu->watchpoint_hit = wp;
931 mmap_lock();
932 tb_check_watchpoint(cpu, ra);
933 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
934 cpu->exception_index = EXCP_DEBUG;
935 mmap_unlock();
936 cpu_loop_exit_restore(cpu, ra);
937 } else {
938 /* Force execution of one insn next time. */
939 cpu->cflags_next_tb = 1 | curr_cflags(cpu);
940 mmap_unlock();
941 if (ra) {
942 cpu_restore_state(cpu, ra, true);
944 cpu_loop_exit_noexc(cpu);
947 } else {
948 wp->flags &= ~BP_WATCHPOINT_HIT;
953 #endif /* CONFIG_TCG */
955 /* Called from RCU critical section */
956 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
958 RAMBlock *block;
960 block = qatomic_rcu_read(&ram_list.mru_block);
961 if (block && addr - block->offset < block->max_length) {
962 return block;
964 RAMBLOCK_FOREACH(block) {
965 if (addr - block->offset < block->max_length) {
966 goto found;
970 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
971 abort();
973 found:
974 /* It is safe to write mru_block outside the iothread lock. This
975 * is what happens:
977 * mru_block = xxx
978 * rcu_read_unlock()
979 * xxx removed from list
980 * rcu_read_lock()
981 * read mru_block
982 * mru_block = NULL;
983 * call_rcu(reclaim_ramblock, xxx);
984 * rcu_read_unlock()
986 * qatomic_rcu_set is not needed here. The block was already published
987 * when it was placed into the list. Here we're just making an extra
988 * copy of the pointer.
990 ram_list.mru_block = block;
991 return block;
994 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
996 CPUState *cpu;
997 ram_addr_t start1;
998 RAMBlock *block;
999 ram_addr_t end;
1001 assert(tcg_enabled());
1002 end = TARGET_PAGE_ALIGN(start + length);
1003 start &= TARGET_PAGE_MASK;
1005 RCU_READ_LOCK_GUARD();
1006 block = qemu_get_ram_block(start);
1007 assert(block == qemu_get_ram_block(end - 1));
1008 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1009 CPU_FOREACH(cpu) {
1010 tlb_reset_dirty(cpu, start1, length);
1014 /* Note: start and end must be within the same ram block. */
1015 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1016 ram_addr_t length,
1017 unsigned client)
1019 DirtyMemoryBlocks *blocks;
1020 unsigned long end, page, start_page;
1021 bool dirty = false;
1022 RAMBlock *ramblock;
1023 uint64_t mr_offset, mr_size;
1025 if (length == 0) {
1026 return false;
1029 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1030 start_page = start >> TARGET_PAGE_BITS;
1031 page = start_page;
1033 WITH_RCU_READ_LOCK_GUARD() {
1034 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1035 ramblock = qemu_get_ram_block(start);
1036 /* Range sanity check on the ramblock */
1037 assert(start >= ramblock->offset &&
1038 start + length <= ramblock->offset + ramblock->used_length);
1040 while (page < end) {
1041 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1042 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1043 unsigned long num = MIN(end - page,
1044 DIRTY_MEMORY_BLOCK_SIZE - offset);
1046 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1047 offset, num);
1048 page += num;
1051 mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
1052 mr_size = (end - start_page) << TARGET_PAGE_BITS;
1053 memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
1056 if (dirty && tcg_enabled()) {
1057 tlb_reset_dirty_range_all(start, length);
1060 return dirty;
1063 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1064 (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
1066 DirtyMemoryBlocks *blocks;
1067 ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
1068 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1069 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1070 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1071 DirtyBitmapSnapshot *snap;
1072 unsigned long page, end, dest;
1074 snap = g_malloc0(sizeof(*snap) +
1075 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1076 snap->start = first;
1077 snap->end = last;
1079 page = first >> TARGET_PAGE_BITS;
1080 end = last >> TARGET_PAGE_BITS;
1081 dest = 0;
1083 WITH_RCU_READ_LOCK_GUARD() {
1084 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1086 while (page < end) {
1087 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1088 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1089 unsigned long num = MIN(end - page,
1090 DIRTY_MEMORY_BLOCK_SIZE - offset);
1092 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1093 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1094 offset >>= BITS_PER_LEVEL;
1096 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1097 blocks->blocks[idx] + offset,
1098 num);
1099 page += num;
1100 dest += num >> BITS_PER_LEVEL;
1104 if (tcg_enabled()) {
1105 tlb_reset_dirty_range_all(start, length);
1108 memory_region_clear_dirty_bitmap(mr, offset, length);
1110 return snap;
1113 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1114 ram_addr_t start,
1115 ram_addr_t length)
1117 unsigned long page, end;
1119 assert(start >= snap->start);
1120 assert(start + length <= snap->end);
1122 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1123 page = (start - snap->start) >> TARGET_PAGE_BITS;
1125 while (page < end) {
1126 if (test_bit(page, snap->dirty)) {
1127 return true;
1129 page++;
1131 return false;
1134 /* Called from RCU critical section */
1135 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1136 MemoryRegionSection *section)
1138 AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
1139 return section - d->map.sections;
1142 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
1143 uint16_t section);
1144 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1146 static uint16_t phys_section_add(PhysPageMap *map,
1147 MemoryRegionSection *section)
1149 /* The physical section number is ORed with a page-aligned
1150 * pointer to produce the iotlb entries. Thus it should
1151 * never overflow into the page-aligned value.
1153 assert(map->sections_nb < TARGET_PAGE_SIZE);
1155 if (map->sections_nb == map->sections_nb_alloc) {
1156 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1157 map->sections = g_renew(MemoryRegionSection, map->sections,
1158 map->sections_nb_alloc);
1160 map->sections[map->sections_nb] = *section;
1161 memory_region_ref(section->mr);
1162 return map->sections_nb++;
1165 static void phys_section_destroy(MemoryRegion *mr)
1167 bool have_sub_page = mr->subpage;
1169 memory_region_unref(mr);
1171 if (have_sub_page) {
1172 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1173 object_unref(OBJECT(&subpage->iomem));
1174 g_free(subpage);
1178 static void phys_sections_free(PhysPageMap *map)
1180 while (map->sections_nb > 0) {
1181 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1182 phys_section_destroy(section->mr);
1184 g_free(map->sections);
1185 g_free(map->nodes);
1188 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1190 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1191 subpage_t *subpage;
1192 hwaddr base = section->offset_within_address_space
1193 & TARGET_PAGE_MASK;
1194 MemoryRegionSection *existing = phys_page_find(d, base);
1195 MemoryRegionSection subsection = {
1196 .offset_within_address_space = base,
1197 .size = int128_make64(TARGET_PAGE_SIZE),
1199 hwaddr start, end;
1201 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1203 if (!(existing->mr->subpage)) {
1204 subpage = subpage_init(fv, base);
1205 subsection.fv = fv;
1206 subsection.mr = &subpage->iomem;
1207 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1208 phys_section_add(&d->map, &subsection));
1209 } else {
1210 subpage = container_of(existing->mr, subpage_t, iomem);
1212 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1213 end = start + int128_get64(section->size) - 1;
1214 subpage_register(subpage, start, end,
1215 phys_section_add(&d->map, section));
1219 static void register_multipage(FlatView *fv,
1220 MemoryRegionSection *section)
1222 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1223 hwaddr start_addr = section->offset_within_address_space;
1224 uint16_t section_index = phys_section_add(&d->map, section);
1225 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1226 TARGET_PAGE_BITS));
1228 assert(num_pages);
1229 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1233 * The range in *section* may look like this:
1235 * |s|PPPPPPP|s|
1237 * where s stands for subpage and P for page.
1239 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1241 MemoryRegionSection remain = *section;
1242 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1244 /* register first subpage */
1245 if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1246 uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1247 - remain.offset_within_address_space;
1249 MemoryRegionSection now = remain;
1250 now.size = int128_min(int128_make64(left), now.size);
1251 register_subpage(fv, &now);
1252 if (int128_eq(remain.size, now.size)) {
1253 return;
1255 remain.size = int128_sub(remain.size, now.size);
1256 remain.offset_within_address_space += int128_get64(now.size);
1257 remain.offset_within_region += int128_get64(now.size);
1260 /* register whole pages */
1261 if (int128_ge(remain.size, page_size)) {
1262 MemoryRegionSection now = remain;
1263 now.size = int128_and(now.size, int128_neg(page_size));
1264 register_multipage(fv, &now);
1265 if (int128_eq(remain.size, now.size)) {
1266 return;
1268 remain.size = int128_sub(remain.size, now.size);
1269 remain.offset_within_address_space += int128_get64(now.size);
1270 remain.offset_within_region += int128_get64(now.size);
1273 /* register last subpage */
1274 register_subpage(fv, &remain);
1277 void qemu_flush_coalesced_mmio_buffer(void)
1279 if (kvm_enabled())
1280 kvm_flush_coalesced_mmio_buffer();
1283 void qemu_mutex_lock_ramlist(void)
1285 qemu_mutex_lock(&ram_list.mutex);
1288 void qemu_mutex_unlock_ramlist(void)
1290 qemu_mutex_unlock(&ram_list.mutex);
1293 void ram_block_dump(Monitor *mon)
1295 RAMBlock *block;
1296 char *psize;
1298 RCU_READ_LOCK_GUARD();
1299 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1300 "Block Name", "PSize", "Offset", "Used", "Total");
1301 RAMBLOCK_FOREACH(block) {
1302 psize = size_to_str(block->page_size);
1303 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1304 " 0x%016" PRIx64 "\n", block->idstr, psize,
1305 (uint64_t)block->offset,
1306 (uint64_t)block->used_length,
1307 (uint64_t)block->max_length);
1308 g_free(psize);
1312 #ifdef __linux__
1314 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1315 * may or may not name the same files / on the same filesystem now as
1316 * when we actually open and map them. Iterate over the file
1317 * descriptors instead, and use qemu_fd_getpagesize().
1319 static int find_min_backend_pagesize(Object *obj, void *opaque)
1321 long *hpsize_min = opaque;
1323 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1324 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1325 long hpsize = host_memory_backend_pagesize(backend);
1327 if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
1328 *hpsize_min = hpsize;
1332 return 0;
1335 static int find_max_backend_pagesize(Object *obj, void *opaque)
1337 long *hpsize_max = opaque;
1339 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1340 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1341 long hpsize = host_memory_backend_pagesize(backend);
1343 if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1344 *hpsize_max = hpsize;
1348 return 0;
1352 * TODO: We assume right now that all mapped host memory backends are
1353 * used as RAM, however some might be used for different purposes.
1355 long qemu_minrampagesize(void)
1357 long hpsize = LONG_MAX;
1358 Object *memdev_root = object_resolve_path("/objects", NULL);
1360 object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
1361 return hpsize;
1364 long qemu_maxrampagesize(void)
1366 long pagesize = 0;
1367 Object *memdev_root = object_resolve_path("/objects", NULL);
1369 object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
1370 return pagesize;
1372 #else
1373 long qemu_minrampagesize(void)
1375 return qemu_real_host_page_size;
1377 long qemu_maxrampagesize(void)
1379 return qemu_real_host_page_size;
1381 #endif
1383 #ifdef CONFIG_POSIX
1384 static int64_t get_file_size(int fd)
1386 int64_t size;
1387 #if defined(__linux__)
1388 struct stat st;
1390 if (fstat(fd, &st) < 0) {
1391 return -errno;
1394 /* Special handling for devdax character devices */
1395 if (S_ISCHR(st.st_mode)) {
1396 g_autofree char *subsystem_path = NULL;
1397 g_autofree char *subsystem = NULL;
1399 subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1400 major(st.st_rdev), minor(st.st_rdev));
1401 subsystem = g_file_read_link(subsystem_path, NULL);
1403 if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
1404 g_autofree char *size_path = NULL;
1405 g_autofree char *size_str = NULL;
1407 size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
1408 major(st.st_rdev), minor(st.st_rdev));
1410 if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
1411 return g_ascii_strtoll(size_str, NULL, 0);
1415 #endif /* defined(__linux__) */
1417 /* st.st_size may be zero for special files yet lseek(2) works */
1418 size = lseek(fd, 0, SEEK_END);
1419 if (size < 0) {
1420 return -errno;
1422 return size;
1425 static int64_t get_file_align(int fd)
1427 int64_t align = -1;
1428 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1429 struct stat st;
1431 if (fstat(fd, &st) < 0) {
1432 return -errno;
1435 /* Special handling for devdax character devices */
1436 if (S_ISCHR(st.st_mode)) {
1437 g_autofree char *path = NULL;
1438 g_autofree char *rpath = NULL;
1439 struct daxctl_ctx *ctx;
1440 struct daxctl_region *region;
1441 int rc = 0;
1443 path = g_strdup_printf("/sys/dev/char/%d:%d",
1444 major(st.st_rdev), minor(st.st_rdev));
1445 rpath = realpath(path, NULL);
1447 rc = daxctl_new(&ctx);
1448 if (rc) {
1449 return -1;
1452 daxctl_region_foreach(ctx, region) {
1453 if (strstr(rpath, daxctl_region_get_path(region))) {
1454 align = daxctl_region_get_align(region);
1455 break;
1458 daxctl_unref(ctx);
1460 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1462 return align;
1465 static int file_ram_open(const char *path,
1466 const char *region_name,
1467 bool readonly,
1468 bool *created,
1469 Error **errp)
1471 char *filename;
1472 char *sanitized_name;
1473 char *c;
1474 int fd = -1;
1476 *created = false;
1477 for (;;) {
1478 fd = open(path, readonly ? O_RDONLY : O_RDWR);
1479 if (fd >= 0) {
1480 /* @path names an existing file, use it */
1481 break;
1483 if (errno == ENOENT) {
1484 /* @path names a file that doesn't exist, create it */
1485 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1486 if (fd >= 0) {
1487 *created = true;
1488 break;
1490 } else if (errno == EISDIR) {
1491 /* @path names a directory, create a file there */
1492 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1493 sanitized_name = g_strdup(region_name);
1494 for (c = sanitized_name; *c != '\0'; c++) {
1495 if (*c == '/') {
1496 *c = '_';
1500 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1501 sanitized_name);
1502 g_free(sanitized_name);
1504 fd = mkstemp(filename);
1505 if (fd >= 0) {
1506 unlink(filename);
1507 g_free(filename);
1508 break;
1510 g_free(filename);
1512 if (errno != EEXIST && errno != EINTR) {
1513 error_setg_errno(errp, errno,
1514 "can't open backing store %s for guest RAM",
1515 path);
1516 return -1;
1519 * Try again on EINTR and EEXIST. The latter happens when
1520 * something else creates the file between our two open().
1524 return fd;
1527 static void *file_ram_alloc(RAMBlock *block,
1528 ram_addr_t memory,
1529 int fd,
1530 bool readonly,
1531 bool truncate,
1532 off_t offset,
1533 Error **errp)
1535 void *area;
1537 block->page_size = qemu_fd_getpagesize(fd);
1538 if (block->mr->align % block->page_size) {
1539 error_setg(errp, "alignment 0x%" PRIx64
1540 " must be multiples of page size 0x%zx",
1541 block->mr->align, block->page_size);
1542 return NULL;
1543 } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1544 error_setg(errp, "alignment 0x%" PRIx64
1545 " must be a power of two", block->mr->align);
1546 return NULL;
1548 block->mr->align = MAX(block->page_size, block->mr->align);
1549 #if defined(__s390x__)
1550 if (kvm_enabled()) {
1551 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1553 #endif
1555 if (memory < block->page_size) {
1556 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1557 "or larger than page size 0x%zx",
1558 memory, block->page_size);
1559 return NULL;
1562 memory = ROUND_UP(memory, block->page_size);
1565 * ftruncate is not supported by hugetlbfs in older
1566 * hosts, so don't bother bailing out on errors.
1567 * If anything goes wrong with it under other filesystems,
1568 * mmap will fail.
1570 * Do not truncate the non-empty backend file to avoid corrupting
1571 * the existing data in the file. Disabling shrinking is not
1572 * enough. For example, the current vNVDIMM implementation stores
1573 * the guest NVDIMM labels at the end of the backend file. If the
1574 * backend file is later extended, QEMU will not be able to find
1575 * those labels. Therefore, extending the non-empty backend file
1576 * is disabled as well.
1578 if (truncate && ftruncate(fd, memory)) {
1579 perror("ftruncate");
1582 area = qemu_ram_mmap(fd, memory, block->mr->align, readonly,
1583 block->flags & RAM_SHARED, block->flags & RAM_PMEM,
1584 offset);
1585 if (area == MAP_FAILED) {
1586 error_setg_errno(errp, errno,
1587 "unable to map backing store for guest RAM");
1588 return NULL;
1591 block->fd = fd;
1592 return area;
1594 #endif
1596 /* Allocate space within the ram_addr_t space that governs the
1597 * dirty bitmaps.
1598 * Called with the ramlist lock held.
1600 static ram_addr_t find_ram_offset(ram_addr_t size)
1602 RAMBlock *block, *next_block;
1603 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1605 assert(size != 0); /* it would hand out same offset multiple times */
1607 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1608 return 0;
1611 RAMBLOCK_FOREACH(block) {
1612 ram_addr_t candidate, next = RAM_ADDR_MAX;
1614 /* Align blocks to start on a 'long' in the bitmap
1615 * which makes the bitmap sync'ing take the fast path.
1617 candidate = block->offset + block->max_length;
1618 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1620 /* Search for the closest following block
1621 * and find the gap.
1623 RAMBLOCK_FOREACH(next_block) {
1624 if (next_block->offset >= candidate) {
1625 next = MIN(next, next_block->offset);
1629 /* If it fits remember our place and remember the size
1630 * of gap, but keep going so that we might find a smaller
1631 * gap to fill so avoiding fragmentation.
1633 if (next - candidate >= size && next - candidate < mingap) {
1634 offset = candidate;
1635 mingap = next - candidate;
1638 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1641 if (offset == RAM_ADDR_MAX) {
1642 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1643 (uint64_t)size);
1644 abort();
1647 trace_find_ram_offset(size, offset);
1649 return offset;
1652 static unsigned long last_ram_page(void)
1654 RAMBlock *block;
1655 ram_addr_t last = 0;
1657 RCU_READ_LOCK_GUARD();
1658 RAMBLOCK_FOREACH(block) {
1659 last = MAX(last, block->offset + block->max_length);
1661 return last >> TARGET_PAGE_BITS;
1664 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1666 int ret;
1668 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1669 if (!machine_dump_guest_core(current_machine)) {
1670 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1671 if (ret) {
1672 perror("qemu_madvise");
1673 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1674 "but dump_guest_core=off specified\n");
1679 const char *qemu_ram_get_idstr(RAMBlock *rb)
1681 return rb->idstr;
1684 void *qemu_ram_get_host_addr(RAMBlock *rb)
1686 return rb->host;
1689 ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
1691 return rb->offset;
1694 ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
1696 return rb->used_length;
1699 bool qemu_ram_is_shared(RAMBlock *rb)
1701 return rb->flags & RAM_SHARED;
1704 /* Note: Only set at the start of postcopy */
1705 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1707 return rb->flags & RAM_UF_ZEROPAGE;
1710 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1712 rb->flags |= RAM_UF_ZEROPAGE;
1715 bool qemu_ram_is_migratable(RAMBlock *rb)
1717 return rb->flags & RAM_MIGRATABLE;
1720 void qemu_ram_set_migratable(RAMBlock *rb)
1722 rb->flags |= RAM_MIGRATABLE;
1725 void qemu_ram_unset_migratable(RAMBlock *rb)
1727 rb->flags &= ~RAM_MIGRATABLE;
1730 /* Called with iothread lock held. */
1731 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1733 RAMBlock *block;
1735 assert(new_block);
1736 assert(!new_block->idstr[0]);
1738 if (dev) {
1739 char *id = qdev_get_dev_path(dev);
1740 if (id) {
1741 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1742 g_free(id);
1745 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1747 RCU_READ_LOCK_GUARD();
1748 RAMBLOCK_FOREACH(block) {
1749 if (block != new_block &&
1750 !strcmp(block->idstr, new_block->idstr)) {
1751 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1752 new_block->idstr);
1753 abort();
1758 /* Called with iothread lock held. */
1759 void qemu_ram_unset_idstr(RAMBlock *block)
1761 /* FIXME: arch_init.c assumes that this is not called throughout
1762 * migration. Ignore the problem since hot-unplug during migration
1763 * does not work anyway.
1765 if (block) {
1766 memset(block->idstr, 0, sizeof(block->idstr));
1770 size_t qemu_ram_pagesize(RAMBlock *rb)
1772 return rb->page_size;
1775 /* Returns the largest size of page in use */
1776 size_t qemu_ram_pagesize_largest(void)
1778 RAMBlock *block;
1779 size_t largest = 0;
1781 RAMBLOCK_FOREACH(block) {
1782 largest = MAX(largest, qemu_ram_pagesize(block));
1785 return largest;
1788 static int memory_try_enable_merging(void *addr, size_t len)
1790 if (!machine_mem_merge(current_machine)) {
1791 /* disabled by the user */
1792 return 0;
1795 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1798 /* Only legal before guest might have detected the memory size: e.g. on
1799 * incoming migration, or right after reset.
1801 * As memory core doesn't know how is memory accessed, it is up to
1802 * resize callback to update device state and/or add assertions to detect
1803 * misuse, if necessary.
1805 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1807 const ram_addr_t unaligned_size = newsize;
1809 assert(block);
1811 newsize = HOST_PAGE_ALIGN(newsize);
1813 if (block->used_length == newsize) {
1815 * We don't have to resize the ram block (which only knows aligned
1816 * sizes), however, we have to notify if the unaligned size changed.
1818 if (unaligned_size != memory_region_size(block->mr)) {
1819 memory_region_set_size(block->mr, unaligned_size);
1820 if (block->resized) {
1821 block->resized(block->idstr, unaligned_size, block->host);
1824 return 0;
1827 if (!(block->flags & RAM_RESIZEABLE)) {
1828 error_setg_errno(errp, EINVAL,
1829 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1830 " != 0x" RAM_ADDR_FMT, block->idstr,
1831 newsize, block->used_length);
1832 return -EINVAL;
1835 if (block->max_length < newsize) {
1836 error_setg_errno(errp, EINVAL,
1837 "Size too large: %s: 0x" RAM_ADDR_FMT
1838 " > 0x" RAM_ADDR_FMT, block->idstr,
1839 newsize, block->max_length);
1840 return -EINVAL;
1843 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1844 block->used_length = newsize;
1845 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1846 DIRTY_CLIENTS_ALL);
1847 memory_region_set_size(block->mr, unaligned_size);
1848 if (block->resized) {
1849 block->resized(block->idstr, unaligned_size, block->host);
1851 return 0;
1855 * Trigger sync on the given ram block for range [start, start + length]
1856 * with the backing store if one is available.
1857 * Otherwise no-op.
1858 * @Note: this is supposed to be a synchronous op.
1860 void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
1862 /* The requested range should fit in within the block range */
1863 g_assert((start + length) <= block->used_length);
1865 #ifdef CONFIG_LIBPMEM
1866 /* The lack of support for pmem should not block the sync */
1867 if (ramblock_is_pmem(block)) {
1868 void *addr = ramblock_ptr(block, start);
1869 pmem_persist(addr, length);
1870 return;
1872 #endif
1873 if (block->fd >= 0) {
1875 * Case there is no support for PMEM or the memory has not been
1876 * specified as persistent (or is not one) - use the msync.
1877 * Less optimal but still achieves the same goal
1879 void *addr = ramblock_ptr(block, start);
1880 if (qemu_msync(addr, length, block->fd)) {
1881 warn_report("%s: failed to sync memory range: start: "
1882 RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
1883 __func__, start, length);
1888 /* Called with ram_list.mutex held */
1889 static void dirty_memory_extend(ram_addr_t old_ram_size,
1890 ram_addr_t new_ram_size)
1892 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1893 DIRTY_MEMORY_BLOCK_SIZE);
1894 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1895 DIRTY_MEMORY_BLOCK_SIZE);
1896 int i;
1898 /* Only need to extend if block count increased */
1899 if (new_num_blocks <= old_num_blocks) {
1900 return;
1903 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1904 DirtyMemoryBlocks *old_blocks;
1905 DirtyMemoryBlocks *new_blocks;
1906 int j;
1908 old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
1909 new_blocks = g_malloc(sizeof(*new_blocks) +
1910 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1912 if (old_num_blocks) {
1913 memcpy(new_blocks->blocks, old_blocks->blocks,
1914 old_num_blocks * sizeof(old_blocks->blocks[0]));
1917 for (j = old_num_blocks; j < new_num_blocks; j++) {
1918 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1921 qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1923 if (old_blocks) {
1924 g_free_rcu(old_blocks, rcu);
1929 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
1931 RAMBlock *block;
1932 RAMBlock *last_block = NULL;
1933 ram_addr_t old_ram_size, new_ram_size;
1934 Error *err = NULL;
1936 old_ram_size = last_ram_page();
1938 qemu_mutex_lock_ramlist();
1939 new_block->offset = find_ram_offset(new_block->max_length);
1941 if (!new_block->host) {
1942 if (xen_enabled()) {
1943 xen_ram_alloc(new_block->offset, new_block->max_length,
1944 new_block->mr, &err);
1945 if (err) {
1946 error_propagate(errp, err);
1947 qemu_mutex_unlock_ramlist();
1948 return;
1950 } else {
1951 new_block->host = qemu_anon_ram_alloc(new_block->max_length,
1952 &new_block->mr->align,
1953 shared);
1954 if (!new_block->host) {
1955 error_setg_errno(errp, errno,
1956 "cannot set up guest memory '%s'",
1957 memory_region_name(new_block->mr));
1958 qemu_mutex_unlock_ramlist();
1959 return;
1961 memory_try_enable_merging(new_block->host, new_block->max_length);
1965 new_ram_size = MAX(old_ram_size,
1966 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1967 if (new_ram_size > old_ram_size) {
1968 dirty_memory_extend(old_ram_size, new_ram_size);
1970 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1971 * QLIST (which has an RCU-friendly variant) does not have insertion at
1972 * tail, so save the last element in last_block.
1974 RAMBLOCK_FOREACH(block) {
1975 last_block = block;
1976 if (block->max_length < new_block->max_length) {
1977 break;
1980 if (block) {
1981 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1982 } else if (last_block) {
1983 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
1984 } else { /* list is empty */
1985 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1987 ram_list.mru_block = NULL;
1989 /* Write list before version */
1990 smp_wmb();
1991 ram_list.version++;
1992 qemu_mutex_unlock_ramlist();
1994 cpu_physical_memory_set_dirty_range(new_block->offset,
1995 new_block->used_length,
1996 DIRTY_CLIENTS_ALL);
1998 if (new_block->host) {
1999 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2000 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2002 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
2003 * Configure it unless the machine is a qtest server, in which case
2004 * KVM is not used and it may be forked (eg for fuzzing purposes).
2006 if (!qtest_enabled()) {
2007 qemu_madvise(new_block->host, new_block->max_length,
2008 QEMU_MADV_DONTFORK);
2010 ram_block_notify_add(new_block->host, new_block->max_length);
2014 #ifdef CONFIG_POSIX
2015 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2016 uint32_t ram_flags, int fd, off_t offset,
2017 bool readonly, Error **errp)
2019 RAMBlock *new_block;
2020 Error *local_err = NULL;
2021 int64_t file_size, file_align;
2023 /* Just support these ram flags by now. */
2024 assert((ram_flags & ~(RAM_SHARED | RAM_PMEM)) == 0);
2026 if (xen_enabled()) {
2027 error_setg(errp, "-mem-path not supported with Xen");
2028 return NULL;
2031 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2032 error_setg(errp,
2033 "host lacks kvm mmu notifiers, -mem-path unsupported");
2034 return NULL;
2037 size = HOST_PAGE_ALIGN(size);
2038 file_size = get_file_size(fd);
2039 if (file_size > 0 && file_size < size) {
2040 error_setg(errp, "backing store size 0x%" PRIx64
2041 " does not match 'size' option 0x" RAM_ADDR_FMT,
2042 file_size, size);
2043 return NULL;
2046 file_align = get_file_align(fd);
2047 if (file_align > 0 && mr && file_align > mr->align) {
2048 error_setg(errp, "backing store align 0x%" PRIx64
2049 " is larger than 'align' option 0x%" PRIx64,
2050 file_align, mr->align);
2051 return NULL;
2054 new_block = g_malloc0(sizeof(*new_block));
2055 new_block->mr = mr;
2056 new_block->used_length = size;
2057 new_block->max_length = size;
2058 new_block->flags = ram_flags;
2059 new_block->host = file_ram_alloc(new_block, size, fd, readonly,
2060 !file_size, offset, errp);
2061 if (!new_block->host) {
2062 g_free(new_block);
2063 return NULL;
2066 ram_block_add(new_block, &local_err, ram_flags & RAM_SHARED);
2067 if (local_err) {
2068 g_free(new_block);
2069 error_propagate(errp, local_err);
2070 return NULL;
2072 return new_block;
2077 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2078 uint32_t ram_flags, const char *mem_path,
2079 bool readonly, Error **errp)
2081 int fd;
2082 bool created;
2083 RAMBlock *block;
2085 fd = file_ram_open(mem_path, memory_region_name(mr), readonly, &created,
2086 errp);
2087 if (fd < 0) {
2088 return NULL;
2091 block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, 0, readonly, errp);
2092 if (!block) {
2093 if (created) {
2094 unlink(mem_path);
2096 close(fd);
2097 return NULL;
2100 return block;
2102 #endif
2104 static
2105 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2106 void (*resized)(const char*,
2107 uint64_t length,
2108 void *host),
2109 void *host, bool resizeable, bool share,
2110 MemoryRegion *mr, Error **errp)
2112 RAMBlock *new_block;
2113 Error *local_err = NULL;
2115 size = HOST_PAGE_ALIGN(size);
2116 max_size = HOST_PAGE_ALIGN(max_size);
2117 new_block = g_malloc0(sizeof(*new_block));
2118 new_block->mr = mr;
2119 new_block->resized = resized;
2120 new_block->used_length = size;
2121 new_block->max_length = max_size;
2122 assert(max_size >= size);
2123 new_block->fd = -1;
2124 new_block->page_size = qemu_real_host_page_size;
2125 new_block->host = host;
2126 if (host) {
2127 new_block->flags |= RAM_PREALLOC;
2129 if (resizeable) {
2130 new_block->flags |= RAM_RESIZEABLE;
2132 ram_block_add(new_block, &local_err, share);
2133 if (local_err) {
2134 g_free(new_block);
2135 error_propagate(errp, local_err);
2136 return NULL;
2138 return new_block;
2141 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2142 MemoryRegion *mr, Error **errp)
2144 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2145 false, mr, errp);
2148 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2149 MemoryRegion *mr, Error **errp)
2151 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2152 share, mr, errp);
2155 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2156 void (*resized)(const char*,
2157 uint64_t length,
2158 void *host),
2159 MemoryRegion *mr, Error **errp)
2161 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2162 false, mr, errp);
2165 static void reclaim_ramblock(RAMBlock *block)
2167 if (block->flags & RAM_PREALLOC) {
2169 } else if (xen_enabled()) {
2170 xen_invalidate_map_cache_entry(block->host);
2171 #ifndef _WIN32
2172 } else if (block->fd >= 0) {
2173 qemu_ram_munmap(block->fd, block->host, block->max_length);
2174 close(block->fd);
2175 #endif
2176 } else {
2177 qemu_anon_ram_free(block->host, block->max_length);
2179 g_free(block);
2182 void qemu_ram_free(RAMBlock *block)
2184 if (!block) {
2185 return;
2188 if (block->host) {
2189 ram_block_notify_remove(block->host, block->max_length);
2192 qemu_mutex_lock_ramlist();
2193 QLIST_REMOVE_RCU(block, next);
2194 ram_list.mru_block = NULL;
2195 /* Write list before version */
2196 smp_wmb();
2197 ram_list.version++;
2198 call_rcu(block, reclaim_ramblock, rcu);
2199 qemu_mutex_unlock_ramlist();
2202 #ifndef _WIN32
2203 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2205 RAMBlock *block;
2206 ram_addr_t offset;
2207 int flags;
2208 void *area, *vaddr;
2210 RAMBLOCK_FOREACH(block) {
2211 offset = addr - block->offset;
2212 if (offset < block->max_length) {
2213 vaddr = ramblock_ptr(block, offset);
2214 if (block->flags & RAM_PREALLOC) {
2216 } else if (xen_enabled()) {
2217 abort();
2218 } else {
2219 flags = MAP_FIXED;
2220 if (block->fd >= 0) {
2221 flags |= (block->flags & RAM_SHARED ?
2222 MAP_SHARED : MAP_PRIVATE);
2223 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2224 flags, block->fd, offset);
2225 } else {
2226 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2227 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2228 flags, -1, 0);
2230 if (area != vaddr) {
2231 error_report("Could not remap addr: "
2232 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2233 length, addr);
2234 exit(1);
2236 memory_try_enable_merging(vaddr, length);
2237 qemu_ram_setup_dump(vaddr, length);
2242 #endif /* !_WIN32 */
2244 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2245 * This should not be used for general purpose DMA. Use address_space_map
2246 * or address_space_rw instead. For local memory (e.g. video ram) that the
2247 * device owns, use memory_region_get_ram_ptr.
2249 * Called within RCU critical section.
2251 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2253 RAMBlock *block = ram_block;
2255 if (block == NULL) {
2256 block = qemu_get_ram_block(addr);
2257 addr -= block->offset;
2260 if (xen_enabled() && block->host == NULL) {
2261 /* We need to check if the requested address is in the RAM
2262 * because we don't want to map the entire memory in QEMU.
2263 * In that case just map until the end of the page.
2265 if (block->offset == 0) {
2266 return xen_map_cache(addr, 0, 0, false);
2269 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2271 return ramblock_ptr(block, addr);
2274 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2275 * but takes a size argument.
2277 * Called within RCU critical section.
2279 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2280 hwaddr *size, bool lock)
2282 RAMBlock *block = ram_block;
2283 if (*size == 0) {
2284 return NULL;
2287 if (block == NULL) {
2288 block = qemu_get_ram_block(addr);
2289 addr -= block->offset;
2291 *size = MIN(*size, block->max_length - addr);
2293 if (xen_enabled() && block->host == NULL) {
2294 /* We need to check if the requested address is in the RAM
2295 * because we don't want to map the entire memory in QEMU.
2296 * In that case just map the requested area.
2298 if (block->offset == 0) {
2299 return xen_map_cache(addr, *size, lock, lock);
2302 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2305 return ramblock_ptr(block, addr);
2308 /* Return the offset of a hostpointer within a ramblock */
2309 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2311 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2312 assert((uintptr_t)host >= (uintptr_t)rb->host);
2313 assert(res < rb->max_length);
2315 return res;
2319 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2320 * in that RAMBlock.
2322 * ptr: Host pointer to look up
2323 * round_offset: If true round the result offset down to a page boundary
2324 * *ram_addr: set to result ram_addr
2325 * *offset: set to result offset within the RAMBlock
2327 * Returns: RAMBlock (or NULL if not found)
2329 * By the time this function returns, the returned pointer is not protected
2330 * by RCU anymore. If the caller is not within an RCU critical section and
2331 * does not hold the iothread lock, it must have other means of protecting the
2332 * pointer, such as a reference to the region that includes the incoming
2333 * ram_addr_t.
2335 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2336 ram_addr_t *offset)
2338 RAMBlock *block;
2339 uint8_t *host = ptr;
2341 if (xen_enabled()) {
2342 ram_addr_t ram_addr;
2343 RCU_READ_LOCK_GUARD();
2344 ram_addr = xen_ram_addr_from_mapcache(ptr);
2345 block = qemu_get_ram_block(ram_addr);
2346 if (block) {
2347 *offset = ram_addr - block->offset;
2349 return block;
2352 RCU_READ_LOCK_GUARD();
2353 block = qatomic_rcu_read(&ram_list.mru_block);
2354 if (block && block->host && host - block->host < block->max_length) {
2355 goto found;
2358 RAMBLOCK_FOREACH(block) {
2359 /* This case append when the block is not mapped. */
2360 if (block->host == NULL) {
2361 continue;
2363 if (host - block->host < block->max_length) {
2364 goto found;
2368 return NULL;
2370 found:
2371 *offset = (host - block->host);
2372 if (round_offset) {
2373 *offset &= TARGET_PAGE_MASK;
2375 return block;
2379 * Finds the named RAMBlock
2381 * name: The name of RAMBlock to find
2383 * Returns: RAMBlock (or NULL if not found)
2385 RAMBlock *qemu_ram_block_by_name(const char *name)
2387 RAMBlock *block;
2389 RAMBLOCK_FOREACH(block) {
2390 if (!strcmp(name, block->idstr)) {
2391 return block;
2395 return NULL;
2398 /* Some of the softmmu routines need to translate from a host pointer
2399 (typically a TLB entry) back to a ram offset. */
2400 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2402 RAMBlock *block;
2403 ram_addr_t offset;
2405 block = qemu_ram_block_from_host(ptr, false, &offset);
2406 if (!block) {
2407 return RAM_ADDR_INVALID;
2410 return block->offset + offset;
2413 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2414 MemTxAttrs attrs, void *buf, hwaddr len);
2415 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2416 const void *buf, hwaddr len);
2417 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2418 bool is_write, MemTxAttrs attrs);
2420 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2421 unsigned len, MemTxAttrs attrs)
2423 subpage_t *subpage = opaque;
2424 uint8_t buf[8];
2425 MemTxResult res;
2427 #if defined(DEBUG_SUBPAGE)
2428 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2429 subpage, len, addr);
2430 #endif
2431 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2432 if (res) {
2433 return res;
2435 *data = ldn_p(buf, len);
2436 return MEMTX_OK;
2439 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2440 uint64_t value, unsigned len, MemTxAttrs attrs)
2442 subpage_t *subpage = opaque;
2443 uint8_t buf[8];
2445 #if defined(DEBUG_SUBPAGE)
2446 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2447 " value %"PRIx64"\n",
2448 __func__, subpage, len, addr, value);
2449 #endif
2450 stn_p(buf, len, value);
2451 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2454 static bool subpage_accepts(void *opaque, hwaddr addr,
2455 unsigned len, bool is_write,
2456 MemTxAttrs attrs)
2458 subpage_t *subpage = opaque;
2459 #if defined(DEBUG_SUBPAGE)
2460 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2461 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2462 #endif
2464 return flatview_access_valid(subpage->fv, addr + subpage->base,
2465 len, is_write, attrs);
2468 static const MemoryRegionOps subpage_ops = {
2469 .read_with_attrs = subpage_read,
2470 .write_with_attrs = subpage_write,
2471 .impl.min_access_size = 1,
2472 .impl.max_access_size = 8,
2473 .valid.min_access_size = 1,
2474 .valid.max_access_size = 8,
2475 .valid.accepts = subpage_accepts,
2476 .endianness = DEVICE_NATIVE_ENDIAN,
2479 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2480 uint16_t section)
2482 int idx, eidx;
2484 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2485 return -1;
2486 idx = SUBPAGE_IDX(start);
2487 eidx = SUBPAGE_IDX(end);
2488 #if defined(DEBUG_SUBPAGE)
2489 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2490 __func__, mmio, start, end, idx, eidx, section);
2491 #endif
2492 for (; idx <= eidx; idx++) {
2493 mmio->sub_section[idx] = section;
2496 return 0;
2499 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2501 subpage_t *mmio;
2503 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2504 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2505 mmio->fv = fv;
2506 mmio->base = base;
2507 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2508 NULL, TARGET_PAGE_SIZE);
2509 mmio->iomem.subpage = true;
2510 #if defined(DEBUG_SUBPAGE)
2511 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2512 mmio, base, TARGET_PAGE_SIZE);
2513 #endif
2515 return mmio;
2518 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2520 assert(fv);
2521 MemoryRegionSection section = {
2522 .fv = fv,
2523 .mr = mr,
2524 .offset_within_address_space = 0,
2525 .offset_within_region = 0,
2526 .size = int128_2_64(),
2529 return phys_section_add(map, &section);
2532 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2533 hwaddr index, MemTxAttrs attrs)
2535 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2536 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2537 AddressSpaceDispatch *d = qatomic_rcu_read(&cpuas->memory_dispatch);
2538 MemoryRegionSection *sections = d->map.sections;
2540 return &sections[index & ~TARGET_PAGE_MASK];
2543 static void io_mem_init(void)
2545 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2546 NULL, UINT64_MAX);
2549 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2551 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2552 uint16_t n;
2554 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2555 assert(n == PHYS_SECTION_UNASSIGNED);
2557 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2559 return d;
2562 void address_space_dispatch_free(AddressSpaceDispatch *d)
2564 phys_sections_free(&d->map);
2565 g_free(d);
2568 static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2572 static void tcg_log_global_after_sync(MemoryListener *listener)
2574 CPUAddressSpace *cpuas;
2576 /* Wait for the CPU to end the current TB. This avoids the following
2577 * incorrect race:
2579 * vCPU migration
2580 * ---------------------- -------------------------
2581 * TLB check -> slow path
2582 * notdirty_mem_write
2583 * write to RAM
2584 * mark dirty
2585 * clear dirty flag
2586 * TLB check -> fast path
2587 * read memory
2588 * write to RAM
2590 * by pushing the migration thread's memory read after the vCPU thread has
2591 * written the memory.
2593 if (replay_mode == REPLAY_MODE_NONE) {
2595 * VGA can make calls to this function while updating the screen.
2596 * In record/replay mode this causes a deadlock, because
2597 * run_on_cpu waits for rr mutex. Therefore no races are possible
2598 * in this case and no need for making run_on_cpu when
2599 * record/replay is not enabled.
2601 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2602 run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2606 static void tcg_commit(MemoryListener *listener)
2608 CPUAddressSpace *cpuas;
2609 AddressSpaceDispatch *d;
2611 assert(tcg_enabled());
2612 /* since each CPU stores ram addresses in its TLB cache, we must
2613 reset the modified entries */
2614 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2615 cpu_reloading_memory_map();
2616 /* The CPU and TLB are protected by the iothread lock.
2617 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2618 * may have split the RCU critical section.
2620 d = address_space_to_dispatch(cpuas->as);
2621 qatomic_rcu_set(&cpuas->memory_dispatch, d);
2622 tlb_flush(cpuas->cpu);
2625 static void memory_map_init(void)
2627 system_memory = g_malloc(sizeof(*system_memory));
2629 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2630 address_space_init(&address_space_memory, system_memory, "memory");
2632 system_io = g_malloc(sizeof(*system_io));
2633 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2634 65536);
2635 address_space_init(&address_space_io, system_io, "I/O");
2638 MemoryRegion *get_system_memory(void)
2640 return system_memory;
2643 MemoryRegion *get_system_io(void)
2645 return system_io;
2648 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2649 hwaddr length)
2651 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2652 addr += memory_region_get_ram_addr(mr);
2654 /* No early return if dirty_log_mask is or becomes 0, because
2655 * cpu_physical_memory_set_dirty_range will still call
2656 * xen_modified_memory.
2658 if (dirty_log_mask) {
2659 dirty_log_mask =
2660 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2662 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2663 assert(tcg_enabled());
2664 tb_invalidate_phys_range(addr, addr + length);
2665 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2667 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2670 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
2673 * In principle this function would work on other memory region types too,
2674 * but the ROM device use case is the only one where this operation is
2675 * necessary. Other memory regions should use the
2676 * address_space_read/write() APIs.
2678 assert(memory_region_is_romd(mr));
2680 invalidate_and_set_dirty(mr, addr, size);
2683 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2685 unsigned access_size_max = mr->ops->valid.max_access_size;
2687 /* Regions are assumed to support 1-4 byte accesses unless
2688 otherwise specified. */
2689 if (access_size_max == 0) {
2690 access_size_max = 4;
2693 /* Bound the maximum access by the alignment of the address. */
2694 if (!mr->ops->impl.unaligned) {
2695 unsigned align_size_max = addr & -addr;
2696 if (align_size_max != 0 && align_size_max < access_size_max) {
2697 access_size_max = align_size_max;
2701 /* Don't attempt accesses larger than the maximum. */
2702 if (l > access_size_max) {
2703 l = access_size_max;
2705 l = pow2floor(l);
2707 return l;
2710 static bool prepare_mmio_access(MemoryRegion *mr)
2712 bool release_lock = false;
2714 if (!qemu_mutex_iothread_locked()) {
2715 qemu_mutex_lock_iothread();
2716 release_lock = true;
2718 if (mr->flush_coalesced_mmio) {
2719 qemu_flush_coalesced_mmio_buffer();
2722 return release_lock;
2725 /* Called within RCU critical section. */
2726 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
2727 MemTxAttrs attrs,
2728 const void *ptr,
2729 hwaddr len, hwaddr addr1,
2730 hwaddr l, MemoryRegion *mr)
2732 uint8_t *ram_ptr;
2733 uint64_t val;
2734 MemTxResult result = MEMTX_OK;
2735 bool release_lock = false;
2736 const uint8_t *buf = ptr;
2738 for (;;) {
2739 if (!memory_access_is_direct(mr, true)) {
2740 release_lock |= prepare_mmio_access(mr);
2741 l = memory_access_size(mr, l, addr1);
2742 /* XXX: could force current_cpu to NULL to avoid
2743 potential bugs */
2744 val = ldn_he_p(buf, l);
2745 result |= memory_region_dispatch_write(mr, addr1, val,
2746 size_memop(l), attrs);
2747 } else {
2748 /* RAM case */
2749 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2750 memcpy(ram_ptr, buf, l);
2751 invalidate_and_set_dirty(mr, addr1, l);
2754 if (release_lock) {
2755 qemu_mutex_unlock_iothread();
2756 release_lock = false;
2759 len -= l;
2760 buf += l;
2761 addr += l;
2763 if (!len) {
2764 break;
2767 l = len;
2768 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2771 return result;
2774 /* Called from RCU critical section. */
2775 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2776 const void *buf, hwaddr len)
2778 hwaddr l;
2779 hwaddr addr1;
2780 MemoryRegion *mr;
2781 MemTxResult result = MEMTX_OK;
2783 l = len;
2784 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2785 result = flatview_write_continue(fv, addr, attrs, buf, len,
2786 addr1, l, mr);
2788 return result;
2791 /* Called within RCU critical section. */
2792 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
2793 MemTxAttrs attrs, void *ptr,
2794 hwaddr len, hwaddr addr1, hwaddr l,
2795 MemoryRegion *mr)
2797 uint8_t *ram_ptr;
2798 uint64_t val;
2799 MemTxResult result = MEMTX_OK;
2800 bool release_lock = false;
2801 uint8_t *buf = ptr;
2803 fuzz_dma_read_cb(addr, len, mr);
2804 for (;;) {
2805 if (!memory_access_is_direct(mr, false)) {
2806 /* I/O case */
2807 release_lock |= prepare_mmio_access(mr);
2808 l = memory_access_size(mr, l, addr1);
2809 result |= memory_region_dispatch_read(mr, addr1, &val,
2810 size_memop(l), attrs);
2811 stn_he_p(buf, l, val);
2812 } else {
2813 /* RAM case */
2814 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2815 memcpy(buf, ram_ptr, l);
2818 if (release_lock) {
2819 qemu_mutex_unlock_iothread();
2820 release_lock = false;
2823 len -= l;
2824 buf += l;
2825 addr += l;
2827 if (!len) {
2828 break;
2831 l = len;
2832 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2835 return result;
2838 /* Called from RCU critical section. */
2839 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2840 MemTxAttrs attrs, void *buf, hwaddr len)
2842 hwaddr l;
2843 hwaddr addr1;
2844 MemoryRegion *mr;
2846 l = len;
2847 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2848 return flatview_read_continue(fv, addr, attrs, buf, len,
2849 addr1, l, mr);
2852 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2853 MemTxAttrs attrs, void *buf, hwaddr len)
2855 MemTxResult result = MEMTX_OK;
2856 FlatView *fv;
2858 if (len > 0) {
2859 RCU_READ_LOCK_GUARD();
2860 fv = address_space_to_flatview(as);
2861 result = flatview_read(fv, addr, attrs, buf, len);
2864 return result;
2867 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2868 MemTxAttrs attrs,
2869 const void *buf, hwaddr len)
2871 MemTxResult result = MEMTX_OK;
2872 FlatView *fv;
2874 if (len > 0) {
2875 RCU_READ_LOCK_GUARD();
2876 fv = address_space_to_flatview(as);
2877 result = flatview_write(fv, addr, attrs, buf, len);
2880 return result;
2883 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2884 void *buf, hwaddr len, bool is_write)
2886 if (is_write) {
2887 return address_space_write(as, addr, attrs, buf, len);
2888 } else {
2889 return address_space_read_full(as, addr, attrs, buf, len);
2893 void cpu_physical_memory_rw(hwaddr addr, void *buf,
2894 hwaddr len, bool is_write)
2896 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
2897 buf, len, is_write);
2900 enum write_rom_type {
2901 WRITE_DATA,
2902 FLUSH_CACHE,
2905 static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
2906 hwaddr addr,
2907 MemTxAttrs attrs,
2908 const void *ptr,
2909 hwaddr len,
2910 enum write_rom_type type)
2912 hwaddr l;
2913 uint8_t *ram_ptr;
2914 hwaddr addr1;
2915 MemoryRegion *mr;
2916 const uint8_t *buf = ptr;
2918 RCU_READ_LOCK_GUARD();
2919 while (len > 0) {
2920 l = len;
2921 mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
2923 if (!(memory_region_is_ram(mr) ||
2924 memory_region_is_romd(mr))) {
2925 l = memory_access_size(mr, l, addr1);
2926 } else {
2927 /* ROM/RAM case */
2928 ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2929 switch (type) {
2930 case WRITE_DATA:
2931 memcpy(ram_ptr, buf, l);
2932 invalidate_and_set_dirty(mr, addr1, l);
2933 break;
2934 case FLUSH_CACHE:
2935 flush_idcache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr, l);
2936 break;
2939 len -= l;
2940 buf += l;
2941 addr += l;
2943 return MEMTX_OK;
2946 /* used for ROM loading : can write in RAM and ROM */
2947 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
2948 MemTxAttrs attrs,
2949 const void *buf, hwaddr len)
2951 return address_space_write_rom_internal(as, addr, attrs,
2952 buf, len, WRITE_DATA);
2955 void cpu_flush_icache_range(hwaddr start, hwaddr len)
2958 * This function should do the same thing as an icache flush that was
2959 * triggered from within the guest. For TCG we are always cache coherent,
2960 * so there is no need to flush anything. For KVM / Xen we need to flush
2961 * the host's instruction cache at least.
2963 if (tcg_enabled()) {
2964 return;
2967 address_space_write_rom_internal(&address_space_memory,
2968 start, MEMTXATTRS_UNSPECIFIED,
2969 NULL, len, FLUSH_CACHE);
2972 typedef struct {
2973 MemoryRegion *mr;
2974 void *buffer;
2975 hwaddr addr;
2976 hwaddr len;
2977 bool in_use;
2978 } BounceBuffer;
2980 static BounceBuffer bounce;
2982 typedef struct MapClient {
2983 QEMUBH *bh;
2984 QLIST_ENTRY(MapClient) link;
2985 } MapClient;
2987 QemuMutex map_client_list_lock;
2988 static QLIST_HEAD(, MapClient) map_client_list
2989 = QLIST_HEAD_INITIALIZER(map_client_list);
2991 static void cpu_unregister_map_client_do(MapClient *client)
2993 QLIST_REMOVE(client, link);
2994 g_free(client);
2997 static void cpu_notify_map_clients_locked(void)
2999 MapClient *client;
3001 while (!QLIST_EMPTY(&map_client_list)) {
3002 client = QLIST_FIRST(&map_client_list);
3003 qemu_bh_schedule(client->bh);
3004 cpu_unregister_map_client_do(client);
3008 void cpu_register_map_client(QEMUBH *bh)
3010 MapClient *client = g_malloc(sizeof(*client));
3012 qemu_mutex_lock(&map_client_list_lock);
3013 client->bh = bh;
3014 QLIST_INSERT_HEAD(&map_client_list, client, link);
3015 if (!qatomic_read(&bounce.in_use)) {
3016 cpu_notify_map_clients_locked();
3018 qemu_mutex_unlock(&map_client_list_lock);
3021 void cpu_exec_init_all(void)
3023 qemu_mutex_init(&ram_list.mutex);
3024 /* The data structures we set up here depend on knowing the page size,
3025 * so no more changes can be made after this point.
3026 * In an ideal world, nothing we did before we had finished the
3027 * machine setup would care about the target page size, and we could
3028 * do this much later, rather than requiring board models to state
3029 * up front what their requirements are.
3031 finalize_target_page_bits();
3032 io_mem_init();
3033 memory_map_init();
3034 qemu_mutex_init(&map_client_list_lock);
3037 void cpu_unregister_map_client(QEMUBH *bh)
3039 MapClient *client;
3041 qemu_mutex_lock(&map_client_list_lock);
3042 QLIST_FOREACH(client, &map_client_list, link) {
3043 if (client->bh == bh) {
3044 cpu_unregister_map_client_do(client);
3045 break;
3048 qemu_mutex_unlock(&map_client_list_lock);
3051 static void cpu_notify_map_clients(void)
3053 qemu_mutex_lock(&map_client_list_lock);
3054 cpu_notify_map_clients_locked();
3055 qemu_mutex_unlock(&map_client_list_lock);
3058 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
3059 bool is_write, MemTxAttrs attrs)
3061 MemoryRegion *mr;
3062 hwaddr l, xlat;
3064 while (len > 0) {
3065 l = len;
3066 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3067 if (!memory_access_is_direct(mr, is_write)) {
3068 l = memory_access_size(mr, l, addr);
3069 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3070 return false;
3074 len -= l;
3075 addr += l;
3077 return true;
3080 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3081 hwaddr len, bool is_write,
3082 MemTxAttrs attrs)
3084 FlatView *fv;
3085 bool result;
3087 RCU_READ_LOCK_GUARD();
3088 fv = address_space_to_flatview(as);
3089 result = flatview_access_valid(fv, addr, len, is_write, attrs);
3090 return result;
3093 static hwaddr
3094 flatview_extend_translation(FlatView *fv, hwaddr addr,
3095 hwaddr target_len,
3096 MemoryRegion *mr, hwaddr base, hwaddr len,
3097 bool is_write, MemTxAttrs attrs)
3099 hwaddr done = 0;
3100 hwaddr xlat;
3101 MemoryRegion *this_mr;
3103 for (;;) {
3104 target_len -= len;
3105 addr += len;
3106 done += len;
3107 if (target_len == 0) {
3108 return done;
3111 len = target_len;
3112 this_mr = flatview_translate(fv, addr, &xlat,
3113 &len, is_write, attrs);
3114 if (this_mr != mr || xlat != base + done) {
3115 return done;
3120 /* Map a physical memory region into a host virtual address.
3121 * May map a subset of the requested range, given by and returned in *plen.
3122 * May return NULL if resources needed to perform the mapping are exhausted.
3123 * Use only for reads OR writes - not for read-modify-write operations.
3124 * Use cpu_register_map_client() to know when retrying the map operation is
3125 * likely to succeed.
3127 void *address_space_map(AddressSpace *as,
3128 hwaddr addr,
3129 hwaddr *plen,
3130 bool is_write,
3131 MemTxAttrs attrs)
3133 hwaddr len = *plen;
3134 hwaddr l, xlat;
3135 MemoryRegion *mr;
3136 void *ptr;
3137 FlatView *fv;
3139 if (len == 0) {
3140 return NULL;
3143 l = len;
3144 RCU_READ_LOCK_GUARD();
3145 fv = address_space_to_flatview(as);
3146 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3148 if (!memory_access_is_direct(mr, is_write)) {
3149 if (qatomic_xchg(&bounce.in_use, true)) {
3150 *plen = 0;
3151 return NULL;
3153 /* Avoid unbounded allocations */
3154 l = MIN(l, TARGET_PAGE_SIZE);
3155 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3156 bounce.addr = addr;
3157 bounce.len = l;
3159 memory_region_ref(mr);
3160 bounce.mr = mr;
3161 if (!is_write) {
3162 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3163 bounce.buffer, l);
3166 *plen = l;
3167 return bounce.buffer;
3171 memory_region_ref(mr);
3172 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3173 l, is_write, attrs);
3174 fuzz_dma_read_cb(addr, *plen, mr);
3175 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3177 return ptr;
3180 /* Unmaps a memory region previously mapped by address_space_map().
3181 * Will also mark the memory as dirty if is_write is true. access_len gives
3182 * the amount of memory that was actually read or written by the caller.
3184 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3185 bool is_write, hwaddr access_len)
3187 if (buffer != bounce.buffer) {
3188 MemoryRegion *mr;
3189 ram_addr_t addr1;
3191 mr = memory_region_from_host(buffer, &addr1);
3192 assert(mr != NULL);
3193 if (is_write) {
3194 invalidate_and_set_dirty(mr, addr1, access_len);
3196 if (xen_enabled()) {
3197 xen_invalidate_map_cache_entry(buffer);
3199 memory_region_unref(mr);
3200 return;
3202 if (is_write) {
3203 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3204 bounce.buffer, access_len);
3206 qemu_vfree(bounce.buffer);
3207 bounce.buffer = NULL;
3208 memory_region_unref(bounce.mr);
3209 qatomic_mb_set(&bounce.in_use, false);
3210 cpu_notify_map_clients();
3213 void *cpu_physical_memory_map(hwaddr addr,
3214 hwaddr *plen,
3215 bool is_write)
3217 return address_space_map(&address_space_memory, addr, plen, is_write,
3218 MEMTXATTRS_UNSPECIFIED);
3221 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3222 bool is_write, hwaddr access_len)
3224 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3227 #define ARG1_DECL AddressSpace *as
3228 #define ARG1 as
3229 #define SUFFIX
3230 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3231 #define RCU_READ_LOCK(...) rcu_read_lock()
3232 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3233 #include "memory_ldst.c.inc"
3235 int64_t address_space_cache_init(MemoryRegionCache *cache,
3236 AddressSpace *as,
3237 hwaddr addr,
3238 hwaddr len,
3239 bool is_write)
3241 AddressSpaceDispatch *d;
3242 hwaddr l;
3243 MemoryRegion *mr;
3244 Int128 diff;
3246 assert(len > 0);
3248 l = len;
3249 cache->fv = address_space_get_flatview(as);
3250 d = flatview_to_dispatch(cache->fv);
3251 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3254 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3255 * Take that into account to compute how many bytes are there between
3256 * cache->xlat and the end of the section.
3258 diff = int128_sub(cache->mrs.size,
3259 int128_make64(cache->xlat - cache->mrs.offset_within_region));
3260 l = int128_get64(int128_min(diff, int128_make64(l)));
3262 mr = cache->mrs.mr;
3263 memory_region_ref(mr);
3264 if (memory_access_is_direct(mr, is_write)) {
3265 /* We don't care about the memory attributes here as we're only
3266 * doing this if we found actual RAM, which behaves the same
3267 * regardless of attributes; so UNSPECIFIED is fine.
3269 l = flatview_extend_translation(cache->fv, addr, len, mr,
3270 cache->xlat, l, is_write,
3271 MEMTXATTRS_UNSPECIFIED);
3272 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3273 } else {
3274 cache->ptr = NULL;
3277 cache->len = l;
3278 cache->is_write = is_write;
3279 return l;
3282 void address_space_cache_invalidate(MemoryRegionCache *cache,
3283 hwaddr addr,
3284 hwaddr access_len)
3286 assert(cache->is_write);
3287 if (likely(cache->ptr)) {
3288 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3292 void address_space_cache_destroy(MemoryRegionCache *cache)
3294 if (!cache->mrs.mr) {
3295 return;
3298 if (xen_enabled()) {
3299 xen_invalidate_map_cache_entry(cache->ptr);
3301 memory_region_unref(cache->mrs.mr);
3302 flatview_unref(cache->fv);
3303 cache->mrs.mr = NULL;
3304 cache->fv = NULL;
3307 /* Called from RCU critical section. This function has the same
3308 * semantics as address_space_translate, but it only works on a
3309 * predefined range of a MemoryRegion that was mapped with
3310 * address_space_cache_init.
3312 static inline MemoryRegion *address_space_translate_cached(
3313 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3314 hwaddr *plen, bool is_write, MemTxAttrs attrs)
3316 MemoryRegionSection section;
3317 MemoryRegion *mr;
3318 IOMMUMemoryRegion *iommu_mr;
3319 AddressSpace *target_as;
3321 assert(!cache->ptr);
3322 *xlat = addr + cache->xlat;
3324 mr = cache->mrs.mr;
3325 iommu_mr = memory_region_get_iommu(mr);
3326 if (!iommu_mr) {
3327 /* MMIO region. */
3328 return mr;
3331 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3332 NULL, is_write, true,
3333 &target_as, attrs);
3334 return section.mr;
3337 /* Called from RCU critical section. address_space_read_cached uses this
3338 * out of line function when the target is an MMIO or IOMMU region.
3340 MemTxResult
3341 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3342 void *buf, hwaddr len)
3344 hwaddr addr1, l;
3345 MemoryRegion *mr;
3347 l = len;
3348 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3349 MEMTXATTRS_UNSPECIFIED);
3350 return flatview_read_continue(cache->fv,
3351 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3352 addr1, l, mr);
3355 /* Called from RCU critical section. address_space_write_cached uses this
3356 * out of line function when the target is an MMIO or IOMMU region.
3358 MemTxResult
3359 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3360 const void *buf, hwaddr len)
3362 hwaddr addr1, l;
3363 MemoryRegion *mr;
3365 l = len;
3366 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3367 MEMTXATTRS_UNSPECIFIED);
3368 return flatview_write_continue(cache->fv,
3369 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3370 addr1, l, mr);
3373 #define ARG1_DECL MemoryRegionCache *cache
3374 #define ARG1 cache
3375 #define SUFFIX _cached_slow
3376 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3377 #define RCU_READ_LOCK() ((void)0)
3378 #define RCU_READ_UNLOCK() ((void)0)
3379 #include "memory_ldst.c.inc"
3381 /* virtual memory access for debug (includes writing to ROM) */
3382 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3383 void *ptr, target_ulong len, bool is_write)
3385 hwaddr phys_addr;
3386 target_ulong l, page;
3387 uint8_t *buf = ptr;
3389 cpu_synchronize_state(cpu);
3390 while (len > 0) {
3391 int asidx;
3392 MemTxAttrs attrs;
3393 MemTxResult res;
3395 page = addr & TARGET_PAGE_MASK;
3396 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3397 asidx = cpu_asidx_from_attrs(cpu, attrs);
3398 /* if no physical page mapped, return an error */
3399 if (phys_addr == -1)
3400 return -1;
3401 l = (page + TARGET_PAGE_SIZE) - addr;
3402 if (l > len)
3403 l = len;
3404 phys_addr += (addr & ~TARGET_PAGE_MASK);
3405 if (is_write) {
3406 res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3407 attrs, buf, l);
3408 } else {
3409 res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3410 attrs, buf, l);
3412 if (res != MEMTX_OK) {
3413 return -1;
3415 len -= l;
3416 buf += l;
3417 addr += l;
3419 return 0;
3423 * Allows code that needs to deal with migration bitmaps etc to still be built
3424 * target independent.
3426 size_t qemu_target_page_size(void)
3428 return TARGET_PAGE_SIZE;
3431 int qemu_target_page_bits(void)
3433 return TARGET_PAGE_BITS;
3436 int qemu_target_page_bits_min(void)
3438 return TARGET_PAGE_BITS_MIN;
3441 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3443 MemoryRegion*mr;
3444 hwaddr l = 1;
3445 bool res;
3447 RCU_READ_LOCK_GUARD();
3448 mr = address_space_translate(&address_space_memory,
3449 phys_addr, &phys_addr, &l, false,
3450 MEMTXATTRS_UNSPECIFIED);
3452 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3453 return res;
3456 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3458 RAMBlock *block;
3459 int ret = 0;
3461 RCU_READ_LOCK_GUARD();
3462 RAMBLOCK_FOREACH(block) {
3463 ret = func(block, opaque);
3464 if (ret) {
3465 break;
3468 return ret;
3472 * Unmap pages of memory from start to start+length such that
3473 * they a) read as 0, b) Trigger whatever fault mechanism
3474 * the OS provides for postcopy.
3475 * The pages must be unmapped by the end of the function.
3476 * Returns: 0 on success, none-0 on failure
3479 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3481 int ret = -1;
3483 uint8_t *host_startaddr = rb->host + start;
3485 if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
3486 error_report("ram_block_discard_range: Unaligned start address: %p",
3487 host_startaddr);
3488 goto err;
3491 if ((start + length) <= rb->used_length) {
3492 bool need_madvise, need_fallocate;
3493 if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
3494 error_report("ram_block_discard_range: Unaligned length: %zx",
3495 length);
3496 goto err;
3499 errno = ENOTSUP; /* If we are missing MADVISE etc */
3501 /* The logic here is messy;
3502 * madvise DONTNEED fails for hugepages
3503 * fallocate works on hugepages and shmem
3505 need_madvise = (rb->page_size == qemu_host_page_size);
3506 need_fallocate = rb->fd != -1;
3507 if (need_fallocate) {
3508 /* For a file, this causes the area of the file to be zero'd
3509 * if read, and for hugetlbfs also causes it to be unmapped
3510 * so a userfault will trigger.
3512 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3513 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3514 start, length);
3515 if (ret) {
3516 ret = -errno;
3517 error_report("ram_block_discard_range: Failed to fallocate "
3518 "%s:%" PRIx64 " +%zx (%d)",
3519 rb->idstr, start, length, ret);
3520 goto err;
3522 #else
3523 ret = -ENOSYS;
3524 error_report("ram_block_discard_range: fallocate not available/file"
3525 "%s:%" PRIx64 " +%zx (%d)",
3526 rb->idstr, start, length, ret);
3527 goto err;
3528 #endif
3530 if (need_madvise) {
3531 /* For normal RAM this causes it to be unmapped,
3532 * for shared memory it causes the local mapping to disappear
3533 * and to fall back on the file contents (which we just
3534 * fallocate'd away).
3536 #if defined(CONFIG_MADVISE)
3537 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3538 if (ret) {
3539 ret = -errno;
3540 error_report("ram_block_discard_range: Failed to discard range "
3541 "%s:%" PRIx64 " +%zx (%d)",
3542 rb->idstr, start, length, ret);
3543 goto err;
3545 #else
3546 ret = -ENOSYS;
3547 error_report("ram_block_discard_range: MADVISE not available"
3548 "%s:%" PRIx64 " +%zx (%d)",
3549 rb->idstr, start, length, ret);
3550 goto err;
3551 #endif
3553 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3554 need_madvise, need_fallocate, ret);
3555 } else {
3556 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3557 "/%zx/" RAM_ADDR_FMT")",
3558 rb->idstr, start, length, rb->used_length);
3561 err:
3562 return ret;
3565 bool ramblock_is_pmem(RAMBlock *rb)
3567 return rb->flags & RAM_PMEM;
3570 static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
3572 if (start == end - 1) {
3573 qemu_printf("\t%3d ", start);
3574 } else {
3575 qemu_printf("\t%3d..%-3d ", start, end - 1);
3577 qemu_printf(" skip=%d ", skip);
3578 if (ptr == PHYS_MAP_NODE_NIL) {
3579 qemu_printf(" ptr=NIL");
3580 } else if (!skip) {
3581 qemu_printf(" ptr=#%d", ptr);
3582 } else {
3583 qemu_printf(" ptr=[%d]", ptr);
3585 qemu_printf("\n");
3588 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3589 int128_sub((size), int128_one())) : 0)
3591 void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
3593 int i;
3595 qemu_printf(" Dispatch\n");
3596 qemu_printf(" Physical sections\n");
3598 for (i = 0; i < d->map.sections_nb; ++i) {
3599 MemoryRegionSection *s = d->map.sections + i;
3600 const char *names[] = { " [unassigned]", " [not dirty]",
3601 " [ROM]", " [watch]" };
3603 qemu_printf(" #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx
3604 " %s%s%s%s%s",
3606 s->offset_within_address_space,
3607 s->offset_within_address_space + MR_SIZE(s->mr->size),
3608 s->mr->name ? s->mr->name : "(noname)",
3609 i < ARRAY_SIZE(names) ? names[i] : "",
3610 s->mr == root ? " [ROOT]" : "",
3611 s == d->mru_section ? " [MRU]" : "",
3612 s->mr->is_iommu ? " [iommu]" : "");
3614 if (s->mr->alias) {
3615 qemu_printf(" alias=%s", s->mr->alias->name ?
3616 s->mr->alias->name : "noname");
3618 qemu_printf("\n");
3621 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3622 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3623 for (i = 0; i < d->map.nodes_nb; ++i) {
3624 int j, jprev;
3625 PhysPageEntry prev;
3626 Node *n = d->map.nodes + i;
3628 qemu_printf(" [%d]\n", i);
3630 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3631 PhysPageEntry *pe = *n + j;
3633 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3634 continue;
3637 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3639 jprev = j;
3640 prev = *pe;
3643 if (jprev != ARRAY_SIZE(*n)) {
3644 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3650 * If positive, discarding RAM is disabled. If negative, discarding RAM is
3651 * required to work and cannot be disabled.
3653 static int ram_block_discard_disabled;
3655 int ram_block_discard_disable(bool state)
3657 int old;
3659 if (!state) {
3660 qatomic_dec(&ram_block_discard_disabled);
3661 return 0;
3664 do {
3665 old = qatomic_read(&ram_block_discard_disabled);
3666 if (old < 0) {
3667 return -EBUSY;
3669 } while (qatomic_cmpxchg(&ram_block_discard_disabled,
3670 old, old + 1) != old);
3671 return 0;
3674 int ram_block_discard_require(bool state)
3676 int old;
3678 if (!state) {
3679 qatomic_inc(&ram_block_discard_disabled);
3680 return 0;
3683 do {
3684 old = qatomic_read(&ram_block_discard_disabled);
3685 if (old > 0) {
3686 return -EBUSY;
3688 } while (qatomic_cmpxchg(&ram_block_discard_disabled,
3689 old, old - 1) != old);
3690 return 0;
3693 bool ram_block_discard_is_disabled(void)
3695 return qatomic_read(&ram_block_discard_disabled) > 0;
3698 bool ram_block_discard_is_required(void)
3700 return qatomic_read(&ram_block_discard_disabled) < 0;