memory: add readonly support to memory_region_init_ram_from_file()
[qemu/ar7.git] / softmmu / physmem.c
blob60760a3bdc5e0ebe7ee6651d0b96e118fc659d1a
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"
27 #include "exec/exec-all.h"
28 #include "exec/target_page.h"
29 #include "hw/qdev-core.h"
30 #include "hw/qdev-properties.h"
31 #include "hw/boards.h"
32 #include "hw/xen/xen.h"
33 #include "sysemu/kvm.h"
34 #include "sysemu/sysemu.h"
35 #include "sysemu/tcg.h"
36 #include "sysemu/qtest.h"
37 #include "qemu/timer.h"
38 #include "qemu/config-file.h"
39 #include "qemu/error-report.h"
40 #include "qemu/qemu-print.h"
41 #include "exec/memory.h"
42 #include "exec/ioport.h"
43 #include "sysemu/dma.h"
44 #include "sysemu/hostmem.h"
45 #include "sysemu/hw_accel.h"
46 #include "exec/address-spaces.h"
47 #include "sysemu/xen-mapcache.h"
48 #include "trace/trace-root.h"
50 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
51 #include <linux/falloc.h>
52 #endif
54 #include "qemu/rcu_queue.h"
55 #include "qemu/main-loop.h"
56 #include "exec/translate-all.h"
57 #include "sysemu/replay.h"
59 #include "exec/memory-internal.h"
60 #include "exec/ram_addr.h"
61 #include "exec/log.h"
63 #include "qemu/pmem.h"
65 #include "migration/vmstate.h"
67 #include "qemu/range.h"
68 #ifndef _WIN32
69 #include "qemu/mmap-alloc.h"
70 #endif
72 #include "monitor/monitor.h"
74 #ifdef CONFIG_LIBDAXCTL
75 #include <daxctl/libdaxctl.h>
76 #endif
78 //#define DEBUG_SUBPAGE
80 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
81 * are protected by the ramlist lock.
83 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
85 static MemoryRegion *system_memory;
86 static MemoryRegion *system_io;
88 AddressSpace address_space_io;
89 AddressSpace address_space_memory;
91 static MemoryRegion io_mem_unassigned;
93 typedef struct PhysPageEntry PhysPageEntry;
95 struct PhysPageEntry {
96 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
97 uint32_t skip : 6;
98 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
99 uint32_t ptr : 26;
102 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
104 /* Size of the L2 (and L3, etc) page tables. */
105 #define ADDR_SPACE_BITS 64
107 #define P_L2_BITS 9
108 #define P_L2_SIZE (1 << P_L2_BITS)
110 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
112 typedef PhysPageEntry Node[P_L2_SIZE];
114 typedef struct PhysPageMap {
115 struct rcu_head rcu;
117 unsigned sections_nb;
118 unsigned sections_nb_alloc;
119 unsigned nodes_nb;
120 unsigned nodes_nb_alloc;
121 Node *nodes;
122 MemoryRegionSection *sections;
123 } PhysPageMap;
125 struct AddressSpaceDispatch {
126 MemoryRegionSection *mru_section;
127 /* This is a multi-level map on the physical address space.
128 * The bottom level has pointers to MemoryRegionSections.
130 PhysPageEntry phys_map;
131 PhysPageMap map;
134 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
135 typedef struct subpage_t {
136 MemoryRegion iomem;
137 FlatView *fv;
138 hwaddr base;
139 uint16_t sub_section[];
140 } subpage_t;
142 #define PHYS_SECTION_UNASSIGNED 0
144 static void io_mem_init(void);
145 static void memory_map_init(void);
146 static void tcg_log_global_after_sync(MemoryListener *listener);
147 static void tcg_commit(MemoryListener *listener);
150 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
151 * @cpu: the CPU whose AddressSpace this is
152 * @as: the AddressSpace itself
153 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
154 * @tcg_as_listener: listener for tracking changes to the AddressSpace
156 struct CPUAddressSpace {
157 CPUState *cpu;
158 AddressSpace *as;
159 struct AddressSpaceDispatch *memory_dispatch;
160 MemoryListener tcg_as_listener;
163 struct DirtyBitmapSnapshot {
164 ram_addr_t start;
165 ram_addr_t end;
166 unsigned long dirty[];
169 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
171 static unsigned alloc_hint = 16;
172 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
173 map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
174 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
175 alloc_hint = map->nodes_nb_alloc;
179 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
181 unsigned i;
182 uint32_t ret;
183 PhysPageEntry e;
184 PhysPageEntry *p;
186 ret = map->nodes_nb++;
187 p = map->nodes[ret];
188 assert(ret != PHYS_MAP_NODE_NIL);
189 assert(ret != map->nodes_nb_alloc);
191 e.skip = leaf ? 0 : 1;
192 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
193 for (i = 0; i < P_L2_SIZE; ++i) {
194 memcpy(&p[i], &e, sizeof(e));
196 return ret;
199 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
200 hwaddr *index, uint64_t *nb, uint16_t leaf,
201 int level)
203 PhysPageEntry *p;
204 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
206 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
207 lp->ptr = phys_map_node_alloc(map, level == 0);
209 p = map->nodes[lp->ptr];
210 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
212 while (*nb && lp < &p[P_L2_SIZE]) {
213 if ((*index & (step - 1)) == 0 && *nb >= step) {
214 lp->skip = 0;
215 lp->ptr = leaf;
216 *index += step;
217 *nb -= step;
218 } else {
219 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
221 ++lp;
225 static void phys_page_set(AddressSpaceDispatch *d,
226 hwaddr index, uint64_t nb,
227 uint16_t leaf)
229 /* Wildly overreserve - it doesn't matter much. */
230 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
232 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
235 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
236 * and update our entry so we can skip it and go directly to the destination.
238 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
240 unsigned valid_ptr = P_L2_SIZE;
241 int valid = 0;
242 PhysPageEntry *p;
243 int i;
245 if (lp->ptr == PHYS_MAP_NODE_NIL) {
246 return;
249 p = nodes[lp->ptr];
250 for (i = 0; i < P_L2_SIZE; i++) {
251 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
252 continue;
255 valid_ptr = i;
256 valid++;
257 if (p[i].skip) {
258 phys_page_compact(&p[i], nodes);
262 /* We can only compress if there's only one child. */
263 if (valid != 1) {
264 return;
267 assert(valid_ptr < P_L2_SIZE);
269 /* Don't compress if it won't fit in the # of bits we have. */
270 if (P_L2_LEVELS >= (1 << 6) &&
271 lp->skip + p[valid_ptr].skip >= (1 << 6)) {
272 return;
275 lp->ptr = p[valid_ptr].ptr;
276 if (!p[valid_ptr].skip) {
277 /* If our only child is a leaf, make this a leaf. */
278 /* By design, we should have made this node a leaf to begin with so we
279 * should never reach here.
280 * But since it's so simple to handle this, let's do it just in case we
281 * change this rule.
283 lp->skip = 0;
284 } else {
285 lp->skip += p[valid_ptr].skip;
289 void address_space_dispatch_compact(AddressSpaceDispatch *d)
291 if (d->phys_map.skip) {
292 phys_page_compact(&d->phys_map, d->map.nodes);
296 static inline bool section_covers_addr(const MemoryRegionSection *section,
297 hwaddr addr)
299 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
300 * the section must cover the entire address space.
302 return int128_gethi(section->size) ||
303 range_covers_byte(section->offset_within_address_space,
304 int128_getlo(section->size), addr);
307 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
309 PhysPageEntry lp = d->phys_map, *p;
310 Node *nodes = d->map.nodes;
311 MemoryRegionSection *sections = d->map.sections;
312 hwaddr index = addr >> TARGET_PAGE_BITS;
313 int i;
315 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
316 if (lp.ptr == PHYS_MAP_NODE_NIL) {
317 return &sections[PHYS_SECTION_UNASSIGNED];
319 p = nodes[lp.ptr];
320 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
323 if (section_covers_addr(&sections[lp.ptr], addr)) {
324 return &sections[lp.ptr];
325 } else {
326 return &sections[PHYS_SECTION_UNASSIGNED];
330 /* Called from RCU critical section */
331 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
332 hwaddr addr,
333 bool resolve_subpage)
335 MemoryRegionSection *section = qatomic_read(&d->mru_section);
336 subpage_t *subpage;
338 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
339 !section_covers_addr(section, addr)) {
340 section = phys_page_find(d, addr);
341 qatomic_set(&d->mru_section, section);
343 if (resolve_subpage && section->mr->subpage) {
344 subpage = container_of(section->mr, subpage_t, iomem);
345 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
347 return section;
350 /* Called from RCU critical section */
351 static MemoryRegionSection *
352 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
353 hwaddr *plen, bool resolve_subpage)
355 MemoryRegionSection *section;
356 MemoryRegion *mr;
357 Int128 diff;
359 section = address_space_lookup_region(d, addr, resolve_subpage);
360 /* Compute offset within MemoryRegionSection */
361 addr -= section->offset_within_address_space;
363 /* Compute offset within MemoryRegion */
364 *xlat = addr + section->offset_within_region;
366 mr = section->mr;
368 /* MMIO registers can be expected to perform full-width accesses based only
369 * on their address, without considering adjacent registers that could
370 * decode to completely different MemoryRegions. When such registers
371 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
372 * regions overlap wildly. For this reason we cannot clamp the accesses
373 * here.
375 * If the length is small (as is the case for address_space_ldl/stl),
376 * everything works fine. If the incoming length is large, however,
377 * the caller really has to do the clamping through memory_access_size.
379 if (memory_region_is_ram(mr)) {
380 diff = int128_sub(section->size, int128_make64(addr));
381 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
383 return section;
387 * address_space_translate_iommu - translate an address through an IOMMU
388 * memory region and then through the target address space.
390 * @iommu_mr: the IOMMU memory region that we start the translation from
391 * @addr: the address to be translated through the MMU
392 * @xlat: the translated address offset within the destination memory region.
393 * It cannot be %NULL.
394 * @plen_out: valid read/write length of the translated address. It
395 * cannot be %NULL.
396 * @page_mask_out: page mask for the translated address. This
397 * should only be meaningful for IOMMU translated
398 * addresses, since there may be huge pages that this bit
399 * would tell. It can be %NULL if we don't care about it.
400 * @is_write: whether the translation operation is for write
401 * @is_mmio: whether this can be MMIO, set true if it can
402 * @target_as: the address space targeted by the IOMMU
403 * @attrs: transaction attributes
405 * This function is called from RCU critical section. It is the common
406 * part of flatview_do_translate and address_space_translate_cached.
408 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
409 hwaddr *xlat,
410 hwaddr *plen_out,
411 hwaddr *page_mask_out,
412 bool is_write,
413 bool is_mmio,
414 AddressSpace **target_as,
415 MemTxAttrs attrs)
417 MemoryRegionSection *section;
418 hwaddr page_mask = (hwaddr)-1;
420 do {
421 hwaddr addr = *xlat;
422 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
423 int iommu_idx = 0;
424 IOMMUTLBEntry iotlb;
426 if (imrc->attrs_to_index) {
427 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
430 iotlb = imrc->translate(iommu_mr, addr, is_write ?
431 IOMMU_WO : IOMMU_RO, iommu_idx);
433 if (!(iotlb.perm & (1 << is_write))) {
434 goto unassigned;
437 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
438 | (addr & iotlb.addr_mask));
439 page_mask &= iotlb.addr_mask;
440 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
441 *target_as = iotlb.target_as;
443 section = address_space_translate_internal(
444 address_space_to_dispatch(iotlb.target_as), addr, xlat,
445 plen_out, is_mmio);
447 iommu_mr = memory_region_get_iommu(section->mr);
448 } while (unlikely(iommu_mr));
450 if (page_mask_out) {
451 *page_mask_out = page_mask;
453 return *section;
455 unassigned:
456 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
460 * flatview_do_translate - translate an address in FlatView
462 * @fv: the flat view that we want to translate on
463 * @addr: the address to be translated in above address space
464 * @xlat: the translated address offset within memory region. It
465 * cannot be @NULL.
466 * @plen_out: valid read/write length of the translated address. It
467 * can be @NULL when we don't care about it.
468 * @page_mask_out: page mask for the translated address. This
469 * should only be meaningful for IOMMU translated
470 * addresses, since there may be huge pages that this bit
471 * would tell. It can be @NULL if we don't care about it.
472 * @is_write: whether the translation operation is for write
473 * @is_mmio: whether this can be MMIO, set true if it can
474 * @target_as: the address space targeted by the IOMMU
475 * @attrs: memory transaction attributes
477 * This function is called from RCU critical section
479 static MemoryRegionSection flatview_do_translate(FlatView *fv,
480 hwaddr addr,
481 hwaddr *xlat,
482 hwaddr *plen_out,
483 hwaddr *page_mask_out,
484 bool is_write,
485 bool is_mmio,
486 AddressSpace **target_as,
487 MemTxAttrs attrs)
489 MemoryRegionSection *section;
490 IOMMUMemoryRegion *iommu_mr;
491 hwaddr plen = (hwaddr)(-1);
493 if (!plen_out) {
494 plen_out = &plen;
497 section = address_space_translate_internal(
498 flatview_to_dispatch(fv), addr, xlat,
499 plen_out, is_mmio);
501 iommu_mr = memory_region_get_iommu(section->mr);
502 if (unlikely(iommu_mr)) {
503 return address_space_translate_iommu(iommu_mr, xlat,
504 plen_out, page_mask_out,
505 is_write, is_mmio,
506 target_as, attrs);
508 if (page_mask_out) {
509 /* Not behind an IOMMU, use default page size. */
510 *page_mask_out = ~TARGET_PAGE_MASK;
513 return *section;
516 /* Called from RCU critical section */
517 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
518 bool is_write, MemTxAttrs attrs)
520 MemoryRegionSection section;
521 hwaddr xlat, page_mask;
524 * This can never be MMIO, and we don't really care about plen,
525 * but page mask.
527 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
528 NULL, &page_mask, is_write, false, &as,
529 attrs);
531 /* Illegal translation */
532 if (section.mr == &io_mem_unassigned) {
533 goto iotlb_fail;
536 /* Convert memory region offset into address space offset */
537 xlat += section.offset_within_address_space -
538 section.offset_within_region;
540 return (IOMMUTLBEntry) {
541 .target_as = as,
542 .iova = addr & ~page_mask,
543 .translated_addr = xlat & ~page_mask,
544 .addr_mask = page_mask,
545 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
546 .perm = IOMMU_RW,
549 iotlb_fail:
550 return (IOMMUTLBEntry) {0};
553 /* Called from RCU critical section */
554 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
555 hwaddr *plen, bool is_write,
556 MemTxAttrs attrs)
558 MemoryRegion *mr;
559 MemoryRegionSection section;
560 AddressSpace *as = NULL;
562 /* This can be MMIO, so setup MMIO bit. */
563 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
564 is_write, true, &as, attrs);
565 mr = section.mr;
567 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
568 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
569 *plen = MIN(page, *plen);
572 return mr;
575 typedef struct TCGIOMMUNotifier {
576 IOMMUNotifier n;
577 MemoryRegion *mr;
578 CPUState *cpu;
579 int iommu_idx;
580 bool active;
581 } TCGIOMMUNotifier;
583 static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
585 TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
587 if (!notifier->active) {
588 return;
590 tlb_flush(notifier->cpu);
591 notifier->active = false;
592 /* We leave the notifier struct on the list to avoid reallocating it later.
593 * Generally the number of IOMMUs a CPU deals with will be small.
594 * In any case we can't unregister the iommu notifier from a notify
595 * callback.
599 static void tcg_register_iommu_notifier(CPUState *cpu,
600 IOMMUMemoryRegion *iommu_mr,
601 int iommu_idx)
603 /* Make sure this CPU has an IOMMU notifier registered for this
604 * IOMMU/IOMMU index combination, so that we can flush its TLB
605 * when the IOMMU tells us the mappings we've cached have changed.
607 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
608 TCGIOMMUNotifier *notifier = NULL;
609 int i;
611 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
612 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
613 if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
614 break;
617 if (i == cpu->iommu_notifiers->len) {
618 /* Not found, add a new entry at the end of the array */
619 cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
620 notifier = g_new0(TCGIOMMUNotifier, 1);
621 g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
623 notifier->mr = mr;
624 notifier->iommu_idx = iommu_idx;
625 notifier->cpu = cpu;
626 /* Rather than trying to register interest in the specific part
627 * of the iommu's address space that we've accessed and then
628 * expand it later as subsequent accesses touch more of it, we
629 * just register interest in the whole thing, on the assumption
630 * that iommu reconfiguration will be rare.
632 iommu_notifier_init(&notifier->n,
633 tcg_iommu_unmap_notify,
634 IOMMU_NOTIFIER_UNMAP,
636 HWADDR_MAX,
637 iommu_idx);
638 memory_region_register_iommu_notifier(notifier->mr, &notifier->n,
639 &error_fatal);
642 if (!notifier->active) {
643 notifier->active = true;
647 void tcg_iommu_free_notifier_list(CPUState *cpu)
649 /* Destroy the CPU's notifier list */
650 int i;
651 TCGIOMMUNotifier *notifier;
653 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
654 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
655 memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
656 g_free(notifier);
658 g_array_free(cpu->iommu_notifiers, true);
661 void tcg_iommu_init_notifier_list(CPUState *cpu)
663 cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
666 /* Called from RCU critical section */
667 MemoryRegionSection *
668 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
669 hwaddr *xlat, hwaddr *plen,
670 MemTxAttrs attrs, int *prot)
672 MemoryRegionSection *section;
673 IOMMUMemoryRegion *iommu_mr;
674 IOMMUMemoryRegionClass *imrc;
675 IOMMUTLBEntry iotlb;
676 int iommu_idx;
677 AddressSpaceDispatch *d =
678 qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
680 for (;;) {
681 section = address_space_translate_internal(d, addr, &addr, plen, false);
683 iommu_mr = memory_region_get_iommu(section->mr);
684 if (!iommu_mr) {
685 break;
688 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
690 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
691 tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
692 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
693 * doesn't short-cut its translation table walk.
695 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
696 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
697 | (addr & iotlb.addr_mask));
698 /* Update the caller's prot bits to remove permissions the IOMMU
699 * is giving us a failure response for. If we get down to no
700 * permissions left at all we can give up now.
702 if (!(iotlb.perm & IOMMU_RO)) {
703 *prot &= ~(PAGE_READ | PAGE_EXEC);
705 if (!(iotlb.perm & IOMMU_WO)) {
706 *prot &= ~PAGE_WRITE;
709 if (!*prot) {
710 goto translate_fail;
713 d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
716 assert(!memory_region_is_iommu(section->mr));
717 *xlat = addr;
718 return section;
720 translate_fail:
721 return &d->map.sections[PHYS_SECTION_UNASSIGNED];
724 void cpu_address_space_init(CPUState *cpu, int asidx,
725 const char *prefix, MemoryRegion *mr)
727 CPUAddressSpace *newas;
728 AddressSpace *as = g_new0(AddressSpace, 1);
729 char *as_name;
731 assert(mr);
732 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
733 address_space_init(as, mr, as_name);
734 g_free(as_name);
736 /* Target code should have set num_ases before calling us */
737 assert(asidx < cpu->num_ases);
739 if (asidx == 0) {
740 /* address space 0 gets the convenience alias */
741 cpu->as = as;
744 /* KVM cannot currently support multiple address spaces. */
745 assert(asidx == 0 || !kvm_enabled());
747 if (!cpu->cpu_ases) {
748 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
751 newas = &cpu->cpu_ases[asidx];
752 newas->cpu = cpu;
753 newas->as = as;
754 if (tcg_enabled()) {
755 newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
756 newas->tcg_as_listener.commit = tcg_commit;
757 memory_listener_register(&newas->tcg_as_listener, as);
761 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
763 /* Return the AddressSpace corresponding to the specified index */
764 return cpu->cpu_ases[asidx].as;
767 /* Add a watchpoint. */
768 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
769 int flags, CPUWatchpoint **watchpoint)
771 CPUWatchpoint *wp;
772 vaddr in_page;
774 /* forbid ranges which are empty or run off the end of the address space */
775 if (len == 0 || (addr + len - 1) < addr) {
776 error_report("tried to set invalid watchpoint at %"
777 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
778 return -EINVAL;
780 wp = g_malloc(sizeof(*wp));
782 wp->vaddr = addr;
783 wp->len = len;
784 wp->flags = flags;
786 /* keep all GDB-injected watchpoints in front */
787 if (flags & BP_GDB) {
788 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
789 } else {
790 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
793 in_page = -(addr | TARGET_PAGE_MASK);
794 if (len <= in_page) {
795 tlb_flush_page(cpu, addr);
796 } else {
797 tlb_flush(cpu);
800 if (watchpoint)
801 *watchpoint = wp;
802 return 0;
805 /* Remove a specific watchpoint. */
806 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
807 int flags)
809 CPUWatchpoint *wp;
811 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
812 if (addr == wp->vaddr && len == wp->len
813 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
814 cpu_watchpoint_remove_by_ref(cpu, wp);
815 return 0;
818 return -ENOENT;
821 /* Remove a specific watchpoint by reference. */
822 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
824 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
826 tlb_flush_page(cpu, watchpoint->vaddr);
828 g_free(watchpoint);
831 /* Remove all matching watchpoints. */
832 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
834 CPUWatchpoint *wp, *next;
836 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
837 if (wp->flags & mask) {
838 cpu_watchpoint_remove_by_ref(cpu, wp);
843 /* Return true if this watchpoint address matches the specified
844 * access (ie the address range covered by the watchpoint overlaps
845 * partially or completely with the address range covered by the
846 * access).
848 static inline bool watchpoint_address_matches(CPUWatchpoint *wp,
849 vaddr addr, vaddr len)
851 /* We know the lengths are non-zero, but a little caution is
852 * required to avoid errors in the case where the range ends
853 * exactly at the top of the address space and so addr + len
854 * wraps round to zero.
856 vaddr wpend = wp->vaddr + wp->len - 1;
857 vaddr addrend = addr + len - 1;
859 return !(addr > wpend || wp->vaddr > addrend);
862 /* Return flags for watchpoints that match addr + prot. */
863 int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len)
865 CPUWatchpoint *wp;
866 int ret = 0;
868 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
869 if (watchpoint_address_matches(wp, addr, len)) {
870 ret |= wp->flags;
873 return ret;
876 /* Called from RCU critical section */
877 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
879 RAMBlock *block;
881 block = qatomic_rcu_read(&ram_list.mru_block);
882 if (block && addr - block->offset < block->max_length) {
883 return block;
885 RAMBLOCK_FOREACH(block) {
886 if (addr - block->offset < block->max_length) {
887 goto found;
891 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
892 abort();
894 found:
895 /* It is safe to write mru_block outside the iothread lock. This
896 * is what happens:
898 * mru_block = xxx
899 * rcu_read_unlock()
900 * xxx removed from list
901 * rcu_read_lock()
902 * read mru_block
903 * mru_block = NULL;
904 * call_rcu(reclaim_ramblock, xxx);
905 * rcu_read_unlock()
907 * qatomic_rcu_set is not needed here. The block was already published
908 * when it was placed into the list. Here we're just making an extra
909 * copy of the pointer.
911 ram_list.mru_block = block;
912 return block;
915 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
917 CPUState *cpu;
918 ram_addr_t start1;
919 RAMBlock *block;
920 ram_addr_t end;
922 assert(tcg_enabled());
923 end = TARGET_PAGE_ALIGN(start + length);
924 start &= TARGET_PAGE_MASK;
926 RCU_READ_LOCK_GUARD();
927 block = qemu_get_ram_block(start);
928 assert(block == qemu_get_ram_block(end - 1));
929 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
930 CPU_FOREACH(cpu) {
931 tlb_reset_dirty(cpu, start1, length);
935 /* Note: start and end must be within the same ram block. */
936 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
937 ram_addr_t length,
938 unsigned client)
940 DirtyMemoryBlocks *blocks;
941 unsigned long end, page, start_page;
942 bool dirty = false;
943 RAMBlock *ramblock;
944 uint64_t mr_offset, mr_size;
946 if (length == 0) {
947 return false;
950 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
951 start_page = start >> TARGET_PAGE_BITS;
952 page = start_page;
954 WITH_RCU_READ_LOCK_GUARD() {
955 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
956 ramblock = qemu_get_ram_block(start);
957 /* Range sanity check on the ramblock */
958 assert(start >= ramblock->offset &&
959 start + length <= ramblock->offset + ramblock->used_length);
961 while (page < end) {
962 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
963 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
964 unsigned long num = MIN(end - page,
965 DIRTY_MEMORY_BLOCK_SIZE - offset);
967 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
968 offset, num);
969 page += num;
972 mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
973 mr_size = (end - start_page) << TARGET_PAGE_BITS;
974 memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
977 if (dirty && tcg_enabled()) {
978 tlb_reset_dirty_range_all(start, length);
981 return dirty;
984 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
985 (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
987 DirtyMemoryBlocks *blocks;
988 ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
989 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
990 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
991 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
992 DirtyBitmapSnapshot *snap;
993 unsigned long page, end, dest;
995 snap = g_malloc0(sizeof(*snap) +
996 ((last - first) >> (TARGET_PAGE_BITS + 3)));
997 snap->start = first;
998 snap->end = last;
1000 page = first >> TARGET_PAGE_BITS;
1001 end = last >> TARGET_PAGE_BITS;
1002 dest = 0;
1004 WITH_RCU_READ_LOCK_GUARD() {
1005 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1007 while (page < end) {
1008 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1009 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1010 unsigned long num = MIN(end - page,
1011 DIRTY_MEMORY_BLOCK_SIZE - offset);
1013 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1014 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1015 offset >>= BITS_PER_LEVEL;
1017 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1018 blocks->blocks[idx] + offset,
1019 num);
1020 page += num;
1021 dest += num >> BITS_PER_LEVEL;
1025 if (tcg_enabled()) {
1026 tlb_reset_dirty_range_all(start, length);
1029 memory_region_clear_dirty_bitmap(mr, offset, length);
1031 return snap;
1034 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1035 ram_addr_t start,
1036 ram_addr_t length)
1038 unsigned long page, end;
1040 assert(start >= snap->start);
1041 assert(start + length <= snap->end);
1043 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1044 page = (start - snap->start) >> TARGET_PAGE_BITS;
1046 while (page < end) {
1047 if (test_bit(page, snap->dirty)) {
1048 return true;
1050 page++;
1052 return false;
1055 /* Called from RCU critical section */
1056 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1057 MemoryRegionSection *section)
1059 AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
1060 return section - d->map.sections;
1063 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
1064 uint16_t section);
1065 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1067 static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
1068 qemu_anon_ram_alloc;
1071 * Set a custom physical guest memory alloator.
1072 * Accelerators with unusual needs may need this. Hopefully, we can
1073 * get rid of it eventually.
1075 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
1077 phys_mem_alloc = alloc;
1080 static uint16_t phys_section_add(PhysPageMap *map,
1081 MemoryRegionSection *section)
1083 /* The physical section number is ORed with a page-aligned
1084 * pointer to produce the iotlb entries. Thus it should
1085 * never overflow into the page-aligned value.
1087 assert(map->sections_nb < TARGET_PAGE_SIZE);
1089 if (map->sections_nb == map->sections_nb_alloc) {
1090 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1091 map->sections = g_renew(MemoryRegionSection, map->sections,
1092 map->sections_nb_alloc);
1094 map->sections[map->sections_nb] = *section;
1095 memory_region_ref(section->mr);
1096 return map->sections_nb++;
1099 static void phys_section_destroy(MemoryRegion *mr)
1101 bool have_sub_page = mr->subpage;
1103 memory_region_unref(mr);
1105 if (have_sub_page) {
1106 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1107 object_unref(OBJECT(&subpage->iomem));
1108 g_free(subpage);
1112 static void phys_sections_free(PhysPageMap *map)
1114 while (map->sections_nb > 0) {
1115 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1116 phys_section_destroy(section->mr);
1118 g_free(map->sections);
1119 g_free(map->nodes);
1122 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1124 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1125 subpage_t *subpage;
1126 hwaddr base = section->offset_within_address_space
1127 & TARGET_PAGE_MASK;
1128 MemoryRegionSection *existing = phys_page_find(d, base);
1129 MemoryRegionSection subsection = {
1130 .offset_within_address_space = base,
1131 .size = int128_make64(TARGET_PAGE_SIZE),
1133 hwaddr start, end;
1135 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1137 if (!(existing->mr->subpage)) {
1138 subpage = subpage_init(fv, base);
1139 subsection.fv = fv;
1140 subsection.mr = &subpage->iomem;
1141 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1142 phys_section_add(&d->map, &subsection));
1143 } else {
1144 subpage = container_of(existing->mr, subpage_t, iomem);
1146 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1147 end = start + int128_get64(section->size) - 1;
1148 subpage_register(subpage, start, end,
1149 phys_section_add(&d->map, section));
1153 static void register_multipage(FlatView *fv,
1154 MemoryRegionSection *section)
1156 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1157 hwaddr start_addr = section->offset_within_address_space;
1158 uint16_t section_index = phys_section_add(&d->map, section);
1159 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1160 TARGET_PAGE_BITS));
1162 assert(num_pages);
1163 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1167 * The range in *section* may look like this:
1169 * |s|PPPPPPP|s|
1171 * where s stands for subpage and P for page.
1173 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1175 MemoryRegionSection remain = *section;
1176 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1178 /* register first subpage */
1179 if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1180 uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1181 - remain.offset_within_address_space;
1183 MemoryRegionSection now = remain;
1184 now.size = int128_min(int128_make64(left), now.size);
1185 register_subpage(fv, &now);
1186 if (int128_eq(remain.size, now.size)) {
1187 return;
1189 remain.size = int128_sub(remain.size, now.size);
1190 remain.offset_within_address_space += int128_get64(now.size);
1191 remain.offset_within_region += int128_get64(now.size);
1194 /* register whole pages */
1195 if (int128_ge(remain.size, page_size)) {
1196 MemoryRegionSection now = remain;
1197 now.size = int128_and(now.size, int128_neg(page_size));
1198 register_multipage(fv, &now);
1199 if (int128_eq(remain.size, now.size)) {
1200 return;
1202 remain.size = int128_sub(remain.size, now.size);
1203 remain.offset_within_address_space += int128_get64(now.size);
1204 remain.offset_within_region += int128_get64(now.size);
1207 /* register last subpage */
1208 register_subpage(fv, &remain);
1211 void qemu_flush_coalesced_mmio_buffer(void)
1213 if (kvm_enabled())
1214 kvm_flush_coalesced_mmio_buffer();
1217 void qemu_mutex_lock_ramlist(void)
1219 qemu_mutex_lock(&ram_list.mutex);
1222 void qemu_mutex_unlock_ramlist(void)
1224 qemu_mutex_unlock(&ram_list.mutex);
1227 void ram_block_dump(Monitor *mon)
1229 RAMBlock *block;
1230 char *psize;
1232 RCU_READ_LOCK_GUARD();
1233 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1234 "Block Name", "PSize", "Offset", "Used", "Total");
1235 RAMBLOCK_FOREACH(block) {
1236 psize = size_to_str(block->page_size);
1237 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1238 " 0x%016" PRIx64 "\n", block->idstr, psize,
1239 (uint64_t)block->offset,
1240 (uint64_t)block->used_length,
1241 (uint64_t)block->max_length);
1242 g_free(psize);
1246 #ifdef __linux__
1248 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1249 * may or may not name the same files / on the same filesystem now as
1250 * when we actually open and map them. Iterate over the file
1251 * descriptors instead, and use qemu_fd_getpagesize().
1253 static int find_min_backend_pagesize(Object *obj, void *opaque)
1255 long *hpsize_min = opaque;
1257 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1258 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1259 long hpsize = host_memory_backend_pagesize(backend);
1261 if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
1262 *hpsize_min = hpsize;
1266 return 0;
1269 static int find_max_backend_pagesize(Object *obj, void *opaque)
1271 long *hpsize_max = opaque;
1273 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1274 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1275 long hpsize = host_memory_backend_pagesize(backend);
1277 if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1278 *hpsize_max = hpsize;
1282 return 0;
1286 * TODO: We assume right now that all mapped host memory backends are
1287 * used as RAM, however some might be used for different purposes.
1289 long qemu_minrampagesize(void)
1291 long hpsize = LONG_MAX;
1292 Object *memdev_root = object_resolve_path("/objects", NULL);
1294 object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
1295 return hpsize;
1298 long qemu_maxrampagesize(void)
1300 long pagesize = 0;
1301 Object *memdev_root = object_resolve_path("/objects", NULL);
1303 object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
1304 return pagesize;
1306 #else
1307 long qemu_minrampagesize(void)
1309 return qemu_real_host_page_size;
1311 long qemu_maxrampagesize(void)
1313 return qemu_real_host_page_size;
1315 #endif
1317 #ifdef CONFIG_POSIX
1318 static int64_t get_file_size(int fd)
1320 int64_t size;
1321 #if defined(__linux__)
1322 struct stat st;
1324 if (fstat(fd, &st) < 0) {
1325 return -errno;
1328 /* Special handling for devdax character devices */
1329 if (S_ISCHR(st.st_mode)) {
1330 g_autofree char *subsystem_path = NULL;
1331 g_autofree char *subsystem = NULL;
1333 subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1334 major(st.st_rdev), minor(st.st_rdev));
1335 subsystem = g_file_read_link(subsystem_path, NULL);
1337 if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
1338 g_autofree char *size_path = NULL;
1339 g_autofree char *size_str = NULL;
1341 size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
1342 major(st.st_rdev), minor(st.st_rdev));
1344 if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
1345 return g_ascii_strtoll(size_str, NULL, 0);
1349 #endif /* defined(__linux__) */
1351 /* st.st_size may be zero for special files yet lseek(2) works */
1352 size = lseek(fd, 0, SEEK_END);
1353 if (size < 0) {
1354 return -errno;
1356 return size;
1359 static int64_t get_file_align(int fd)
1361 int64_t align = -1;
1362 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1363 struct stat st;
1365 if (fstat(fd, &st) < 0) {
1366 return -errno;
1369 /* Special handling for devdax character devices */
1370 if (S_ISCHR(st.st_mode)) {
1371 g_autofree char *path = NULL;
1372 g_autofree char *rpath = NULL;
1373 struct daxctl_ctx *ctx;
1374 struct daxctl_region *region;
1375 int rc = 0;
1377 path = g_strdup_printf("/sys/dev/char/%d:%d",
1378 major(st.st_rdev), minor(st.st_rdev));
1379 rpath = realpath(path, NULL);
1381 rc = daxctl_new(&ctx);
1382 if (rc) {
1383 return -1;
1386 daxctl_region_foreach(ctx, region) {
1387 if (strstr(rpath, daxctl_region_get_path(region))) {
1388 align = daxctl_region_get_align(region);
1389 break;
1392 daxctl_unref(ctx);
1394 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1396 return align;
1399 static int file_ram_open(const char *path,
1400 const char *region_name,
1401 bool readonly,
1402 bool *created,
1403 Error **errp)
1405 char *filename;
1406 char *sanitized_name;
1407 char *c;
1408 int fd = -1;
1410 *created = false;
1411 for (;;) {
1412 fd = open(path, readonly ? O_RDONLY : O_RDWR);
1413 if (fd >= 0) {
1414 /* @path names an existing file, use it */
1415 break;
1417 if (errno == ENOENT) {
1418 /* @path names a file that doesn't exist, create it */
1419 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1420 if (fd >= 0) {
1421 *created = true;
1422 break;
1424 } else if (errno == EISDIR) {
1425 /* @path names a directory, create a file there */
1426 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1427 sanitized_name = g_strdup(region_name);
1428 for (c = sanitized_name; *c != '\0'; c++) {
1429 if (*c == '/') {
1430 *c = '_';
1434 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1435 sanitized_name);
1436 g_free(sanitized_name);
1438 fd = mkstemp(filename);
1439 if (fd >= 0) {
1440 unlink(filename);
1441 g_free(filename);
1442 break;
1444 g_free(filename);
1446 if (errno != EEXIST && errno != EINTR) {
1447 error_setg_errno(errp, errno,
1448 "can't open backing store %s for guest RAM",
1449 path);
1450 return -1;
1453 * Try again on EINTR and EEXIST. The latter happens when
1454 * something else creates the file between our two open().
1458 return fd;
1461 static void *file_ram_alloc(RAMBlock *block,
1462 ram_addr_t memory,
1463 int fd,
1464 bool readonly,
1465 bool truncate,
1466 Error **errp)
1468 void *area;
1470 block->page_size = qemu_fd_getpagesize(fd);
1471 if (block->mr->align % block->page_size) {
1472 error_setg(errp, "alignment 0x%" PRIx64
1473 " must be multiples of page size 0x%zx",
1474 block->mr->align, block->page_size);
1475 return NULL;
1476 } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1477 error_setg(errp, "alignment 0x%" PRIx64
1478 " must be a power of two", block->mr->align);
1479 return NULL;
1481 block->mr->align = MAX(block->page_size, block->mr->align);
1482 #if defined(__s390x__)
1483 if (kvm_enabled()) {
1484 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1486 #endif
1488 if (memory < block->page_size) {
1489 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1490 "or larger than page size 0x%zx",
1491 memory, block->page_size);
1492 return NULL;
1495 memory = ROUND_UP(memory, block->page_size);
1498 * ftruncate is not supported by hugetlbfs in older
1499 * hosts, so don't bother bailing out on errors.
1500 * If anything goes wrong with it under other filesystems,
1501 * mmap will fail.
1503 * Do not truncate the non-empty backend file to avoid corrupting
1504 * the existing data in the file. Disabling shrinking is not
1505 * enough. For example, the current vNVDIMM implementation stores
1506 * the guest NVDIMM labels at the end of the backend file. If the
1507 * backend file is later extended, QEMU will not be able to find
1508 * those labels. Therefore, extending the non-empty backend file
1509 * is disabled as well.
1511 if (truncate && ftruncate(fd, memory)) {
1512 perror("ftruncate");
1515 area = qemu_ram_mmap(fd, memory, block->mr->align, readonly,
1516 block->flags & RAM_SHARED, block->flags & RAM_PMEM);
1517 if (area == MAP_FAILED) {
1518 error_setg_errno(errp, errno,
1519 "unable to map backing store for guest RAM");
1520 return NULL;
1523 block->fd = fd;
1524 return area;
1526 #endif
1528 /* Allocate space within the ram_addr_t space that governs the
1529 * dirty bitmaps.
1530 * Called with the ramlist lock held.
1532 static ram_addr_t find_ram_offset(ram_addr_t size)
1534 RAMBlock *block, *next_block;
1535 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1537 assert(size != 0); /* it would hand out same offset multiple times */
1539 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1540 return 0;
1543 RAMBLOCK_FOREACH(block) {
1544 ram_addr_t candidate, next = RAM_ADDR_MAX;
1546 /* Align blocks to start on a 'long' in the bitmap
1547 * which makes the bitmap sync'ing take the fast path.
1549 candidate = block->offset + block->max_length;
1550 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1552 /* Search for the closest following block
1553 * and find the gap.
1555 RAMBLOCK_FOREACH(next_block) {
1556 if (next_block->offset >= candidate) {
1557 next = MIN(next, next_block->offset);
1561 /* If it fits remember our place and remember the size
1562 * of gap, but keep going so that we might find a smaller
1563 * gap to fill so avoiding fragmentation.
1565 if (next - candidate >= size && next - candidate < mingap) {
1566 offset = candidate;
1567 mingap = next - candidate;
1570 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1573 if (offset == RAM_ADDR_MAX) {
1574 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1575 (uint64_t)size);
1576 abort();
1579 trace_find_ram_offset(size, offset);
1581 return offset;
1584 static unsigned long last_ram_page(void)
1586 RAMBlock *block;
1587 ram_addr_t last = 0;
1589 RCU_READ_LOCK_GUARD();
1590 RAMBLOCK_FOREACH(block) {
1591 last = MAX(last, block->offset + block->max_length);
1593 return last >> TARGET_PAGE_BITS;
1596 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1598 int ret;
1600 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1601 if (!machine_dump_guest_core(current_machine)) {
1602 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1603 if (ret) {
1604 perror("qemu_madvise");
1605 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1606 "but dump_guest_core=off specified\n");
1611 const char *qemu_ram_get_idstr(RAMBlock *rb)
1613 return rb->idstr;
1616 void *qemu_ram_get_host_addr(RAMBlock *rb)
1618 return rb->host;
1621 ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
1623 return rb->offset;
1626 ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
1628 return rb->used_length;
1631 bool qemu_ram_is_shared(RAMBlock *rb)
1633 return rb->flags & RAM_SHARED;
1636 /* Note: Only set at the start of postcopy */
1637 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1639 return rb->flags & RAM_UF_ZEROPAGE;
1642 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1644 rb->flags |= RAM_UF_ZEROPAGE;
1647 bool qemu_ram_is_migratable(RAMBlock *rb)
1649 return rb->flags & RAM_MIGRATABLE;
1652 void qemu_ram_set_migratable(RAMBlock *rb)
1654 rb->flags |= RAM_MIGRATABLE;
1657 void qemu_ram_unset_migratable(RAMBlock *rb)
1659 rb->flags &= ~RAM_MIGRATABLE;
1662 /* Called with iothread lock held. */
1663 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1665 RAMBlock *block;
1667 assert(new_block);
1668 assert(!new_block->idstr[0]);
1670 if (dev) {
1671 char *id = qdev_get_dev_path(dev);
1672 if (id) {
1673 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1674 g_free(id);
1677 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1679 RCU_READ_LOCK_GUARD();
1680 RAMBLOCK_FOREACH(block) {
1681 if (block != new_block &&
1682 !strcmp(block->idstr, new_block->idstr)) {
1683 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1684 new_block->idstr);
1685 abort();
1690 /* Called with iothread lock held. */
1691 void qemu_ram_unset_idstr(RAMBlock *block)
1693 /* FIXME: arch_init.c assumes that this is not called throughout
1694 * migration. Ignore the problem since hot-unplug during migration
1695 * does not work anyway.
1697 if (block) {
1698 memset(block->idstr, 0, sizeof(block->idstr));
1702 size_t qemu_ram_pagesize(RAMBlock *rb)
1704 return rb->page_size;
1707 /* Returns the largest size of page in use */
1708 size_t qemu_ram_pagesize_largest(void)
1710 RAMBlock *block;
1711 size_t largest = 0;
1713 RAMBLOCK_FOREACH(block) {
1714 largest = MAX(largest, qemu_ram_pagesize(block));
1717 return largest;
1720 static int memory_try_enable_merging(void *addr, size_t len)
1722 if (!machine_mem_merge(current_machine)) {
1723 /* disabled by the user */
1724 return 0;
1727 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1730 /* Only legal before guest might have detected the memory size: e.g. on
1731 * incoming migration, or right after reset.
1733 * As memory core doesn't know how is memory accessed, it is up to
1734 * resize callback to update device state and/or add assertions to detect
1735 * misuse, if necessary.
1737 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1739 const ram_addr_t unaligned_size = newsize;
1741 assert(block);
1743 newsize = HOST_PAGE_ALIGN(newsize);
1745 if (block->used_length == newsize) {
1747 * We don't have to resize the ram block (which only knows aligned
1748 * sizes), however, we have to notify if the unaligned size changed.
1750 if (unaligned_size != memory_region_size(block->mr)) {
1751 memory_region_set_size(block->mr, unaligned_size);
1752 if (block->resized) {
1753 block->resized(block->idstr, unaligned_size, block->host);
1756 return 0;
1759 if (!(block->flags & RAM_RESIZEABLE)) {
1760 error_setg_errno(errp, EINVAL,
1761 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1762 " != 0x" RAM_ADDR_FMT, block->idstr,
1763 newsize, block->used_length);
1764 return -EINVAL;
1767 if (block->max_length < newsize) {
1768 error_setg_errno(errp, EINVAL,
1769 "Size too large: %s: 0x" RAM_ADDR_FMT
1770 " > 0x" RAM_ADDR_FMT, block->idstr,
1771 newsize, block->max_length);
1772 return -EINVAL;
1775 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1776 block->used_length = newsize;
1777 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1778 DIRTY_CLIENTS_ALL);
1779 memory_region_set_size(block->mr, unaligned_size);
1780 if (block->resized) {
1781 block->resized(block->idstr, unaligned_size, block->host);
1783 return 0;
1787 * Trigger sync on the given ram block for range [start, start + length]
1788 * with the backing store if one is available.
1789 * Otherwise no-op.
1790 * @Note: this is supposed to be a synchronous op.
1792 void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
1794 /* The requested range should fit in within the block range */
1795 g_assert((start + length) <= block->used_length);
1797 #ifdef CONFIG_LIBPMEM
1798 /* The lack of support for pmem should not block the sync */
1799 if (ramblock_is_pmem(block)) {
1800 void *addr = ramblock_ptr(block, start);
1801 pmem_persist(addr, length);
1802 return;
1804 #endif
1805 if (block->fd >= 0) {
1807 * Case there is no support for PMEM or the memory has not been
1808 * specified as persistent (or is not one) - use the msync.
1809 * Less optimal but still achieves the same goal
1811 void *addr = ramblock_ptr(block, start);
1812 if (qemu_msync(addr, length, block->fd)) {
1813 warn_report("%s: failed to sync memory range: start: "
1814 RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
1815 __func__, start, length);
1820 /* Called with ram_list.mutex held */
1821 static void dirty_memory_extend(ram_addr_t old_ram_size,
1822 ram_addr_t new_ram_size)
1824 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1825 DIRTY_MEMORY_BLOCK_SIZE);
1826 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1827 DIRTY_MEMORY_BLOCK_SIZE);
1828 int i;
1830 /* Only need to extend if block count increased */
1831 if (new_num_blocks <= old_num_blocks) {
1832 return;
1835 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1836 DirtyMemoryBlocks *old_blocks;
1837 DirtyMemoryBlocks *new_blocks;
1838 int j;
1840 old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
1841 new_blocks = g_malloc(sizeof(*new_blocks) +
1842 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1844 if (old_num_blocks) {
1845 memcpy(new_blocks->blocks, old_blocks->blocks,
1846 old_num_blocks * sizeof(old_blocks->blocks[0]));
1849 for (j = old_num_blocks; j < new_num_blocks; j++) {
1850 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1853 qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1855 if (old_blocks) {
1856 g_free_rcu(old_blocks, rcu);
1861 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
1863 RAMBlock *block;
1864 RAMBlock *last_block = NULL;
1865 ram_addr_t old_ram_size, new_ram_size;
1866 Error *err = NULL;
1868 old_ram_size = last_ram_page();
1870 qemu_mutex_lock_ramlist();
1871 new_block->offset = find_ram_offset(new_block->max_length);
1873 if (!new_block->host) {
1874 if (xen_enabled()) {
1875 xen_ram_alloc(new_block->offset, new_block->max_length,
1876 new_block->mr, &err);
1877 if (err) {
1878 error_propagate(errp, err);
1879 qemu_mutex_unlock_ramlist();
1880 return;
1882 } else {
1883 new_block->host = phys_mem_alloc(new_block->max_length,
1884 &new_block->mr->align, shared);
1885 if (!new_block->host) {
1886 error_setg_errno(errp, errno,
1887 "cannot set up guest memory '%s'",
1888 memory_region_name(new_block->mr));
1889 qemu_mutex_unlock_ramlist();
1890 return;
1892 memory_try_enable_merging(new_block->host, new_block->max_length);
1896 new_ram_size = MAX(old_ram_size,
1897 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1898 if (new_ram_size > old_ram_size) {
1899 dirty_memory_extend(old_ram_size, new_ram_size);
1901 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1902 * QLIST (which has an RCU-friendly variant) does not have insertion at
1903 * tail, so save the last element in last_block.
1905 RAMBLOCK_FOREACH(block) {
1906 last_block = block;
1907 if (block->max_length < new_block->max_length) {
1908 break;
1911 if (block) {
1912 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1913 } else if (last_block) {
1914 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
1915 } else { /* list is empty */
1916 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1918 ram_list.mru_block = NULL;
1920 /* Write list before version */
1921 smp_wmb();
1922 ram_list.version++;
1923 qemu_mutex_unlock_ramlist();
1925 cpu_physical_memory_set_dirty_range(new_block->offset,
1926 new_block->used_length,
1927 DIRTY_CLIENTS_ALL);
1929 if (new_block->host) {
1930 qemu_ram_setup_dump(new_block->host, new_block->max_length);
1931 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
1933 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
1934 * Configure it unless the machine is a qtest server, in which case
1935 * KVM is not used and it may be forked (eg for fuzzing purposes).
1937 if (!qtest_enabled()) {
1938 qemu_madvise(new_block->host, new_block->max_length,
1939 QEMU_MADV_DONTFORK);
1941 ram_block_notify_add(new_block->host, new_block->max_length);
1945 #ifdef CONFIG_POSIX
1946 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
1947 uint32_t ram_flags, int fd, bool readonly,
1948 Error **errp)
1950 RAMBlock *new_block;
1951 Error *local_err = NULL;
1952 int64_t file_size, file_align;
1954 /* Just support these ram flags by now. */
1955 assert((ram_flags & ~(RAM_SHARED | RAM_PMEM)) == 0);
1957 if (xen_enabled()) {
1958 error_setg(errp, "-mem-path not supported with Xen");
1959 return NULL;
1962 if (kvm_enabled() && !kvm_has_sync_mmu()) {
1963 error_setg(errp,
1964 "host lacks kvm mmu notifiers, -mem-path unsupported");
1965 return NULL;
1968 if (phys_mem_alloc != qemu_anon_ram_alloc) {
1970 * file_ram_alloc() needs to allocate just like
1971 * phys_mem_alloc, but we haven't bothered to provide
1972 * a hook there.
1974 error_setg(errp,
1975 "-mem-path not supported with this accelerator");
1976 return NULL;
1979 size = HOST_PAGE_ALIGN(size);
1980 file_size = get_file_size(fd);
1981 if (file_size > 0 && file_size < size) {
1982 error_setg(errp, "backing store size 0x%" PRIx64
1983 " does not match 'size' option 0x" RAM_ADDR_FMT,
1984 file_size, size);
1985 return NULL;
1988 file_align = get_file_align(fd);
1989 if (file_align > 0 && mr && file_align > mr->align) {
1990 error_setg(errp, "backing store align 0x%" PRIx64
1991 " is larger than 'align' option 0x%" PRIx64,
1992 file_align, mr->align);
1993 return NULL;
1996 new_block = g_malloc0(sizeof(*new_block));
1997 new_block->mr = mr;
1998 new_block->used_length = size;
1999 new_block->max_length = size;
2000 new_block->flags = ram_flags;
2001 new_block->host = file_ram_alloc(new_block, size, fd, readonly,
2002 !file_size, errp);
2003 if (!new_block->host) {
2004 g_free(new_block);
2005 return NULL;
2008 ram_block_add(new_block, &local_err, ram_flags & RAM_SHARED);
2009 if (local_err) {
2010 g_free(new_block);
2011 error_propagate(errp, local_err);
2012 return NULL;
2014 return new_block;
2019 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2020 uint32_t ram_flags, const char *mem_path,
2021 bool readonly, Error **errp)
2023 int fd;
2024 bool created;
2025 RAMBlock *block;
2027 fd = file_ram_open(mem_path, memory_region_name(mr), readonly, &created,
2028 errp);
2029 if (fd < 0) {
2030 return NULL;
2033 block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, readonly, errp);
2034 if (!block) {
2035 if (created) {
2036 unlink(mem_path);
2038 close(fd);
2039 return NULL;
2042 return block;
2044 #endif
2046 static
2047 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2048 void (*resized)(const char*,
2049 uint64_t length,
2050 void *host),
2051 void *host, bool resizeable, bool share,
2052 MemoryRegion *mr, Error **errp)
2054 RAMBlock *new_block;
2055 Error *local_err = NULL;
2057 size = HOST_PAGE_ALIGN(size);
2058 max_size = HOST_PAGE_ALIGN(max_size);
2059 new_block = g_malloc0(sizeof(*new_block));
2060 new_block->mr = mr;
2061 new_block->resized = resized;
2062 new_block->used_length = size;
2063 new_block->max_length = max_size;
2064 assert(max_size >= size);
2065 new_block->fd = -1;
2066 new_block->page_size = qemu_real_host_page_size;
2067 new_block->host = host;
2068 if (host) {
2069 new_block->flags |= RAM_PREALLOC;
2071 if (resizeable) {
2072 new_block->flags |= RAM_RESIZEABLE;
2074 ram_block_add(new_block, &local_err, share);
2075 if (local_err) {
2076 g_free(new_block);
2077 error_propagate(errp, local_err);
2078 return NULL;
2080 return new_block;
2083 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2084 MemoryRegion *mr, Error **errp)
2086 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2087 false, mr, errp);
2090 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2091 MemoryRegion *mr, Error **errp)
2093 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2094 share, mr, errp);
2097 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2098 void (*resized)(const char*,
2099 uint64_t length,
2100 void *host),
2101 MemoryRegion *mr, Error **errp)
2103 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2104 false, mr, errp);
2107 static void reclaim_ramblock(RAMBlock *block)
2109 if (block->flags & RAM_PREALLOC) {
2111 } else if (xen_enabled()) {
2112 xen_invalidate_map_cache_entry(block->host);
2113 #ifndef _WIN32
2114 } else if (block->fd >= 0) {
2115 qemu_ram_munmap(block->fd, block->host, block->max_length);
2116 close(block->fd);
2117 #endif
2118 } else {
2119 qemu_anon_ram_free(block->host, block->max_length);
2121 g_free(block);
2124 void qemu_ram_free(RAMBlock *block)
2126 if (!block) {
2127 return;
2130 if (block->host) {
2131 ram_block_notify_remove(block->host, block->max_length);
2134 qemu_mutex_lock_ramlist();
2135 QLIST_REMOVE_RCU(block, next);
2136 ram_list.mru_block = NULL;
2137 /* Write list before version */
2138 smp_wmb();
2139 ram_list.version++;
2140 call_rcu(block, reclaim_ramblock, rcu);
2141 qemu_mutex_unlock_ramlist();
2144 #ifndef _WIN32
2145 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2147 RAMBlock *block;
2148 ram_addr_t offset;
2149 int flags;
2150 void *area, *vaddr;
2152 RAMBLOCK_FOREACH(block) {
2153 offset = addr - block->offset;
2154 if (offset < block->max_length) {
2155 vaddr = ramblock_ptr(block, offset);
2156 if (block->flags & RAM_PREALLOC) {
2158 } else if (xen_enabled()) {
2159 abort();
2160 } else {
2161 flags = MAP_FIXED;
2162 if (block->fd >= 0) {
2163 flags |= (block->flags & RAM_SHARED ?
2164 MAP_SHARED : MAP_PRIVATE);
2165 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2166 flags, block->fd, offset);
2167 } else {
2169 * Remap needs to match alloc. Accelerators that
2170 * set phys_mem_alloc never remap. If they did,
2171 * we'd need a remap hook here.
2173 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2175 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2176 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2177 flags, -1, 0);
2179 if (area != vaddr) {
2180 error_report("Could not remap addr: "
2181 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2182 length, addr);
2183 exit(1);
2185 memory_try_enable_merging(vaddr, length);
2186 qemu_ram_setup_dump(vaddr, length);
2191 #endif /* !_WIN32 */
2193 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2194 * This should not be used for general purpose DMA. Use address_space_map
2195 * or address_space_rw instead. For local memory (e.g. video ram) that the
2196 * device owns, use memory_region_get_ram_ptr.
2198 * Called within RCU critical section.
2200 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2202 RAMBlock *block = ram_block;
2204 if (block == NULL) {
2205 block = qemu_get_ram_block(addr);
2206 addr -= block->offset;
2209 if (xen_enabled() && block->host == NULL) {
2210 /* We need to check if the requested address is in the RAM
2211 * because we don't want to map the entire memory in QEMU.
2212 * In that case just map until the end of the page.
2214 if (block->offset == 0) {
2215 return xen_map_cache(addr, 0, 0, false);
2218 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2220 return ramblock_ptr(block, addr);
2223 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2224 * but takes a size argument.
2226 * Called within RCU critical section.
2228 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2229 hwaddr *size, bool lock)
2231 RAMBlock *block = ram_block;
2232 if (*size == 0) {
2233 return NULL;
2236 if (block == NULL) {
2237 block = qemu_get_ram_block(addr);
2238 addr -= block->offset;
2240 *size = MIN(*size, block->max_length - addr);
2242 if (xen_enabled() && block->host == NULL) {
2243 /* We need to check if the requested address is in the RAM
2244 * because we don't want to map the entire memory in QEMU.
2245 * In that case just map the requested area.
2247 if (block->offset == 0) {
2248 return xen_map_cache(addr, *size, lock, lock);
2251 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2254 return ramblock_ptr(block, addr);
2257 /* Return the offset of a hostpointer within a ramblock */
2258 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2260 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2261 assert((uintptr_t)host >= (uintptr_t)rb->host);
2262 assert(res < rb->max_length);
2264 return res;
2268 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2269 * in that RAMBlock.
2271 * ptr: Host pointer to look up
2272 * round_offset: If true round the result offset down to a page boundary
2273 * *ram_addr: set to result ram_addr
2274 * *offset: set to result offset within the RAMBlock
2276 * Returns: RAMBlock (or NULL if not found)
2278 * By the time this function returns, the returned pointer is not protected
2279 * by RCU anymore. If the caller is not within an RCU critical section and
2280 * does not hold the iothread lock, it must have other means of protecting the
2281 * pointer, such as a reference to the region that includes the incoming
2282 * ram_addr_t.
2284 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2285 ram_addr_t *offset)
2287 RAMBlock *block;
2288 uint8_t *host = ptr;
2290 if (xen_enabled()) {
2291 ram_addr_t ram_addr;
2292 RCU_READ_LOCK_GUARD();
2293 ram_addr = xen_ram_addr_from_mapcache(ptr);
2294 block = qemu_get_ram_block(ram_addr);
2295 if (block) {
2296 *offset = ram_addr - block->offset;
2298 return block;
2301 RCU_READ_LOCK_GUARD();
2302 block = qatomic_rcu_read(&ram_list.mru_block);
2303 if (block && block->host && host - block->host < block->max_length) {
2304 goto found;
2307 RAMBLOCK_FOREACH(block) {
2308 /* This case append when the block is not mapped. */
2309 if (block->host == NULL) {
2310 continue;
2312 if (host - block->host < block->max_length) {
2313 goto found;
2317 return NULL;
2319 found:
2320 *offset = (host - block->host);
2321 if (round_offset) {
2322 *offset &= TARGET_PAGE_MASK;
2324 return block;
2328 * Finds the named RAMBlock
2330 * name: The name of RAMBlock to find
2332 * Returns: RAMBlock (or NULL if not found)
2334 RAMBlock *qemu_ram_block_by_name(const char *name)
2336 RAMBlock *block;
2338 RAMBLOCK_FOREACH(block) {
2339 if (!strcmp(name, block->idstr)) {
2340 return block;
2344 return NULL;
2347 /* Some of the softmmu routines need to translate from a host pointer
2348 (typically a TLB entry) back to a ram offset. */
2349 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2351 RAMBlock *block;
2352 ram_addr_t offset;
2354 block = qemu_ram_block_from_host(ptr, false, &offset);
2355 if (!block) {
2356 return RAM_ADDR_INVALID;
2359 return block->offset + offset;
2362 /* Generate a debug exception if a watchpoint has been hit. */
2363 void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
2364 MemTxAttrs attrs, int flags, uintptr_t ra)
2366 CPUClass *cc = CPU_GET_CLASS(cpu);
2367 CPUWatchpoint *wp;
2369 assert(tcg_enabled());
2370 if (cpu->watchpoint_hit) {
2372 * We re-entered the check after replacing the TB.
2373 * Now raise the debug interrupt so that it will
2374 * trigger after the current instruction.
2376 qemu_mutex_lock_iothread();
2377 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2378 qemu_mutex_unlock_iothread();
2379 return;
2382 addr = cc->adjust_watchpoint_address(cpu, addr, len);
2383 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2384 if (watchpoint_address_matches(wp, addr, len)
2385 && (wp->flags & flags)) {
2386 if (replay_running_debug()) {
2388 * Don't process the watchpoints when we are
2389 * in a reverse debugging operation.
2391 replay_breakpoint();
2392 return;
2394 if (flags == BP_MEM_READ) {
2395 wp->flags |= BP_WATCHPOINT_HIT_READ;
2396 } else {
2397 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2399 wp->hitaddr = MAX(addr, wp->vaddr);
2400 wp->hitattrs = attrs;
2401 if (!cpu->watchpoint_hit) {
2402 if (wp->flags & BP_CPU &&
2403 !cc->debug_check_watchpoint(cpu, wp)) {
2404 wp->flags &= ~BP_WATCHPOINT_HIT;
2405 continue;
2407 cpu->watchpoint_hit = wp;
2409 mmap_lock();
2410 tb_check_watchpoint(cpu, ra);
2411 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2412 cpu->exception_index = EXCP_DEBUG;
2413 mmap_unlock();
2414 cpu_loop_exit_restore(cpu, ra);
2415 } else {
2416 /* Force execution of one insn next time. */
2417 cpu->cflags_next_tb = 1 | curr_cflags();
2418 mmap_unlock();
2419 if (ra) {
2420 cpu_restore_state(cpu, ra, true);
2422 cpu_loop_exit_noexc(cpu);
2425 } else {
2426 wp->flags &= ~BP_WATCHPOINT_HIT;
2431 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2432 MemTxAttrs attrs, void *buf, hwaddr len);
2433 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2434 const void *buf, hwaddr len);
2435 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2436 bool is_write, MemTxAttrs attrs);
2438 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2439 unsigned len, MemTxAttrs attrs)
2441 subpage_t *subpage = opaque;
2442 uint8_t buf[8];
2443 MemTxResult res;
2445 #if defined(DEBUG_SUBPAGE)
2446 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2447 subpage, len, addr);
2448 #endif
2449 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2450 if (res) {
2451 return res;
2453 *data = ldn_p(buf, len);
2454 return MEMTX_OK;
2457 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2458 uint64_t value, unsigned len, MemTxAttrs attrs)
2460 subpage_t *subpage = opaque;
2461 uint8_t buf[8];
2463 #if defined(DEBUG_SUBPAGE)
2464 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2465 " value %"PRIx64"\n",
2466 __func__, subpage, len, addr, value);
2467 #endif
2468 stn_p(buf, len, value);
2469 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2472 static bool subpage_accepts(void *opaque, hwaddr addr,
2473 unsigned len, bool is_write,
2474 MemTxAttrs attrs)
2476 subpage_t *subpage = opaque;
2477 #if defined(DEBUG_SUBPAGE)
2478 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2479 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2480 #endif
2482 return flatview_access_valid(subpage->fv, addr + subpage->base,
2483 len, is_write, attrs);
2486 static const MemoryRegionOps subpage_ops = {
2487 .read_with_attrs = subpage_read,
2488 .write_with_attrs = subpage_write,
2489 .impl.min_access_size = 1,
2490 .impl.max_access_size = 8,
2491 .valid.min_access_size = 1,
2492 .valid.max_access_size = 8,
2493 .valid.accepts = subpage_accepts,
2494 .endianness = DEVICE_NATIVE_ENDIAN,
2497 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2498 uint16_t section)
2500 int idx, eidx;
2502 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2503 return -1;
2504 idx = SUBPAGE_IDX(start);
2505 eidx = SUBPAGE_IDX(end);
2506 #if defined(DEBUG_SUBPAGE)
2507 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2508 __func__, mmio, start, end, idx, eidx, section);
2509 #endif
2510 for (; idx <= eidx; idx++) {
2511 mmio->sub_section[idx] = section;
2514 return 0;
2517 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2519 subpage_t *mmio;
2521 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2522 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2523 mmio->fv = fv;
2524 mmio->base = base;
2525 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2526 NULL, TARGET_PAGE_SIZE);
2527 mmio->iomem.subpage = true;
2528 #if defined(DEBUG_SUBPAGE)
2529 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2530 mmio, base, TARGET_PAGE_SIZE);
2531 #endif
2533 return mmio;
2536 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2538 assert(fv);
2539 MemoryRegionSection section = {
2540 .fv = fv,
2541 .mr = mr,
2542 .offset_within_address_space = 0,
2543 .offset_within_region = 0,
2544 .size = int128_2_64(),
2547 return phys_section_add(map, &section);
2550 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2551 hwaddr index, MemTxAttrs attrs)
2553 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2554 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2555 AddressSpaceDispatch *d = qatomic_rcu_read(&cpuas->memory_dispatch);
2556 MemoryRegionSection *sections = d->map.sections;
2558 return &sections[index & ~TARGET_PAGE_MASK];
2561 static void io_mem_init(void)
2563 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2564 NULL, UINT64_MAX);
2567 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2569 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2570 uint16_t n;
2572 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2573 assert(n == PHYS_SECTION_UNASSIGNED);
2575 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2577 return d;
2580 void address_space_dispatch_free(AddressSpaceDispatch *d)
2582 phys_sections_free(&d->map);
2583 g_free(d);
2586 static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2590 static void tcg_log_global_after_sync(MemoryListener *listener)
2592 CPUAddressSpace *cpuas;
2594 /* Wait for the CPU to end the current TB. This avoids the following
2595 * incorrect race:
2597 * vCPU migration
2598 * ---------------------- -------------------------
2599 * TLB check -> slow path
2600 * notdirty_mem_write
2601 * write to RAM
2602 * mark dirty
2603 * clear dirty flag
2604 * TLB check -> fast path
2605 * read memory
2606 * write to RAM
2608 * by pushing the migration thread's memory read after the vCPU thread has
2609 * written the memory.
2611 if (replay_mode == REPLAY_MODE_NONE) {
2613 * VGA can make calls to this function while updating the screen.
2614 * In record/replay mode this causes a deadlock, because
2615 * run_on_cpu waits for rr mutex. Therefore no races are possible
2616 * in this case and no need for making run_on_cpu when
2617 * record/replay is not enabled.
2619 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2620 run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2624 static void tcg_commit(MemoryListener *listener)
2626 CPUAddressSpace *cpuas;
2627 AddressSpaceDispatch *d;
2629 assert(tcg_enabled());
2630 /* since each CPU stores ram addresses in its TLB cache, we must
2631 reset the modified entries */
2632 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2633 cpu_reloading_memory_map();
2634 /* The CPU and TLB are protected by the iothread lock.
2635 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2636 * may have split the RCU critical section.
2638 d = address_space_to_dispatch(cpuas->as);
2639 qatomic_rcu_set(&cpuas->memory_dispatch, d);
2640 tlb_flush(cpuas->cpu);
2643 static void memory_map_init(void)
2645 system_memory = g_malloc(sizeof(*system_memory));
2647 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2648 address_space_init(&address_space_memory, system_memory, "memory");
2650 system_io = g_malloc(sizeof(*system_io));
2651 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2652 65536);
2653 address_space_init(&address_space_io, system_io, "I/O");
2656 MemoryRegion *get_system_memory(void)
2658 return system_memory;
2661 MemoryRegion *get_system_io(void)
2663 return system_io;
2666 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2667 hwaddr length)
2669 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2670 addr += memory_region_get_ram_addr(mr);
2672 /* No early return if dirty_log_mask is or becomes 0, because
2673 * cpu_physical_memory_set_dirty_range will still call
2674 * xen_modified_memory.
2676 if (dirty_log_mask) {
2677 dirty_log_mask =
2678 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2680 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2681 assert(tcg_enabled());
2682 tb_invalidate_phys_range(addr, addr + length);
2683 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2685 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2688 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
2691 * In principle this function would work on other memory region types too,
2692 * but the ROM device use case is the only one where this operation is
2693 * necessary. Other memory regions should use the
2694 * address_space_read/write() APIs.
2696 assert(memory_region_is_romd(mr));
2698 invalidate_and_set_dirty(mr, addr, size);
2701 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2703 unsigned access_size_max = mr->ops->valid.max_access_size;
2705 /* Regions are assumed to support 1-4 byte accesses unless
2706 otherwise specified. */
2707 if (access_size_max == 0) {
2708 access_size_max = 4;
2711 /* Bound the maximum access by the alignment of the address. */
2712 if (!mr->ops->impl.unaligned) {
2713 unsigned align_size_max = addr & -addr;
2714 if (align_size_max != 0 && align_size_max < access_size_max) {
2715 access_size_max = align_size_max;
2719 /* Don't attempt accesses larger than the maximum. */
2720 if (l > access_size_max) {
2721 l = access_size_max;
2723 l = pow2floor(l);
2725 return l;
2728 static bool prepare_mmio_access(MemoryRegion *mr)
2730 bool release_lock = false;
2732 if (!qemu_mutex_iothread_locked()) {
2733 qemu_mutex_lock_iothread();
2734 release_lock = true;
2736 if (mr->flush_coalesced_mmio) {
2737 qemu_flush_coalesced_mmio_buffer();
2740 return release_lock;
2743 /* Called within RCU critical section. */
2744 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
2745 MemTxAttrs attrs,
2746 const void *ptr,
2747 hwaddr len, hwaddr addr1,
2748 hwaddr l, MemoryRegion *mr)
2750 uint8_t *ram_ptr;
2751 uint64_t val;
2752 MemTxResult result = MEMTX_OK;
2753 bool release_lock = false;
2754 const uint8_t *buf = ptr;
2756 for (;;) {
2757 if (!memory_access_is_direct(mr, true)) {
2758 release_lock |= prepare_mmio_access(mr);
2759 l = memory_access_size(mr, l, addr1);
2760 /* XXX: could force current_cpu to NULL to avoid
2761 potential bugs */
2762 val = ldn_he_p(buf, l);
2763 result |= memory_region_dispatch_write(mr, addr1, val,
2764 size_memop(l), attrs);
2765 } else {
2766 /* RAM case */
2767 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2768 memcpy(ram_ptr, buf, l);
2769 invalidate_and_set_dirty(mr, addr1, l);
2772 if (release_lock) {
2773 qemu_mutex_unlock_iothread();
2774 release_lock = false;
2777 len -= l;
2778 buf += l;
2779 addr += l;
2781 if (!len) {
2782 break;
2785 l = len;
2786 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2789 return result;
2792 /* Called from RCU critical section. */
2793 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2794 const void *buf, hwaddr len)
2796 hwaddr l;
2797 hwaddr addr1;
2798 MemoryRegion *mr;
2799 MemTxResult result = MEMTX_OK;
2801 l = len;
2802 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2803 result = flatview_write_continue(fv, addr, attrs, buf, len,
2804 addr1, l, mr);
2806 return result;
2809 /* Called within RCU critical section. */
2810 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
2811 MemTxAttrs attrs, void *ptr,
2812 hwaddr len, hwaddr addr1, hwaddr l,
2813 MemoryRegion *mr)
2815 uint8_t *ram_ptr;
2816 uint64_t val;
2817 MemTxResult result = MEMTX_OK;
2818 bool release_lock = false;
2819 uint8_t *buf = ptr;
2821 for (;;) {
2822 if (!memory_access_is_direct(mr, false)) {
2823 /* I/O case */
2824 release_lock |= prepare_mmio_access(mr);
2825 l = memory_access_size(mr, l, addr1);
2826 result |= memory_region_dispatch_read(mr, addr1, &val,
2827 size_memop(l), attrs);
2828 stn_he_p(buf, l, val);
2829 } else {
2830 /* RAM case */
2831 fuzz_dma_read_cb(addr, len, mr, false);
2832 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2833 memcpy(buf, ram_ptr, l);
2836 if (release_lock) {
2837 qemu_mutex_unlock_iothread();
2838 release_lock = false;
2841 len -= l;
2842 buf += l;
2843 addr += l;
2845 if (!len) {
2846 break;
2849 l = len;
2850 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2853 return result;
2856 /* Called from RCU critical section. */
2857 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2858 MemTxAttrs attrs, void *buf, hwaddr len)
2860 hwaddr l;
2861 hwaddr addr1;
2862 MemoryRegion *mr;
2864 l = len;
2865 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2866 return flatview_read_continue(fv, addr, attrs, buf, len,
2867 addr1, l, mr);
2870 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2871 MemTxAttrs attrs, void *buf, hwaddr len)
2873 MemTxResult result = MEMTX_OK;
2874 FlatView *fv;
2876 if (len > 0) {
2877 RCU_READ_LOCK_GUARD();
2878 fv = address_space_to_flatview(as);
2879 result = flatview_read(fv, addr, attrs, buf, len);
2882 return result;
2885 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2886 MemTxAttrs attrs,
2887 const void *buf, hwaddr len)
2889 MemTxResult result = MEMTX_OK;
2890 FlatView *fv;
2892 if (len > 0) {
2893 RCU_READ_LOCK_GUARD();
2894 fv = address_space_to_flatview(as);
2895 result = flatview_write(fv, addr, attrs, buf, len);
2898 return result;
2901 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2902 void *buf, hwaddr len, bool is_write)
2904 if (is_write) {
2905 return address_space_write(as, addr, attrs, buf, len);
2906 } else {
2907 return address_space_read_full(as, addr, attrs, buf, len);
2911 void cpu_physical_memory_rw(hwaddr addr, void *buf,
2912 hwaddr len, bool is_write)
2914 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
2915 buf, len, is_write);
2918 enum write_rom_type {
2919 WRITE_DATA,
2920 FLUSH_CACHE,
2923 static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
2924 hwaddr addr,
2925 MemTxAttrs attrs,
2926 const void *ptr,
2927 hwaddr len,
2928 enum write_rom_type type)
2930 hwaddr l;
2931 uint8_t *ram_ptr;
2932 hwaddr addr1;
2933 MemoryRegion *mr;
2934 const uint8_t *buf = ptr;
2936 RCU_READ_LOCK_GUARD();
2937 while (len > 0) {
2938 l = len;
2939 mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
2941 if (!(memory_region_is_ram(mr) ||
2942 memory_region_is_romd(mr))) {
2943 l = memory_access_size(mr, l, addr1);
2944 } else {
2945 /* ROM/RAM case */
2946 ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2947 switch (type) {
2948 case WRITE_DATA:
2949 memcpy(ram_ptr, buf, l);
2950 invalidate_and_set_dirty(mr, addr1, l);
2951 break;
2952 case FLUSH_CACHE:
2953 flush_idcache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr, l);
2954 break;
2957 len -= l;
2958 buf += l;
2959 addr += l;
2961 return MEMTX_OK;
2964 /* used for ROM loading : can write in RAM and ROM */
2965 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
2966 MemTxAttrs attrs,
2967 const void *buf, hwaddr len)
2969 return address_space_write_rom_internal(as, addr, attrs,
2970 buf, len, WRITE_DATA);
2973 void cpu_flush_icache_range(hwaddr start, hwaddr len)
2976 * This function should do the same thing as an icache flush that was
2977 * triggered from within the guest. For TCG we are always cache coherent,
2978 * so there is no need to flush anything. For KVM / Xen we need to flush
2979 * the host's instruction cache at least.
2981 if (tcg_enabled()) {
2982 return;
2985 address_space_write_rom_internal(&address_space_memory,
2986 start, MEMTXATTRS_UNSPECIFIED,
2987 NULL, len, FLUSH_CACHE);
2990 typedef struct {
2991 MemoryRegion *mr;
2992 void *buffer;
2993 hwaddr addr;
2994 hwaddr len;
2995 bool in_use;
2996 } BounceBuffer;
2998 static BounceBuffer bounce;
3000 typedef struct MapClient {
3001 QEMUBH *bh;
3002 QLIST_ENTRY(MapClient) link;
3003 } MapClient;
3005 QemuMutex map_client_list_lock;
3006 static QLIST_HEAD(, MapClient) map_client_list
3007 = QLIST_HEAD_INITIALIZER(map_client_list);
3009 static void cpu_unregister_map_client_do(MapClient *client)
3011 QLIST_REMOVE(client, link);
3012 g_free(client);
3015 static void cpu_notify_map_clients_locked(void)
3017 MapClient *client;
3019 while (!QLIST_EMPTY(&map_client_list)) {
3020 client = QLIST_FIRST(&map_client_list);
3021 qemu_bh_schedule(client->bh);
3022 cpu_unregister_map_client_do(client);
3026 void cpu_register_map_client(QEMUBH *bh)
3028 MapClient *client = g_malloc(sizeof(*client));
3030 qemu_mutex_lock(&map_client_list_lock);
3031 client->bh = bh;
3032 QLIST_INSERT_HEAD(&map_client_list, client, link);
3033 if (!qatomic_read(&bounce.in_use)) {
3034 cpu_notify_map_clients_locked();
3036 qemu_mutex_unlock(&map_client_list_lock);
3039 void cpu_exec_init_all(void)
3041 qemu_mutex_init(&ram_list.mutex);
3042 /* The data structures we set up here depend on knowing the page size,
3043 * so no more changes can be made after this point.
3044 * In an ideal world, nothing we did before we had finished the
3045 * machine setup would care about the target page size, and we could
3046 * do this much later, rather than requiring board models to state
3047 * up front what their requirements are.
3049 finalize_target_page_bits();
3050 io_mem_init();
3051 memory_map_init();
3052 qemu_mutex_init(&map_client_list_lock);
3055 void cpu_unregister_map_client(QEMUBH *bh)
3057 MapClient *client;
3059 qemu_mutex_lock(&map_client_list_lock);
3060 QLIST_FOREACH(client, &map_client_list, link) {
3061 if (client->bh == bh) {
3062 cpu_unregister_map_client_do(client);
3063 break;
3066 qemu_mutex_unlock(&map_client_list_lock);
3069 static void cpu_notify_map_clients(void)
3071 qemu_mutex_lock(&map_client_list_lock);
3072 cpu_notify_map_clients_locked();
3073 qemu_mutex_unlock(&map_client_list_lock);
3076 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
3077 bool is_write, MemTxAttrs attrs)
3079 MemoryRegion *mr;
3080 hwaddr l, xlat;
3082 while (len > 0) {
3083 l = len;
3084 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3085 if (!memory_access_is_direct(mr, is_write)) {
3086 l = memory_access_size(mr, l, addr);
3087 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3088 return false;
3092 len -= l;
3093 addr += l;
3095 return true;
3098 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3099 hwaddr len, bool is_write,
3100 MemTxAttrs attrs)
3102 FlatView *fv;
3103 bool result;
3105 RCU_READ_LOCK_GUARD();
3106 fv = address_space_to_flatview(as);
3107 result = flatview_access_valid(fv, addr, len, is_write, attrs);
3108 return result;
3111 static hwaddr
3112 flatview_extend_translation(FlatView *fv, hwaddr addr,
3113 hwaddr target_len,
3114 MemoryRegion *mr, hwaddr base, hwaddr len,
3115 bool is_write, MemTxAttrs attrs)
3117 hwaddr done = 0;
3118 hwaddr xlat;
3119 MemoryRegion *this_mr;
3121 for (;;) {
3122 target_len -= len;
3123 addr += len;
3124 done += len;
3125 if (target_len == 0) {
3126 return done;
3129 len = target_len;
3130 this_mr = flatview_translate(fv, addr, &xlat,
3131 &len, is_write, attrs);
3132 if (this_mr != mr || xlat != base + done) {
3133 return done;
3138 /* Map a physical memory region into a host virtual address.
3139 * May map a subset of the requested range, given by and returned in *plen.
3140 * May return NULL if resources needed to perform the mapping are exhausted.
3141 * Use only for reads OR writes - not for read-modify-write operations.
3142 * Use cpu_register_map_client() to know when retrying the map operation is
3143 * likely to succeed.
3145 void *address_space_map(AddressSpace *as,
3146 hwaddr addr,
3147 hwaddr *plen,
3148 bool is_write,
3149 MemTxAttrs attrs)
3151 hwaddr len = *plen;
3152 hwaddr l, xlat;
3153 MemoryRegion *mr;
3154 void *ptr;
3155 FlatView *fv;
3157 if (len == 0) {
3158 return NULL;
3161 l = len;
3162 RCU_READ_LOCK_GUARD();
3163 fv = address_space_to_flatview(as);
3164 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3166 if (!memory_access_is_direct(mr, is_write)) {
3167 if (qatomic_xchg(&bounce.in_use, true)) {
3168 *plen = 0;
3169 return NULL;
3171 /* Avoid unbounded allocations */
3172 l = MIN(l, TARGET_PAGE_SIZE);
3173 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3174 bounce.addr = addr;
3175 bounce.len = l;
3177 memory_region_ref(mr);
3178 bounce.mr = mr;
3179 if (!is_write) {
3180 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3181 bounce.buffer, l);
3184 *plen = l;
3185 return bounce.buffer;
3189 memory_region_ref(mr);
3190 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3191 l, is_write, attrs);
3192 fuzz_dma_read_cb(addr, *plen, mr, is_write);
3193 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3195 return ptr;
3198 /* Unmaps a memory region previously mapped by address_space_map().
3199 * Will also mark the memory as dirty if is_write is true. access_len gives
3200 * the amount of memory that was actually read or written by the caller.
3202 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3203 bool is_write, hwaddr access_len)
3205 if (buffer != bounce.buffer) {
3206 MemoryRegion *mr;
3207 ram_addr_t addr1;
3209 mr = memory_region_from_host(buffer, &addr1);
3210 assert(mr != NULL);
3211 if (is_write) {
3212 invalidate_and_set_dirty(mr, addr1, access_len);
3214 if (xen_enabled()) {
3215 xen_invalidate_map_cache_entry(buffer);
3217 memory_region_unref(mr);
3218 return;
3220 if (is_write) {
3221 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3222 bounce.buffer, access_len);
3224 qemu_vfree(bounce.buffer);
3225 bounce.buffer = NULL;
3226 memory_region_unref(bounce.mr);
3227 qatomic_mb_set(&bounce.in_use, false);
3228 cpu_notify_map_clients();
3231 void *cpu_physical_memory_map(hwaddr addr,
3232 hwaddr *plen,
3233 bool is_write)
3235 return address_space_map(&address_space_memory, addr, plen, is_write,
3236 MEMTXATTRS_UNSPECIFIED);
3239 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3240 bool is_write, hwaddr access_len)
3242 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3245 #define ARG1_DECL AddressSpace *as
3246 #define ARG1 as
3247 #define SUFFIX
3248 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3249 #define RCU_READ_LOCK(...) rcu_read_lock()
3250 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3251 #include "memory_ldst.c.inc"
3253 int64_t address_space_cache_init(MemoryRegionCache *cache,
3254 AddressSpace *as,
3255 hwaddr addr,
3256 hwaddr len,
3257 bool is_write)
3259 AddressSpaceDispatch *d;
3260 hwaddr l;
3261 MemoryRegion *mr;
3262 Int128 diff;
3264 assert(len > 0);
3266 l = len;
3267 cache->fv = address_space_get_flatview(as);
3268 d = flatview_to_dispatch(cache->fv);
3269 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3272 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3273 * Take that into account to compute how many bytes are there between
3274 * cache->xlat and the end of the section.
3276 diff = int128_sub(cache->mrs.size,
3277 int128_make64(cache->xlat - cache->mrs.offset_within_region));
3278 l = int128_get64(int128_min(diff, int128_make64(l)));
3280 mr = cache->mrs.mr;
3281 memory_region_ref(mr);
3282 if (memory_access_is_direct(mr, is_write)) {
3283 /* We don't care about the memory attributes here as we're only
3284 * doing this if we found actual RAM, which behaves the same
3285 * regardless of attributes; so UNSPECIFIED is fine.
3287 l = flatview_extend_translation(cache->fv, addr, len, mr,
3288 cache->xlat, l, is_write,
3289 MEMTXATTRS_UNSPECIFIED);
3290 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3291 } else {
3292 cache->ptr = NULL;
3295 cache->len = l;
3296 cache->is_write = is_write;
3297 return l;
3300 void address_space_cache_invalidate(MemoryRegionCache *cache,
3301 hwaddr addr,
3302 hwaddr access_len)
3304 assert(cache->is_write);
3305 if (likely(cache->ptr)) {
3306 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3310 void address_space_cache_destroy(MemoryRegionCache *cache)
3312 if (!cache->mrs.mr) {
3313 return;
3316 if (xen_enabled()) {
3317 xen_invalidate_map_cache_entry(cache->ptr);
3319 memory_region_unref(cache->mrs.mr);
3320 flatview_unref(cache->fv);
3321 cache->mrs.mr = NULL;
3322 cache->fv = NULL;
3325 /* Called from RCU critical section. This function has the same
3326 * semantics as address_space_translate, but it only works on a
3327 * predefined range of a MemoryRegion that was mapped with
3328 * address_space_cache_init.
3330 static inline MemoryRegion *address_space_translate_cached(
3331 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3332 hwaddr *plen, bool is_write, MemTxAttrs attrs)
3334 MemoryRegionSection section;
3335 MemoryRegion *mr;
3336 IOMMUMemoryRegion *iommu_mr;
3337 AddressSpace *target_as;
3339 assert(!cache->ptr);
3340 *xlat = addr + cache->xlat;
3342 mr = cache->mrs.mr;
3343 iommu_mr = memory_region_get_iommu(mr);
3344 if (!iommu_mr) {
3345 /* MMIO region. */
3346 return mr;
3349 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3350 NULL, is_write, true,
3351 &target_as, attrs);
3352 return section.mr;
3355 /* Called from RCU critical section. address_space_read_cached uses this
3356 * out of line function when the target is an MMIO or IOMMU region.
3358 MemTxResult
3359 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3360 void *buf, hwaddr len)
3362 hwaddr addr1, l;
3363 MemoryRegion *mr;
3365 l = len;
3366 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3367 MEMTXATTRS_UNSPECIFIED);
3368 return flatview_read_continue(cache->fv,
3369 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3370 addr1, l, mr);
3373 /* Called from RCU critical section. address_space_write_cached uses this
3374 * out of line function when the target is an MMIO or IOMMU region.
3376 MemTxResult
3377 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3378 const void *buf, hwaddr len)
3380 hwaddr addr1, l;
3381 MemoryRegion *mr;
3383 l = len;
3384 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3385 MEMTXATTRS_UNSPECIFIED);
3386 return flatview_write_continue(cache->fv,
3387 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3388 addr1, l, mr);
3391 #define ARG1_DECL MemoryRegionCache *cache
3392 #define ARG1 cache
3393 #define SUFFIX _cached_slow
3394 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3395 #define RCU_READ_LOCK() ((void)0)
3396 #define RCU_READ_UNLOCK() ((void)0)
3397 #include "memory_ldst.c.inc"
3399 /* virtual memory access for debug (includes writing to ROM) */
3400 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3401 void *ptr, target_ulong len, bool is_write)
3403 hwaddr phys_addr;
3404 target_ulong l, page;
3405 uint8_t *buf = ptr;
3407 cpu_synchronize_state(cpu);
3408 while (len > 0) {
3409 int asidx;
3410 MemTxAttrs attrs;
3411 MemTxResult res;
3413 page = addr & TARGET_PAGE_MASK;
3414 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3415 asidx = cpu_asidx_from_attrs(cpu, attrs);
3416 /* if no physical page mapped, return an error */
3417 if (phys_addr == -1)
3418 return -1;
3419 l = (page + TARGET_PAGE_SIZE) - addr;
3420 if (l > len)
3421 l = len;
3422 phys_addr += (addr & ~TARGET_PAGE_MASK);
3423 if (is_write) {
3424 res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3425 attrs, buf, l);
3426 } else {
3427 res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3428 attrs, buf, l);
3430 if (res != MEMTX_OK) {
3431 return -1;
3433 len -= l;
3434 buf += l;
3435 addr += l;
3437 return 0;
3441 * Allows code that needs to deal with migration bitmaps etc to still be built
3442 * target independent.
3444 size_t qemu_target_page_size(void)
3446 return TARGET_PAGE_SIZE;
3449 int qemu_target_page_bits(void)
3451 return TARGET_PAGE_BITS;
3454 int qemu_target_page_bits_min(void)
3456 return TARGET_PAGE_BITS_MIN;
3459 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3461 MemoryRegion*mr;
3462 hwaddr l = 1;
3463 bool res;
3465 RCU_READ_LOCK_GUARD();
3466 mr = address_space_translate(&address_space_memory,
3467 phys_addr, &phys_addr, &l, false,
3468 MEMTXATTRS_UNSPECIFIED);
3470 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3471 return res;
3474 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3476 RAMBlock *block;
3477 int ret = 0;
3479 RCU_READ_LOCK_GUARD();
3480 RAMBLOCK_FOREACH(block) {
3481 ret = func(block, opaque);
3482 if (ret) {
3483 break;
3486 return ret;
3490 * Unmap pages of memory from start to start+length such that
3491 * they a) read as 0, b) Trigger whatever fault mechanism
3492 * the OS provides for postcopy.
3493 * The pages must be unmapped by the end of the function.
3494 * Returns: 0 on success, none-0 on failure
3497 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3499 int ret = -1;
3501 uint8_t *host_startaddr = rb->host + start;
3503 if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
3504 error_report("ram_block_discard_range: Unaligned start address: %p",
3505 host_startaddr);
3506 goto err;
3509 if ((start + length) <= rb->used_length) {
3510 bool need_madvise, need_fallocate;
3511 if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
3512 error_report("ram_block_discard_range: Unaligned length: %zx",
3513 length);
3514 goto err;
3517 errno = ENOTSUP; /* If we are missing MADVISE etc */
3519 /* The logic here is messy;
3520 * madvise DONTNEED fails for hugepages
3521 * fallocate works on hugepages and shmem
3523 need_madvise = (rb->page_size == qemu_host_page_size);
3524 need_fallocate = rb->fd != -1;
3525 if (need_fallocate) {
3526 /* For a file, this causes the area of the file to be zero'd
3527 * if read, and for hugetlbfs also causes it to be unmapped
3528 * so a userfault will trigger.
3530 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3531 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3532 start, length);
3533 if (ret) {
3534 ret = -errno;
3535 error_report("ram_block_discard_range: Failed to fallocate "
3536 "%s:%" PRIx64 " +%zx (%d)",
3537 rb->idstr, start, length, ret);
3538 goto err;
3540 #else
3541 ret = -ENOSYS;
3542 error_report("ram_block_discard_range: fallocate not available/file"
3543 "%s:%" PRIx64 " +%zx (%d)",
3544 rb->idstr, start, length, ret);
3545 goto err;
3546 #endif
3548 if (need_madvise) {
3549 /* For normal RAM this causes it to be unmapped,
3550 * for shared memory it causes the local mapping to disappear
3551 * and to fall back on the file contents (which we just
3552 * fallocate'd away).
3554 #if defined(CONFIG_MADVISE)
3555 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3556 if (ret) {
3557 ret = -errno;
3558 error_report("ram_block_discard_range: Failed to discard range "
3559 "%s:%" PRIx64 " +%zx (%d)",
3560 rb->idstr, start, length, ret);
3561 goto err;
3563 #else
3564 ret = -ENOSYS;
3565 error_report("ram_block_discard_range: MADVISE not available"
3566 "%s:%" PRIx64 " +%zx (%d)",
3567 rb->idstr, start, length, ret);
3568 goto err;
3569 #endif
3571 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3572 need_madvise, need_fallocate, ret);
3573 } else {
3574 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3575 "/%zx/" RAM_ADDR_FMT")",
3576 rb->idstr, start, length, rb->used_length);
3579 err:
3580 return ret;
3583 bool ramblock_is_pmem(RAMBlock *rb)
3585 return rb->flags & RAM_PMEM;
3588 static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
3590 if (start == end - 1) {
3591 qemu_printf("\t%3d ", start);
3592 } else {
3593 qemu_printf("\t%3d..%-3d ", start, end - 1);
3595 qemu_printf(" skip=%d ", skip);
3596 if (ptr == PHYS_MAP_NODE_NIL) {
3597 qemu_printf(" ptr=NIL");
3598 } else if (!skip) {
3599 qemu_printf(" ptr=#%d", ptr);
3600 } else {
3601 qemu_printf(" ptr=[%d]", ptr);
3603 qemu_printf("\n");
3606 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3607 int128_sub((size), int128_one())) : 0)
3609 void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
3611 int i;
3613 qemu_printf(" Dispatch\n");
3614 qemu_printf(" Physical sections\n");
3616 for (i = 0; i < d->map.sections_nb; ++i) {
3617 MemoryRegionSection *s = d->map.sections + i;
3618 const char *names[] = { " [unassigned]", " [not dirty]",
3619 " [ROM]", " [watch]" };
3621 qemu_printf(" #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx
3622 " %s%s%s%s%s",
3624 s->offset_within_address_space,
3625 s->offset_within_address_space + MR_SIZE(s->mr->size),
3626 s->mr->name ? s->mr->name : "(noname)",
3627 i < ARRAY_SIZE(names) ? names[i] : "",
3628 s->mr == root ? " [ROOT]" : "",
3629 s == d->mru_section ? " [MRU]" : "",
3630 s->mr->is_iommu ? " [iommu]" : "");
3632 if (s->mr->alias) {
3633 qemu_printf(" alias=%s", s->mr->alias->name ?
3634 s->mr->alias->name : "noname");
3636 qemu_printf("\n");
3639 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3640 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3641 for (i = 0; i < d->map.nodes_nb; ++i) {
3642 int j, jprev;
3643 PhysPageEntry prev;
3644 Node *n = d->map.nodes + i;
3646 qemu_printf(" [%d]\n", i);
3648 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3649 PhysPageEntry *pe = *n + j;
3651 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3652 continue;
3655 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3657 jprev = j;
3658 prev = *pe;
3661 if (jprev != ARRAY_SIZE(*n)) {
3662 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3668 * If positive, discarding RAM is disabled. If negative, discarding RAM is
3669 * required to work and cannot be disabled.
3671 static int ram_block_discard_disabled;
3673 int ram_block_discard_disable(bool state)
3675 int old;
3677 if (!state) {
3678 qatomic_dec(&ram_block_discard_disabled);
3679 return 0;
3682 do {
3683 old = qatomic_read(&ram_block_discard_disabled);
3684 if (old < 0) {
3685 return -EBUSY;
3687 } while (qatomic_cmpxchg(&ram_block_discard_disabled,
3688 old, old + 1) != old);
3689 return 0;
3692 int ram_block_discard_require(bool state)
3694 int old;
3696 if (!state) {
3697 qatomic_inc(&ram_block_discard_disabled);
3698 return 0;
3701 do {
3702 old = qatomic_read(&ram_block_discard_disabled);
3703 if (old > 0) {
3704 return -EBUSY;
3706 } while (qatomic_cmpxchg(&ram_block_discard_disabled,
3707 old, old - 1) != old);
3708 return 0;
3711 bool ram_block_discard_is_disabled(void)
3713 return qatomic_read(&ram_block_discard_disabled) > 0;
3716 bool ram_block_discard_is_required(void)
3718 return qatomic_read(&ram_block_discard_disabled) < 0;