spapr: Get rid of cas_check_pvr() error reporting
[qemu/ar7.git] / exec.c
blobec68f4a9ca504606b36ab2a79b74a9a500c61b8b
1 /*
2 * Virtual page mapping
4 * Copyright (c) 2003 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 #include "qemu/osdep.h"
21 #include "qemu-common.h"
22 #include "qapi/error.h"
24 #include "qemu/cutils.h"
25 #include "cpu.h"
26 #include "exec/exec-all.h"
27 #include "exec/target_page.h"
28 #include "tcg/tcg.h"
29 #include "hw/qdev-core.h"
30 #include "hw/qdev-properties.h"
31 #if !defined(CONFIG_USER_ONLY)
32 #include "hw/boards.h"
33 #include "hw/xen/xen.h"
34 #endif
35 #include "sysemu/kvm.h"
36 #include "sysemu/sysemu.h"
37 #include "sysemu/tcg.h"
38 #include "sysemu/qtest.h"
39 #include "qemu/timer.h"
40 #include "qemu/config-file.h"
41 #include "qemu/error-report.h"
42 #include "qemu/qemu-print.h"
43 #if defined(CONFIG_USER_ONLY)
44 #include "qemu.h"
45 #else /* !CONFIG_USER_ONLY */
46 #include "exec/memory.h"
47 #include "exec/ioport.h"
48 #include "sysemu/dma.h"
49 #include "sysemu/hostmem.h"
50 #include "sysemu/hw_accel.h"
51 #include "exec/address-spaces.h"
52 #include "sysemu/xen-mapcache.h"
53 #include "trace/trace-root.h"
55 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
56 #include <linux/falloc.h>
57 #endif
59 #endif
60 #include "qemu/rcu_queue.h"
61 #include "qemu/main-loop.h"
62 #include "translate-all.h"
63 #include "sysemu/replay.h"
65 #include "exec/memory-internal.h"
66 #include "exec/ram_addr.h"
67 #include "exec/log.h"
69 #include "qemu/pmem.h"
71 #include "migration/vmstate.h"
73 #include "qemu/range.h"
74 #ifndef _WIN32
75 #include "qemu/mmap-alloc.h"
76 #endif
78 #include "monitor/monitor.h"
80 #ifdef CONFIG_LIBDAXCTL
81 #include <daxctl/libdaxctl.h>
82 #endif
84 //#define DEBUG_SUBPAGE
86 #if !defined(CONFIG_USER_ONLY)
87 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
88 * are protected by the ramlist lock.
90 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
92 static MemoryRegion *system_memory;
93 static MemoryRegion *system_io;
95 AddressSpace address_space_io;
96 AddressSpace address_space_memory;
98 static MemoryRegion io_mem_unassigned;
99 #endif
101 uintptr_t qemu_host_page_size;
102 intptr_t qemu_host_page_mask;
104 #if !defined(CONFIG_USER_ONLY)
106 typedef struct PhysPageEntry PhysPageEntry;
108 struct PhysPageEntry {
109 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
110 uint32_t skip : 6;
111 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
112 uint32_t ptr : 26;
115 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
117 /* Size of the L2 (and L3, etc) page tables. */
118 #define ADDR_SPACE_BITS 64
120 #define P_L2_BITS 9
121 #define P_L2_SIZE (1 << P_L2_BITS)
123 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
125 typedef PhysPageEntry Node[P_L2_SIZE];
127 typedef struct PhysPageMap {
128 struct rcu_head rcu;
130 unsigned sections_nb;
131 unsigned sections_nb_alloc;
132 unsigned nodes_nb;
133 unsigned nodes_nb_alloc;
134 Node *nodes;
135 MemoryRegionSection *sections;
136 } PhysPageMap;
138 struct AddressSpaceDispatch {
139 MemoryRegionSection *mru_section;
140 /* This is a multi-level map on the physical address space.
141 * The bottom level has pointers to MemoryRegionSections.
143 PhysPageEntry phys_map;
144 PhysPageMap map;
147 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
148 typedef struct subpage_t {
149 MemoryRegion iomem;
150 FlatView *fv;
151 hwaddr base;
152 uint16_t sub_section[];
153 } subpage_t;
155 #define PHYS_SECTION_UNASSIGNED 0
157 static void io_mem_init(void);
158 static void memory_map_init(void);
159 static void tcg_log_global_after_sync(MemoryListener *listener);
160 static void tcg_commit(MemoryListener *listener);
163 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
164 * @cpu: the CPU whose AddressSpace this is
165 * @as: the AddressSpace itself
166 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
167 * @tcg_as_listener: listener for tracking changes to the AddressSpace
169 struct CPUAddressSpace {
170 CPUState *cpu;
171 AddressSpace *as;
172 struct AddressSpaceDispatch *memory_dispatch;
173 MemoryListener tcg_as_listener;
176 struct DirtyBitmapSnapshot {
177 ram_addr_t start;
178 ram_addr_t end;
179 unsigned long dirty[];
182 #endif
184 #if !defined(CONFIG_USER_ONLY)
186 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
188 static unsigned alloc_hint = 16;
189 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
190 map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
191 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
192 alloc_hint = map->nodes_nb_alloc;
196 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
198 unsigned i;
199 uint32_t ret;
200 PhysPageEntry e;
201 PhysPageEntry *p;
203 ret = map->nodes_nb++;
204 p = map->nodes[ret];
205 assert(ret != PHYS_MAP_NODE_NIL);
206 assert(ret != map->nodes_nb_alloc);
208 e.skip = leaf ? 0 : 1;
209 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
210 for (i = 0; i < P_L2_SIZE; ++i) {
211 memcpy(&p[i], &e, sizeof(e));
213 return ret;
216 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
217 hwaddr *index, uint64_t *nb, uint16_t leaf,
218 int level)
220 PhysPageEntry *p;
221 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
223 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
224 lp->ptr = phys_map_node_alloc(map, level == 0);
226 p = map->nodes[lp->ptr];
227 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
229 while (*nb && lp < &p[P_L2_SIZE]) {
230 if ((*index & (step - 1)) == 0 && *nb >= step) {
231 lp->skip = 0;
232 lp->ptr = leaf;
233 *index += step;
234 *nb -= step;
235 } else {
236 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
238 ++lp;
242 static void phys_page_set(AddressSpaceDispatch *d,
243 hwaddr index, uint64_t nb,
244 uint16_t leaf)
246 /* Wildly overreserve - it doesn't matter much. */
247 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
249 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
252 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
253 * and update our entry so we can skip it and go directly to the destination.
255 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
257 unsigned valid_ptr = P_L2_SIZE;
258 int valid = 0;
259 PhysPageEntry *p;
260 int i;
262 if (lp->ptr == PHYS_MAP_NODE_NIL) {
263 return;
266 p = nodes[lp->ptr];
267 for (i = 0; i < P_L2_SIZE; i++) {
268 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
269 continue;
272 valid_ptr = i;
273 valid++;
274 if (p[i].skip) {
275 phys_page_compact(&p[i], nodes);
279 /* We can only compress if there's only one child. */
280 if (valid != 1) {
281 return;
284 assert(valid_ptr < P_L2_SIZE);
286 /* Don't compress if it won't fit in the # of bits we have. */
287 if (P_L2_LEVELS >= (1 << 6) &&
288 lp->skip + p[valid_ptr].skip >= (1 << 6)) {
289 return;
292 lp->ptr = p[valid_ptr].ptr;
293 if (!p[valid_ptr].skip) {
294 /* If our only child is a leaf, make this a leaf. */
295 /* By design, we should have made this node a leaf to begin with so we
296 * should never reach here.
297 * But since it's so simple to handle this, let's do it just in case we
298 * change this rule.
300 lp->skip = 0;
301 } else {
302 lp->skip += p[valid_ptr].skip;
306 void address_space_dispatch_compact(AddressSpaceDispatch *d)
308 if (d->phys_map.skip) {
309 phys_page_compact(&d->phys_map, d->map.nodes);
313 static inline bool section_covers_addr(const MemoryRegionSection *section,
314 hwaddr addr)
316 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
317 * the section must cover the entire address space.
319 return int128_gethi(section->size) ||
320 range_covers_byte(section->offset_within_address_space,
321 int128_getlo(section->size), addr);
324 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
326 PhysPageEntry lp = d->phys_map, *p;
327 Node *nodes = d->map.nodes;
328 MemoryRegionSection *sections = d->map.sections;
329 hwaddr index = addr >> TARGET_PAGE_BITS;
330 int i;
332 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
333 if (lp.ptr == PHYS_MAP_NODE_NIL) {
334 return &sections[PHYS_SECTION_UNASSIGNED];
336 p = nodes[lp.ptr];
337 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
340 if (section_covers_addr(&sections[lp.ptr], addr)) {
341 return &sections[lp.ptr];
342 } else {
343 return &sections[PHYS_SECTION_UNASSIGNED];
347 /* Called from RCU critical section */
348 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
349 hwaddr addr,
350 bool resolve_subpage)
352 MemoryRegionSection *section = qatomic_read(&d->mru_section);
353 subpage_t *subpage;
355 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
356 !section_covers_addr(section, addr)) {
357 section = phys_page_find(d, addr);
358 qatomic_set(&d->mru_section, section);
360 if (resolve_subpage && section->mr->subpage) {
361 subpage = container_of(section->mr, subpage_t, iomem);
362 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
364 return section;
367 /* Called from RCU critical section */
368 static MemoryRegionSection *
369 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
370 hwaddr *plen, bool resolve_subpage)
372 MemoryRegionSection *section;
373 MemoryRegion *mr;
374 Int128 diff;
376 section = address_space_lookup_region(d, addr, resolve_subpage);
377 /* Compute offset within MemoryRegionSection */
378 addr -= section->offset_within_address_space;
380 /* Compute offset within MemoryRegion */
381 *xlat = addr + section->offset_within_region;
383 mr = section->mr;
385 /* MMIO registers can be expected to perform full-width accesses based only
386 * on their address, without considering adjacent registers that could
387 * decode to completely different MemoryRegions. When such registers
388 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
389 * regions overlap wildly. For this reason we cannot clamp the accesses
390 * here.
392 * If the length is small (as is the case for address_space_ldl/stl),
393 * everything works fine. If the incoming length is large, however,
394 * the caller really has to do the clamping through memory_access_size.
396 if (memory_region_is_ram(mr)) {
397 diff = int128_sub(section->size, int128_make64(addr));
398 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
400 return section;
404 * address_space_translate_iommu - translate an address through an IOMMU
405 * memory region and then through the target address space.
407 * @iommu_mr: the IOMMU memory region that we start the translation from
408 * @addr: the address to be translated through the MMU
409 * @xlat: the translated address offset within the destination memory region.
410 * It cannot be %NULL.
411 * @plen_out: valid read/write length of the translated address. It
412 * cannot be %NULL.
413 * @page_mask_out: page mask for the translated address. This
414 * should only be meaningful for IOMMU translated
415 * addresses, since there may be huge pages that this bit
416 * would tell. It can be %NULL if we don't care about it.
417 * @is_write: whether the translation operation is for write
418 * @is_mmio: whether this can be MMIO, set true if it can
419 * @target_as: the address space targeted by the IOMMU
420 * @attrs: transaction attributes
422 * This function is called from RCU critical section. It is the common
423 * part of flatview_do_translate and address_space_translate_cached.
425 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
426 hwaddr *xlat,
427 hwaddr *plen_out,
428 hwaddr *page_mask_out,
429 bool is_write,
430 bool is_mmio,
431 AddressSpace **target_as,
432 MemTxAttrs attrs)
434 MemoryRegionSection *section;
435 hwaddr page_mask = (hwaddr)-1;
437 do {
438 hwaddr addr = *xlat;
439 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
440 int iommu_idx = 0;
441 IOMMUTLBEntry iotlb;
443 if (imrc->attrs_to_index) {
444 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
447 iotlb = imrc->translate(iommu_mr, addr, is_write ?
448 IOMMU_WO : IOMMU_RO, iommu_idx);
450 if (!(iotlb.perm & (1 << is_write))) {
451 goto unassigned;
454 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
455 | (addr & iotlb.addr_mask));
456 page_mask &= iotlb.addr_mask;
457 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
458 *target_as = iotlb.target_as;
460 section = address_space_translate_internal(
461 address_space_to_dispatch(iotlb.target_as), addr, xlat,
462 plen_out, is_mmio);
464 iommu_mr = memory_region_get_iommu(section->mr);
465 } while (unlikely(iommu_mr));
467 if (page_mask_out) {
468 *page_mask_out = page_mask;
470 return *section;
472 unassigned:
473 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
477 * flatview_do_translate - translate an address in FlatView
479 * @fv: the flat view that we want to translate on
480 * @addr: the address to be translated in above address space
481 * @xlat: the translated address offset within memory region. It
482 * cannot be @NULL.
483 * @plen_out: valid read/write length of the translated address. It
484 * can be @NULL when we don't care about it.
485 * @page_mask_out: page mask for the translated address. This
486 * should only be meaningful for IOMMU translated
487 * addresses, since there may be huge pages that this bit
488 * would tell. It can be @NULL if we don't care about it.
489 * @is_write: whether the translation operation is for write
490 * @is_mmio: whether this can be MMIO, set true if it can
491 * @target_as: the address space targeted by the IOMMU
492 * @attrs: memory transaction attributes
494 * This function is called from RCU critical section
496 static MemoryRegionSection flatview_do_translate(FlatView *fv,
497 hwaddr addr,
498 hwaddr *xlat,
499 hwaddr *plen_out,
500 hwaddr *page_mask_out,
501 bool is_write,
502 bool is_mmio,
503 AddressSpace **target_as,
504 MemTxAttrs attrs)
506 MemoryRegionSection *section;
507 IOMMUMemoryRegion *iommu_mr;
508 hwaddr plen = (hwaddr)(-1);
510 if (!plen_out) {
511 plen_out = &plen;
514 section = address_space_translate_internal(
515 flatview_to_dispatch(fv), addr, xlat,
516 plen_out, is_mmio);
518 iommu_mr = memory_region_get_iommu(section->mr);
519 if (unlikely(iommu_mr)) {
520 return address_space_translate_iommu(iommu_mr, xlat,
521 plen_out, page_mask_out,
522 is_write, is_mmio,
523 target_as, attrs);
525 if (page_mask_out) {
526 /* Not behind an IOMMU, use default page size. */
527 *page_mask_out = ~TARGET_PAGE_MASK;
530 return *section;
533 /* Called from RCU critical section */
534 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
535 bool is_write, MemTxAttrs attrs)
537 MemoryRegionSection section;
538 hwaddr xlat, page_mask;
541 * This can never be MMIO, and we don't really care about plen,
542 * but page mask.
544 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
545 NULL, &page_mask, is_write, false, &as,
546 attrs);
548 /* Illegal translation */
549 if (section.mr == &io_mem_unassigned) {
550 goto iotlb_fail;
553 /* Convert memory region offset into address space offset */
554 xlat += section.offset_within_address_space -
555 section.offset_within_region;
557 return (IOMMUTLBEntry) {
558 .target_as = as,
559 .iova = addr & ~page_mask,
560 .translated_addr = xlat & ~page_mask,
561 .addr_mask = page_mask,
562 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
563 .perm = IOMMU_RW,
566 iotlb_fail:
567 return (IOMMUTLBEntry) {0};
570 /* Called from RCU critical section */
571 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
572 hwaddr *plen, bool is_write,
573 MemTxAttrs attrs)
575 MemoryRegion *mr;
576 MemoryRegionSection section;
577 AddressSpace *as = NULL;
579 /* This can be MMIO, so setup MMIO bit. */
580 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
581 is_write, true, &as, attrs);
582 mr = section.mr;
584 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
585 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
586 *plen = MIN(page, *plen);
589 return mr;
592 typedef struct TCGIOMMUNotifier {
593 IOMMUNotifier n;
594 MemoryRegion *mr;
595 CPUState *cpu;
596 int iommu_idx;
597 bool active;
598 } TCGIOMMUNotifier;
600 static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
602 TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
604 if (!notifier->active) {
605 return;
607 tlb_flush(notifier->cpu);
608 notifier->active = false;
609 /* We leave the notifier struct on the list to avoid reallocating it later.
610 * Generally the number of IOMMUs a CPU deals with will be small.
611 * In any case we can't unregister the iommu notifier from a notify
612 * callback.
616 static void tcg_register_iommu_notifier(CPUState *cpu,
617 IOMMUMemoryRegion *iommu_mr,
618 int iommu_idx)
620 /* Make sure this CPU has an IOMMU notifier registered for this
621 * IOMMU/IOMMU index combination, so that we can flush its TLB
622 * when the IOMMU tells us the mappings we've cached have changed.
624 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
625 TCGIOMMUNotifier *notifier;
626 Error *err = NULL;
627 int i, ret;
629 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
630 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
631 if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
632 break;
635 if (i == cpu->iommu_notifiers->len) {
636 /* Not found, add a new entry at the end of the array */
637 cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
638 notifier = g_new0(TCGIOMMUNotifier, 1);
639 g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
641 notifier->mr = mr;
642 notifier->iommu_idx = iommu_idx;
643 notifier->cpu = cpu;
644 /* Rather than trying to register interest in the specific part
645 * of the iommu's address space that we've accessed and then
646 * expand it later as subsequent accesses touch more of it, we
647 * just register interest in the whole thing, on the assumption
648 * that iommu reconfiguration will be rare.
650 iommu_notifier_init(&notifier->n,
651 tcg_iommu_unmap_notify,
652 IOMMU_NOTIFIER_UNMAP,
654 HWADDR_MAX,
655 iommu_idx);
656 ret = memory_region_register_iommu_notifier(notifier->mr, &notifier->n,
657 &err);
658 if (ret) {
659 error_report_err(err);
660 exit(1);
664 if (!notifier->active) {
665 notifier->active = true;
669 static void tcg_iommu_free_notifier_list(CPUState *cpu)
671 /* Destroy the CPU's notifier list */
672 int i;
673 TCGIOMMUNotifier *notifier;
675 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
676 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
677 memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
678 g_free(notifier);
680 g_array_free(cpu->iommu_notifiers, true);
683 /* Called from RCU critical section */
684 MemoryRegionSection *
685 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
686 hwaddr *xlat, hwaddr *plen,
687 MemTxAttrs attrs, int *prot)
689 MemoryRegionSection *section;
690 IOMMUMemoryRegion *iommu_mr;
691 IOMMUMemoryRegionClass *imrc;
692 IOMMUTLBEntry iotlb;
693 int iommu_idx;
694 AddressSpaceDispatch *d =
695 qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
697 for (;;) {
698 section = address_space_translate_internal(d, addr, &addr, plen, false);
700 iommu_mr = memory_region_get_iommu(section->mr);
701 if (!iommu_mr) {
702 break;
705 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
707 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
708 tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
709 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
710 * doesn't short-cut its translation table walk.
712 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
713 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
714 | (addr & iotlb.addr_mask));
715 /* Update the caller's prot bits to remove permissions the IOMMU
716 * is giving us a failure response for. If we get down to no
717 * permissions left at all we can give up now.
719 if (!(iotlb.perm & IOMMU_RO)) {
720 *prot &= ~(PAGE_READ | PAGE_EXEC);
722 if (!(iotlb.perm & IOMMU_WO)) {
723 *prot &= ~PAGE_WRITE;
726 if (!*prot) {
727 goto translate_fail;
730 d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
733 assert(!memory_region_is_iommu(section->mr));
734 *xlat = addr;
735 return section;
737 translate_fail:
738 return &d->map.sections[PHYS_SECTION_UNASSIGNED];
740 #endif
742 #if !defined(CONFIG_USER_ONLY)
744 static int cpu_common_post_load(void *opaque, int version_id)
746 CPUState *cpu = opaque;
748 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
749 version_id is increased. */
750 cpu->interrupt_request &= ~0x01;
751 tlb_flush(cpu);
753 /* loadvm has just updated the content of RAM, bypassing the
754 * usual mechanisms that ensure we flush TBs for writes to
755 * memory we've translated code from. So we must flush all TBs,
756 * which will now be stale.
758 tb_flush(cpu);
760 return 0;
763 static int cpu_common_pre_load(void *opaque)
765 CPUState *cpu = opaque;
767 cpu->exception_index = -1;
769 return 0;
772 static bool cpu_common_exception_index_needed(void *opaque)
774 CPUState *cpu = opaque;
776 return tcg_enabled() && cpu->exception_index != -1;
779 static const VMStateDescription vmstate_cpu_common_exception_index = {
780 .name = "cpu_common/exception_index",
781 .version_id = 1,
782 .minimum_version_id = 1,
783 .needed = cpu_common_exception_index_needed,
784 .fields = (VMStateField[]) {
785 VMSTATE_INT32(exception_index, CPUState),
786 VMSTATE_END_OF_LIST()
790 static bool cpu_common_crash_occurred_needed(void *opaque)
792 CPUState *cpu = opaque;
794 return cpu->crash_occurred;
797 static const VMStateDescription vmstate_cpu_common_crash_occurred = {
798 .name = "cpu_common/crash_occurred",
799 .version_id = 1,
800 .minimum_version_id = 1,
801 .needed = cpu_common_crash_occurred_needed,
802 .fields = (VMStateField[]) {
803 VMSTATE_BOOL(crash_occurred, CPUState),
804 VMSTATE_END_OF_LIST()
808 const VMStateDescription vmstate_cpu_common = {
809 .name = "cpu_common",
810 .version_id = 1,
811 .minimum_version_id = 1,
812 .pre_load = cpu_common_pre_load,
813 .post_load = cpu_common_post_load,
814 .fields = (VMStateField[]) {
815 VMSTATE_UINT32(halted, CPUState),
816 VMSTATE_UINT32(interrupt_request, CPUState),
817 VMSTATE_END_OF_LIST()
819 .subsections = (const VMStateDescription*[]) {
820 &vmstate_cpu_common_exception_index,
821 &vmstate_cpu_common_crash_occurred,
822 NULL
826 void cpu_address_space_init(CPUState *cpu, int asidx,
827 const char *prefix, MemoryRegion *mr)
829 CPUAddressSpace *newas;
830 AddressSpace *as = g_new0(AddressSpace, 1);
831 char *as_name;
833 assert(mr);
834 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
835 address_space_init(as, mr, as_name);
836 g_free(as_name);
838 /* Target code should have set num_ases before calling us */
839 assert(asidx < cpu->num_ases);
841 if (asidx == 0) {
842 /* address space 0 gets the convenience alias */
843 cpu->as = as;
846 /* KVM cannot currently support multiple address spaces. */
847 assert(asidx == 0 || !kvm_enabled());
849 if (!cpu->cpu_ases) {
850 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
853 newas = &cpu->cpu_ases[asidx];
854 newas->cpu = cpu;
855 newas->as = as;
856 if (tcg_enabled()) {
857 newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
858 newas->tcg_as_listener.commit = tcg_commit;
859 memory_listener_register(&newas->tcg_as_listener, as);
863 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
865 /* Return the AddressSpace corresponding to the specified index */
866 return cpu->cpu_ases[asidx].as;
868 #endif
870 void cpu_exec_unrealizefn(CPUState *cpu)
872 CPUClass *cc = CPU_GET_CLASS(cpu);
874 tlb_destroy(cpu);
875 cpu_list_remove(cpu);
877 if (cc->vmsd != NULL) {
878 vmstate_unregister(NULL, cc->vmsd, cpu);
880 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
881 vmstate_unregister(NULL, &vmstate_cpu_common, cpu);
883 #ifndef CONFIG_USER_ONLY
884 tcg_iommu_free_notifier_list(cpu);
885 #endif
888 Property cpu_common_props[] = {
889 #ifndef CONFIG_USER_ONLY
890 /* Create a memory property for softmmu CPU object,
891 * so users can wire up its memory. (This can't go in hw/core/cpu.c
892 * because that file is compiled only once for both user-mode
893 * and system builds.) The default if no link is set up is to use
894 * the system address space.
896 DEFINE_PROP_LINK("memory", CPUState, memory, TYPE_MEMORY_REGION,
897 MemoryRegion *),
898 #endif
899 DEFINE_PROP_BOOL("start-powered-off", CPUState, start_powered_off, false),
900 DEFINE_PROP_END_OF_LIST(),
903 void cpu_exec_initfn(CPUState *cpu)
905 cpu->as = NULL;
906 cpu->num_ases = 0;
908 #ifndef CONFIG_USER_ONLY
909 cpu->thread_id = qemu_get_thread_id();
910 cpu->memory = system_memory;
911 object_ref(OBJECT(cpu->memory));
912 #endif
915 void cpu_exec_realizefn(CPUState *cpu, Error **errp)
917 CPUClass *cc = CPU_GET_CLASS(cpu);
918 static bool tcg_target_initialized;
920 cpu_list_add(cpu);
922 if (tcg_enabled() && !tcg_target_initialized) {
923 tcg_target_initialized = true;
924 cc->tcg_initialize();
926 tlb_init(cpu);
928 qemu_plugin_vcpu_init_hook(cpu);
930 #ifdef CONFIG_USER_ONLY
931 assert(cc->vmsd == NULL);
932 #else /* !CONFIG_USER_ONLY */
933 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
934 vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
936 if (cc->vmsd != NULL) {
937 vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);
940 cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
941 #endif
944 const char *parse_cpu_option(const char *cpu_option)
946 ObjectClass *oc;
947 CPUClass *cc;
948 gchar **model_pieces;
949 const char *cpu_type;
951 model_pieces = g_strsplit(cpu_option, ",", 2);
952 if (!model_pieces[0]) {
953 error_report("-cpu option cannot be empty");
954 exit(1);
957 oc = cpu_class_by_name(CPU_RESOLVING_TYPE, model_pieces[0]);
958 if (oc == NULL) {
959 error_report("unable to find CPU model '%s'", model_pieces[0]);
960 g_strfreev(model_pieces);
961 exit(EXIT_FAILURE);
964 cpu_type = object_class_get_name(oc);
965 cc = CPU_CLASS(oc);
966 cc->parse_features(cpu_type, model_pieces[1], &error_fatal);
967 g_strfreev(model_pieces);
968 return cpu_type;
971 #if defined(CONFIG_USER_ONLY)
972 void tb_invalidate_phys_addr(target_ulong addr)
974 mmap_lock();
975 tb_invalidate_phys_page_range(addr, addr + 1);
976 mmap_unlock();
979 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
981 tb_invalidate_phys_addr(pc);
983 #else
984 void tb_invalidate_phys_addr(AddressSpace *as, hwaddr addr, MemTxAttrs attrs)
986 ram_addr_t ram_addr;
987 MemoryRegion *mr;
988 hwaddr l = 1;
990 if (!tcg_enabled()) {
991 return;
994 RCU_READ_LOCK_GUARD();
995 mr = address_space_translate(as, addr, &addr, &l, false, attrs);
996 if (!(memory_region_is_ram(mr)
997 || memory_region_is_romd(mr))) {
998 return;
1000 ram_addr = memory_region_get_ram_addr(mr) + addr;
1001 tb_invalidate_phys_page_range(ram_addr, ram_addr + 1);
1004 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
1007 * There may not be a virtual to physical translation for the pc
1008 * right now, but there may exist cached TB for this pc.
1009 * Flush the whole TB cache to force re-translation of such TBs.
1010 * This is heavyweight, but we're debugging anyway.
1012 tb_flush(cpu);
1014 #endif
1016 #ifndef CONFIG_USER_ONLY
1017 /* Add a watchpoint. */
1018 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
1019 int flags, CPUWatchpoint **watchpoint)
1021 CPUWatchpoint *wp;
1022 vaddr in_page;
1024 /* forbid ranges which are empty or run off the end of the address space */
1025 if (len == 0 || (addr + len - 1) < addr) {
1026 error_report("tried to set invalid watchpoint at %"
1027 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
1028 return -EINVAL;
1030 wp = g_malloc(sizeof(*wp));
1032 wp->vaddr = addr;
1033 wp->len = len;
1034 wp->flags = flags;
1036 /* keep all GDB-injected watchpoints in front */
1037 if (flags & BP_GDB) {
1038 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
1039 } else {
1040 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
1043 in_page = -(addr | TARGET_PAGE_MASK);
1044 if (len <= in_page) {
1045 tlb_flush_page(cpu, addr);
1046 } else {
1047 tlb_flush(cpu);
1050 if (watchpoint)
1051 *watchpoint = wp;
1052 return 0;
1055 /* Remove a specific watchpoint. */
1056 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
1057 int flags)
1059 CPUWatchpoint *wp;
1061 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1062 if (addr == wp->vaddr && len == wp->len
1063 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
1064 cpu_watchpoint_remove_by_ref(cpu, wp);
1065 return 0;
1068 return -ENOENT;
1071 /* Remove a specific watchpoint by reference. */
1072 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
1074 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
1076 tlb_flush_page(cpu, watchpoint->vaddr);
1078 g_free(watchpoint);
1081 /* Remove all matching watchpoints. */
1082 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
1084 CPUWatchpoint *wp, *next;
1086 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
1087 if (wp->flags & mask) {
1088 cpu_watchpoint_remove_by_ref(cpu, wp);
1093 /* Return true if this watchpoint address matches the specified
1094 * access (ie the address range covered by the watchpoint overlaps
1095 * partially or completely with the address range covered by the
1096 * access).
1098 static inline bool watchpoint_address_matches(CPUWatchpoint *wp,
1099 vaddr addr, vaddr len)
1101 /* We know the lengths are non-zero, but a little caution is
1102 * required to avoid errors in the case where the range ends
1103 * exactly at the top of the address space and so addr + len
1104 * wraps round to zero.
1106 vaddr wpend = wp->vaddr + wp->len - 1;
1107 vaddr addrend = addr + len - 1;
1109 return !(addr > wpend || wp->vaddr > addrend);
1112 /* Return flags for watchpoints that match addr + prot. */
1113 int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len)
1115 CPUWatchpoint *wp;
1116 int ret = 0;
1118 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1119 if (watchpoint_address_matches(wp, addr, len)) {
1120 ret |= wp->flags;
1123 return ret;
1125 #endif /* !CONFIG_USER_ONLY */
1127 /* Add a breakpoint. */
1128 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
1129 CPUBreakpoint **breakpoint)
1131 CPUBreakpoint *bp;
1133 bp = g_malloc(sizeof(*bp));
1135 bp->pc = pc;
1136 bp->flags = flags;
1138 /* keep all GDB-injected breakpoints in front */
1139 if (flags & BP_GDB) {
1140 QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
1141 } else {
1142 QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
1145 breakpoint_invalidate(cpu, pc);
1147 if (breakpoint) {
1148 *breakpoint = bp;
1150 return 0;
1153 /* Remove a specific breakpoint. */
1154 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
1156 CPUBreakpoint *bp;
1158 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
1159 if (bp->pc == pc && bp->flags == flags) {
1160 cpu_breakpoint_remove_by_ref(cpu, bp);
1161 return 0;
1164 return -ENOENT;
1167 /* Remove a specific breakpoint by reference. */
1168 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
1170 QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);
1172 breakpoint_invalidate(cpu, breakpoint->pc);
1174 g_free(breakpoint);
1177 /* Remove all matching breakpoints. */
1178 void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
1180 CPUBreakpoint *bp, *next;
1182 QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
1183 if (bp->flags & mask) {
1184 cpu_breakpoint_remove_by_ref(cpu, bp);
1189 /* enable or disable single step mode. EXCP_DEBUG is returned by the
1190 CPU loop after each instruction */
1191 void cpu_single_step(CPUState *cpu, int enabled)
1193 if (cpu->singlestep_enabled != enabled) {
1194 cpu->singlestep_enabled = enabled;
1195 if (kvm_enabled()) {
1196 kvm_update_guest_debug(cpu, 0);
1197 } else {
1198 /* must flush all the translated code to avoid inconsistencies */
1199 /* XXX: only flush what is necessary */
1200 tb_flush(cpu);
1205 void cpu_abort(CPUState *cpu, const char *fmt, ...)
1207 va_list ap;
1208 va_list ap2;
1210 va_start(ap, fmt);
1211 va_copy(ap2, ap);
1212 fprintf(stderr, "qemu: fatal: ");
1213 vfprintf(stderr, fmt, ap);
1214 fprintf(stderr, "\n");
1215 cpu_dump_state(cpu, stderr, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1216 if (qemu_log_separate()) {
1217 FILE *logfile = qemu_log_lock();
1218 qemu_log("qemu: fatal: ");
1219 qemu_log_vprintf(fmt, ap2);
1220 qemu_log("\n");
1221 log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1222 qemu_log_flush();
1223 qemu_log_unlock(logfile);
1224 qemu_log_close();
1226 va_end(ap2);
1227 va_end(ap);
1228 replay_finish();
1229 #if defined(CONFIG_USER_ONLY)
1231 struct sigaction act;
1232 sigfillset(&act.sa_mask);
1233 act.sa_handler = SIG_DFL;
1234 act.sa_flags = 0;
1235 sigaction(SIGABRT, &act, NULL);
1237 #endif
1238 abort();
1241 #if !defined(CONFIG_USER_ONLY)
1242 /* Called from RCU critical section */
1243 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
1245 RAMBlock *block;
1247 block = qatomic_rcu_read(&ram_list.mru_block);
1248 if (block && addr - block->offset < block->max_length) {
1249 return block;
1251 RAMBLOCK_FOREACH(block) {
1252 if (addr - block->offset < block->max_length) {
1253 goto found;
1257 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1258 abort();
1260 found:
1261 /* It is safe to write mru_block outside the iothread lock. This
1262 * is what happens:
1264 * mru_block = xxx
1265 * rcu_read_unlock()
1266 * xxx removed from list
1267 * rcu_read_lock()
1268 * read mru_block
1269 * mru_block = NULL;
1270 * call_rcu(reclaim_ramblock, xxx);
1271 * rcu_read_unlock()
1273 * qatomic_rcu_set is not needed here. The block was already published
1274 * when it was placed into the list. Here we're just making an extra
1275 * copy of the pointer.
1277 ram_list.mru_block = block;
1278 return block;
1281 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1283 CPUState *cpu;
1284 ram_addr_t start1;
1285 RAMBlock *block;
1286 ram_addr_t end;
1288 assert(tcg_enabled());
1289 end = TARGET_PAGE_ALIGN(start + length);
1290 start &= TARGET_PAGE_MASK;
1292 RCU_READ_LOCK_GUARD();
1293 block = qemu_get_ram_block(start);
1294 assert(block == qemu_get_ram_block(end - 1));
1295 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1296 CPU_FOREACH(cpu) {
1297 tlb_reset_dirty(cpu, start1, length);
1301 /* Note: start and end must be within the same ram block. */
1302 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1303 ram_addr_t length,
1304 unsigned client)
1306 DirtyMemoryBlocks *blocks;
1307 unsigned long end, page, start_page;
1308 bool dirty = false;
1309 RAMBlock *ramblock;
1310 uint64_t mr_offset, mr_size;
1312 if (length == 0) {
1313 return false;
1316 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1317 start_page = start >> TARGET_PAGE_BITS;
1318 page = start_page;
1320 WITH_RCU_READ_LOCK_GUARD() {
1321 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1322 ramblock = qemu_get_ram_block(start);
1323 /* Range sanity check on the ramblock */
1324 assert(start >= ramblock->offset &&
1325 start + length <= ramblock->offset + ramblock->used_length);
1327 while (page < end) {
1328 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1329 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1330 unsigned long num = MIN(end - page,
1331 DIRTY_MEMORY_BLOCK_SIZE - offset);
1333 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1334 offset, num);
1335 page += num;
1338 mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
1339 mr_size = (end - start_page) << TARGET_PAGE_BITS;
1340 memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
1343 if (dirty && tcg_enabled()) {
1344 tlb_reset_dirty_range_all(start, length);
1347 return dirty;
1350 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1351 (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
1353 DirtyMemoryBlocks *blocks;
1354 ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
1355 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1356 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1357 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1358 DirtyBitmapSnapshot *snap;
1359 unsigned long page, end, dest;
1361 snap = g_malloc0(sizeof(*snap) +
1362 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1363 snap->start = first;
1364 snap->end = last;
1366 page = first >> TARGET_PAGE_BITS;
1367 end = last >> TARGET_PAGE_BITS;
1368 dest = 0;
1370 WITH_RCU_READ_LOCK_GUARD() {
1371 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1373 while (page < end) {
1374 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1375 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1376 unsigned long num = MIN(end - page,
1377 DIRTY_MEMORY_BLOCK_SIZE - offset);
1379 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1380 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1381 offset >>= BITS_PER_LEVEL;
1383 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1384 blocks->blocks[idx] + offset,
1385 num);
1386 page += num;
1387 dest += num >> BITS_PER_LEVEL;
1391 if (tcg_enabled()) {
1392 tlb_reset_dirty_range_all(start, length);
1395 memory_region_clear_dirty_bitmap(mr, offset, length);
1397 return snap;
1400 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1401 ram_addr_t start,
1402 ram_addr_t length)
1404 unsigned long page, end;
1406 assert(start >= snap->start);
1407 assert(start + length <= snap->end);
1409 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1410 page = (start - snap->start) >> TARGET_PAGE_BITS;
1412 while (page < end) {
1413 if (test_bit(page, snap->dirty)) {
1414 return true;
1416 page++;
1418 return false;
1421 /* Called from RCU critical section */
1422 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1423 MemoryRegionSection *section)
1425 AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
1426 return section - d->map.sections;
1428 #endif /* defined(CONFIG_USER_ONLY) */
1430 #if !defined(CONFIG_USER_ONLY)
1432 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
1433 uint16_t section);
1434 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1436 static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
1437 qemu_anon_ram_alloc;
1440 * Set a custom physical guest memory alloator.
1441 * Accelerators with unusual needs may need this. Hopefully, we can
1442 * get rid of it eventually.
1444 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
1446 phys_mem_alloc = alloc;
1449 static uint16_t phys_section_add(PhysPageMap *map,
1450 MemoryRegionSection *section)
1452 /* The physical section number is ORed with a page-aligned
1453 * pointer to produce the iotlb entries. Thus it should
1454 * never overflow into the page-aligned value.
1456 assert(map->sections_nb < TARGET_PAGE_SIZE);
1458 if (map->sections_nb == map->sections_nb_alloc) {
1459 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1460 map->sections = g_renew(MemoryRegionSection, map->sections,
1461 map->sections_nb_alloc);
1463 map->sections[map->sections_nb] = *section;
1464 memory_region_ref(section->mr);
1465 return map->sections_nb++;
1468 static void phys_section_destroy(MemoryRegion *mr)
1470 bool have_sub_page = mr->subpage;
1472 memory_region_unref(mr);
1474 if (have_sub_page) {
1475 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1476 object_unref(OBJECT(&subpage->iomem));
1477 g_free(subpage);
1481 static void phys_sections_free(PhysPageMap *map)
1483 while (map->sections_nb > 0) {
1484 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1485 phys_section_destroy(section->mr);
1487 g_free(map->sections);
1488 g_free(map->nodes);
1491 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1493 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1494 subpage_t *subpage;
1495 hwaddr base = section->offset_within_address_space
1496 & TARGET_PAGE_MASK;
1497 MemoryRegionSection *existing = phys_page_find(d, base);
1498 MemoryRegionSection subsection = {
1499 .offset_within_address_space = base,
1500 .size = int128_make64(TARGET_PAGE_SIZE),
1502 hwaddr start, end;
1504 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1506 if (!(existing->mr->subpage)) {
1507 subpage = subpage_init(fv, base);
1508 subsection.fv = fv;
1509 subsection.mr = &subpage->iomem;
1510 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1511 phys_section_add(&d->map, &subsection));
1512 } else {
1513 subpage = container_of(existing->mr, subpage_t, iomem);
1515 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1516 end = start + int128_get64(section->size) - 1;
1517 subpage_register(subpage, start, end,
1518 phys_section_add(&d->map, section));
1522 static void register_multipage(FlatView *fv,
1523 MemoryRegionSection *section)
1525 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1526 hwaddr start_addr = section->offset_within_address_space;
1527 uint16_t section_index = phys_section_add(&d->map, section);
1528 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1529 TARGET_PAGE_BITS));
1531 assert(num_pages);
1532 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1536 * The range in *section* may look like this:
1538 * |s|PPPPPPP|s|
1540 * where s stands for subpage and P for page.
1542 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1544 MemoryRegionSection remain = *section;
1545 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1547 /* register first subpage */
1548 if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1549 uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1550 - remain.offset_within_address_space;
1552 MemoryRegionSection now = remain;
1553 now.size = int128_min(int128_make64(left), now.size);
1554 register_subpage(fv, &now);
1555 if (int128_eq(remain.size, now.size)) {
1556 return;
1558 remain.size = int128_sub(remain.size, now.size);
1559 remain.offset_within_address_space += int128_get64(now.size);
1560 remain.offset_within_region += int128_get64(now.size);
1563 /* register whole pages */
1564 if (int128_ge(remain.size, page_size)) {
1565 MemoryRegionSection now = remain;
1566 now.size = int128_and(now.size, int128_neg(page_size));
1567 register_multipage(fv, &now);
1568 if (int128_eq(remain.size, now.size)) {
1569 return;
1571 remain.size = int128_sub(remain.size, now.size);
1572 remain.offset_within_address_space += int128_get64(now.size);
1573 remain.offset_within_region += int128_get64(now.size);
1576 /* register last subpage */
1577 register_subpage(fv, &remain);
1580 void qemu_flush_coalesced_mmio_buffer(void)
1582 if (kvm_enabled())
1583 kvm_flush_coalesced_mmio_buffer();
1586 void qemu_mutex_lock_ramlist(void)
1588 qemu_mutex_lock(&ram_list.mutex);
1591 void qemu_mutex_unlock_ramlist(void)
1593 qemu_mutex_unlock(&ram_list.mutex);
1596 void ram_block_dump(Monitor *mon)
1598 RAMBlock *block;
1599 char *psize;
1601 RCU_READ_LOCK_GUARD();
1602 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1603 "Block Name", "PSize", "Offset", "Used", "Total");
1604 RAMBLOCK_FOREACH(block) {
1605 psize = size_to_str(block->page_size);
1606 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1607 " 0x%016" PRIx64 "\n", block->idstr, psize,
1608 (uint64_t)block->offset,
1609 (uint64_t)block->used_length,
1610 (uint64_t)block->max_length);
1611 g_free(psize);
1615 #ifdef __linux__
1617 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1618 * may or may not name the same files / on the same filesystem now as
1619 * when we actually open and map them. Iterate over the file
1620 * descriptors instead, and use qemu_fd_getpagesize().
1622 static int find_min_backend_pagesize(Object *obj, void *opaque)
1624 long *hpsize_min = opaque;
1626 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1627 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1628 long hpsize = host_memory_backend_pagesize(backend);
1630 if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
1631 *hpsize_min = hpsize;
1635 return 0;
1638 static int find_max_backend_pagesize(Object *obj, void *opaque)
1640 long *hpsize_max = opaque;
1642 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1643 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1644 long hpsize = host_memory_backend_pagesize(backend);
1646 if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1647 *hpsize_max = hpsize;
1651 return 0;
1655 * TODO: We assume right now that all mapped host memory backends are
1656 * used as RAM, however some might be used for different purposes.
1658 long qemu_minrampagesize(void)
1660 long hpsize = LONG_MAX;
1661 Object *memdev_root = object_resolve_path("/objects", NULL);
1663 object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
1664 return hpsize;
1667 long qemu_maxrampagesize(void)
1669 long pagesize = 0;
1670 Object *memdev_root = object_resolve_path("/objects", NULL);
1672 object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
1673 return pagesize;
1675 #else
1676 long qemu_minrampagesize(void)
1678 return qemu_real_host_page_size;
1680 long qemu_maxrampagesize(void)
1682 return qemu_real_host_page_size;
1684 #endif
1686 #ifdef CONFIG_POSIX
1687 static int64_t get_file_size(int fd)
1689 int64_t size;
1690 #if defined(__linux__)
1691 struct stat st;
1693 if (fstat(fd, &st) < 0) {
1694 return -errno;
1697 /* Special handling for devdax character devices */
1698 if (S_ISCHR(st.st_mode)) {
1699 g_autofree char *subsystem_path = NULL;
1700 g_autofree char *subsystem = NULL;
1702 subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1703 major(st.st_rdev), minor(st.st_rdev));
1704 subsystem = g_file_read_link(subsystem_path, NULL);
1706 if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
1707 g_autofree char *size_path = NULL;
1708 g_autofree char *size_str = NULL;
1710 size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
1711 major(st.st_rdev), minor(st.st_rdev));
1713 if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
1714 return g_ascii_strtoll(size_str, NULL, 0);
1718 #endif /* defined(__linux__) */
1720 /* st.st_size may be zero for special files yet lseek(2) works */
1721 size = lseek(fd, 0, SEEK_END);
1722 if (size < 0) {
1723 return -errno;
1725 return size;
1728 static int64_t get_file_align(int fd)
1730 int64_t align = -1;
1731 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1732 struct stat st;
1734 if (fstat(fd, &st) < 0) {
1735 return -errno;
1738 /* Special handling for devdax character devices */
1739 if (S_ISCHR(st.st_mode)) {
1740 g_autofree char *path = NULL;
1741 g_autofree char *rpath = NULL;
1742 struct daxctl_ctx *ctx;
1743 struct daxctl_region *region;
1744 int rc = 0;
1746 path = g_strdup_printf("/sys/dev/char/%d:%d",
1747 major(st.st_rdev), minor(st.st_rdev));
1748 rpath = realpath(path, NULL);
1750 rc = daxctl_new(&ctx);
1751 if (rc) {
1752 return -1;
1755 daxctl_region_foreach(ctx, region) {
1756 if (strstr(rpath, daxctl_region_get_path(region))) {
1757 align = daxctl_region_get_align(region);
1758 break;
1761 daxctl_unref(ctx);
1763 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1765 return align;
1768 static int file_ram_open(const char *path,
1769 const char *region_name,
1770 bool *created,
1771 Error **errp)
1773 char *filename;
1774 char *sanitized_name;
1775 char *c;
1776 int fd = -1;
1778 *created = false;
1779 for (;;) {
1780 fd = open(path, O_RDWR);
1781 if (fd >= 0) {
1782 /* @path names an existing file, use it */
1783 break;
1785 if (errno == ENOENT) {
1786 /* @path names a file that doesn't exist, create it */
1787 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1788 if (fd >= 0) {
1789 *created = true;
1790 break;
1792 } else if (errno == EISDIR) {
1793 /* @path names a directory, create a file there */
1794 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1795 sanitized_name = g_strdup(region_name);
1796 for (c = sanitized_name; *c != '\0'; c++) {
1797 if (*c == '/') {
1798 *c = '_';
1802 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1803 sanitized_name);
1804 g_free(sanitized_name);
1806 fd = mkstemp(filename);
1807 if (fd >= 0) {
1808 unlink(filename);
1809 g_free(filename);
1810 break;
1812 g_free(filename);
1814 if (errno != EEXIST && errno != EINTR) {
1815 error_setg_errno(errp, errno,
1816 "can't open backing store %s for guest RAM",
1817 path);
1818 return -1;
1821 * Try again on EINTR and EEXIST. The latter happens when
1822 * something else creates the file between our two open().
1826 return fd;
1829 static void *file_ram_alloc(RAMBlock *block,
1830 ram_addr_t memory,
1831 int fd,
1832 bool truncate,
1833 Error **errp)
1835 void *area;
1837 block->page_size = qemu_fd_getpagesize(fd);
1838 if (block->mr->align % block->page_size) {
1839 error_setg(errp, "alignment 0x%" PRIx64
1840 " must be multiples of page size 0x%zx",
1841 block->mr->align, block->page_size);
1842 return NULL;
1843 } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1844 error_setg(errp, "alignment 0x%" PRIx64
1845 " must be a power of two", block->mr->align);
1846 return NULL;
1848 block->mr->align = MAX(block->page_size, block->mr->align);
1849 #if defined(__s390x__)
1850 if (kvm_enabled()) {
1851 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1853 #endif
1855 if (memory < block->page_size) {
1856 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1857 "or larger than page size 0x%zx",
1858 memory, block->page_size);
1859 return NULL;
1862 memory = ROUND_UP(memory, block->page_size);
1865 * ftruncate is not supported by hugetlbfs in older
1866 * hosts, so don't bother bailing out on errors.
1867 * If anything goes wrong with it under other filesystems,
1868 * mmap will fail.
1870 * Do not truncate the non-empty backend file to avoid corrupting
1871 * the existing data in the file. Disabling shrinking is not
1872 * enough. For example, the current vNVDIMM implementation stores
1873 * the guest NVDIMM labels at the end of the backend file. If the
1874 * backend file is later extended, QEMU will not be able to find
1875 * those labels. Therefore, extending the non-empty backend file
1876 * is disabled as well.
1878 if (truncate && ftruncate(fd, memory)) {
1879 perror("ftruncate");
1882 area = qemu_ram_mmap(fd, memory, block->mr->align,
1883 block->flags & RAM_SHARED, block->flags & RAM_PMEM);
1884 if (area == MAP_FAILED) {
1885 error_setg_errno(errp, errno,
1886 "unable to map backing store for guest RAM");
1887 return NULL;
1890 block->fd = fd;
1891 return area;
1893 #endif
1895 /* Allocate space within the ram_addr_t space that governs the
1896 * dirty bitmaps.
1897 * Called with the ramlist lock held.
1899 static ram_addr_t find_ram_offset(ram_addr_t size)
1901 RAMBlock *block, *next_block;
1902 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1904 assert(size != 0); /* it would hand out same offset multiple times */
1906 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1907 return 0;
1910 RAMBLOCK_FOREACH(block) {
1911 ram_addr_t candidate, next = RAM_ADDR_MAX;
1913 /* Align blocks to start on a 'long' in the bitmap
1914 * which makes the bitmap sync'ing take the fast path.
1916 candidate = block->offset + block->max_length;
1917 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1919 /* Search for the closest following block
1920 * and find the gap.
1922 RAMBLOCK_FOREACH(next_block) {
1923 if (next_block->offset >= candidate) {
1924 next = MIN(next, next_block->offset);
1928 /* If it fits remember our place and remember the size
1929 * of gap, but keep going so that we might find a smaller
1930 * gap to fill so avoiding fragmentation.
1932 if (next - candidate >= size && next - candidate < mingap) {
1933 offset = candidate;
1934 mingap = next - candidate;
1937 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1940 if (offset == RAM_ADDR_MAX) {
1941 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1942 (uint64_t)size);
1943 abort();
1946 trace_find_ram_offset(size, offset);
1948 return offset;
1951 static unsigned long last_ram_page(void)
1953 RAMBlock *block;
1954 ram_addr_t last = 0;
1956 RCU_READ_LOCK_GUARD();
1957 RAMBLOCK_FOREACH(block) {
1958 last = MAX(last, block->offset + block->max_length);
1960 return last >> TARGET_PAGE_BITS;
1963 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1965 int ret;
1967 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1968 if (!machine_dump_guest_core(current_machine)) {
1969 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1970 if (ret) {
1971 perror("qemu_madvise");
1972 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1973 "but dump_guest_core=off specified\n");
1978 const char *qemu_ram_get_idstr(RAMBlock *rb)
1980 return rb->idstr;
1983 void *qemu_ram_get_host_addr(RAMBlock *rb)
1985 return rb->host;
1988 ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
1990 return rb->offset;
1993 ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
1995 return rb->used_length;
1998 bool qemu_ram_is_shared(RAMBlock *rb)
2000 return rb->flags & RAM_SHARED;
2003 /* Note: Only set at the start of postcopy */
2004 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
2006 return rb->flags & RAM_UF_ZEROPAGE;
2009 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
2011 rb->flags |= RAM_UF_ZEROPAGE;
2014 bool qemu_ram_is_migratable(RAMBlock *rb)
2016 return rb->flags & RAM_MIGRATABLE;
2019 void qemu_ram_set_migratable(RAMBlock *rb)
2021 rb->flags |= RAM_MIGRATABLE;
2024 void qemu_ram_unset_migratable(RAMBlock *rb)
2026 rb->flags &= ~RAM_MIGRATABLE;
2029 /* Called with iothread lock held. */
2030 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
2032 RAMBlock *block;
2034 assert(new_block);
2035 assert(!new_block->idstr[0]);
2037 if (dev) {
2038 char *id = qdev_get_dev_path(dev);
2039 if (id) {
2040 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
2041 g_free(id);
2044 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
2046 RCU_READ_LOCK_GUARD();
2047 RAMBLOCK_FOREACH(block) {
2048 if (block != new_block &&
2049 !strcmp(block->idstr, new_block->idstr)) {
2050 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
2051 new_block->idstr);
2052 abort();
2057 /* Called with iothread lock held. */
2058 void qemu_ram_unset_idstr(RAMBlock *block)
2060 /* FIXME: arch_init.c assumes that this is not called throughout
2061 * migration. Ignore the problem since hot-unplug during migration
2062 * does not work anyway.
2064 if (block) {
2065 memset(block->idstr, 0, sizeof(block->idstr));
2069 size_t qemu_ram_pagesize(RAMBlock *rb)
2071 return rb->page_size;
2074 /* Returns the largest size of page in use */
2075 size_t qemu_ram_pagesize_largest(void)
2077 RAMBlock *block;
2078 size_t largest = 0;
2080 RAMBLOCK_FOREACH(block) {
2081 largest = MAX(largest, qemu_ram_pagesize(block));
2084 return largest;
2087 static int memory_try_enable_merging(void *addr, size_t len)
2089 if (!machine_mem_merge(current_machine)) {
2090 /* disabled by the user */
2091 return 0;
2094 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
2097 /* Only legal before guest might have detected the memory size: e.g. on
2098 * incoming migration, or right after reset.
2100 * As memory core doesn't know how is memory accessed, it is up to
2101 * resize callback to update device state and/or add assertions to detect
2102 * misuse, if necessary.
2104 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
2106 const ram_addr_t unaligned_size = newsize;
2108 assert(block);
2110 newsize = HOST_PAGE_ALIGN(newsize);
2112 if (block->used_length == newsize) {
2114 * We don't have to resize the ram block (which only knows aligned
2115 * sizes), however, we have to notify if the unaligned size changed.
2117 if (unaligned_size != memory_region_size(block->mr)) {
2118 memory_region_set_size(block->mr, unaligned_size);
2119 if (block->resized) {
2120 block->resized(block->idstr, unaligned_size, block->host);
2123 return 0;
2126 if (!(block->flags & RAM_RESIZEABLE)) {
2127 error_setg_errno(errp, EINVAL,
2128 "Length mismatch: %s: 0x" RAM_ADDR_FMT
2129 " in != 0x" RAM_ADDR_FMT, block->idstr,
2130 newsize, block->used_length);
2131 return -EINVAL;
2134 if (block->max_length < newsize) {
2135 error_setg_errno(errp, EINVAL,
2136 "Length too large: %s: 0x" RAM_ADDR_FMT
2137 " > 0x" RAM_ADDR_FMT, block->idstr,
2138 newsize, block->max_length);
2139 return -EINVAL;
2142 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
2143 block->used_length = newsize;
2144 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
2145 DIRTY_CLIENTS_ALL);
2146 memory_region_set_size(block->mr, unaligned_size);
2147 if (block->resized) {
2148 block->resized(block->idstr, unaligned_size, block->host);
2150 return 0;
2154 * Trigger sync on the given ram block for range [start, start + length]
2155 * with the backing store if one is available.
2156 * Otherwise no-op.
2157 * @Note: this is supposed to be a synchronous op.
2159 void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
2161 /* The requested range should fit in within the block range */
2162 g_assert((start + length) <= block->used_length);
2164 #ifdef CONFIG_LIBPMEM
2165 /* The lack of support for pmem should not block the sync */
2166 if (ramblock_is_pmem(block)) {
2167 void *addr = ramblock_ptr(block, start);
2168 pmem_persist(addr, length);
2169 return;
2171 #endif
2172 if (block->fd >= 0) {
2174 * Case there is no support for PMEM or the memory has not been
2175 * specified as persistent (or is not one) - use the msync.
2176 * Less optimal but still achieves the same goal
2178 void *addr = ramblock_ptr(block, start);
2179 if (qemu_msync(addr, length, block->fd)) {
2180 warn_report("%s: failed to sync memory range: start: "
2181 RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
2182 __func__, start, length);
2187 /* Called with ram_list.mutex held */
2188 static void dirty_memory_extend(ram_addr_t old_ram_size,
2189 ram_addr_t new_ram_size)
2191 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
2192 DIRTY_MEMORY_BLOCK_SIZE);
2193 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
2194 DIRTY_MEMORY_BLOCK_SIZE);
2195 int i;
2197 /* Only need to extend if block count increased */
2198 if (new_num_blocks <= old_num_blocks) {
2199 return;
2202 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
2203 DirtyMemoryBlocks *old_blocks;
2204 DirtyMemoryBlocks *new_blocks;
2205 int j;
2207 old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
2208 new_blocks = g_malloc(sizeof(*new_blocks) +
2209 sizeof(new_blocks->blocks[0]) * new_num_blocks);
2211 if (old_num_blocks) {
2212 memcpy(new_blocks->blocks, old_blocks->blocks,
2213 old_num_blocks * sizeof(old_blocks->blocks[0]));
2216 for (j = old_num_blocks; j < new_num_blocks; j++) {
2217 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
2220 qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
2222 if (old_blocks) {
2223 g_free_rcu(old_blocks, rcu);
2228 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
2230 RAMBlock *block;
2231 RAMBlock *last_block = NULL;
2232 ram_addr_t old_ram_size, new_ram_size;
2233 Error *err = NULL;
2235 old_ram_size = last_ram_page();
2237 qemu_mutex_lock_ramlist();
2238 new_block->offset = find_ram_offset(new_block->max_length);
2240 if (!new_block->host) {
2241 if (xen_enabled()) {
2242 xen_ram_alloc(new_block->offset, new_block->max_length,
2243 new_block->mr, &err);
2244 if (err) {
2245 error_propagate(errp, err);
2246 qemu_mutex_unlock_ramlist();
2247 return;
2249 } else {
2250 new_block->host = phys_mem_alloc(new_block->max_length,
2251 &new_block->mr->align, shared);
2252 if (!new_block->host) {
2253 error_setg_errno(errp, errno,
2254 "cannot set up guest memory '%s'",
2255 memory_region_name(new_block->mr));
2256 qemu_mutex_unlock_ramlist();
2257 return;
2259 memory_try_enable_merging(new_block->host, new_block->max_length);
2263 new_ram_size = MAX(old_ram_size,
2264 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
2265 if (new_ram_size > old_ram_size) {
2266 dirty_memory_extend(old_ram_size, new_ram_size);
2268 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2269 * QLIST (which has an RCU-friendly variant) does not have insertion at
2270 * tail, so save the last element in last_block.
2272 RAMBLOCK_FOREACH(block) {
2273 last_block = block;
2274 if (block->max_length < new_block->max_length) {
2275 break;
2278 if (block) {
2279 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
2280 } else if (last_block) {
2281 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
2282 } else { /* list is empty */
2283 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
2285 ram_list.mru_block = NULL;
2287 /* Write list before version */
2288 smp_wmb();
2289 ram_list.version++;
2290 qemu_mutex_unlock_ramlist();
2292 cpu_physical_memory_set_dirty_range(new_block->offset,
2293 new_block->used_length,
2294 DIRTY_CLIENTS_ALL);
2296 if (new_block->host) {
2297 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2298 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2300 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
2301 * Configure it unless the machine is a qtest server, in which case
2302 * KVM is not used and it may be forked (eg for fuzzing purposes).
2304 if (!qtest_enabled()) {
2305 qemu_madvise(new_block->host, new_block->max_length,
2306 QEMU_MADV_DONTFORK);
2308 ram_block_notify_add(new_block->host, new_block->max_length);
2312 #ifdef CONFIG_POSIX
2313 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2314 uint32_t ram_flags, int fd,
2315 Error **errp)
2317 RAMBlock *new_block;
2318 Error *local_err = NULL;
2319 int64_t file_size, file_align;
2321 /* Just support these ram flags by now. */
2322 assert((ram_flags & ~(RAM_SHARED | RAM_PMEM)) == 0);
2324 if (xen_enabled()) {
2325 error_setg(errp, "-mem-path not supported with Xen");
2326 return NULL;
2329 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2330 error_setg(errp,
2331 "host lacks kvm mmu notifiers, -mem-path unsupported");
2332 return NULL;
2335 if (phys_mem_alloc != qemu_anon_ram_alloc) {
2337 * file_ram_alloc() needs to allocate just like
2338 * phys_mem_alloc, but we haven't bothered to provide
2339 * a hook there.
2341 error_setg(errp,
2342 "-mem-path not supported with this accelerator");
2343 return NULL;
2346 size = HOST_PAGE_ALIGN(size);
2347 file_size = get_file_size(fd);
2348 if (file_size > 0 && file_size < size) {
2349 error_setg(errp, "backing store size 0x%" PRIx64
2350 " does not match 'size' option 0x" RAM_ADDR_FMT,
2351 file_size, size);
2352 return NULL;
2355 file_align = get_file_align(fd);
2356 if (file_align > 0 && mr && file_align > mr->align) {
2357 error_setg(errp, "backing store align 0x%" PRIx64
2358 " is larger than 'align' option 0x%" PRIx64,
2359 file_align, mr->align);
2360 return NULL;
2363 new_block = g_malloc0(sizeof(*new_block));
2364 new_block->mr = mr;
2365 new_block->used_length = size;
2366 new_block->max_length = size;
2367 new_block->flags = ram_flags;
2368 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
2369 if (!new_block->host) {
2370 g_free(new_block);
2371 return NULL;
2374 ram_block_add(new_block, &local_err, ram_flags & RAM_SHARED);
2375 if (local_err) {
2376 g_free(new_block);
2377 error_propagate(errp, local_err);
2378 return NULL;
2380 return new_block;
2385 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2386 uint32_t ram_flags, const char *mem_path,
2387 Error **errp)
2389 int fd;
2390 bool created;
2391 RAMBlock *block;
2393 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2394 if (fd < 0) {
2395 return NULL;
2398 block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, errp);
2399 if (!block) {
2400 if (created) {
2401 unlink(mem_path);
2403 close(fd);
2404 return NULL;
2407 return block;
2409 #endif
2411 static
2412 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2413 void (*resized)(const char*,
2414 uint64_t length,
2415 void *host),
2416 void *host, bool resizeable, bool share,
2417 MemoryRegion *mr, Error **errp)
2419 RAMBlock *new_block;
2420 Error *local_err = NULL;
2422 size = HOST_PAGE_ALIGN(size);
2423 max_size = HOST_PAGE_ALIGN(max_size);
2424 new_block = g_malloc0(sizeof(*new_block));
2425 new_block->mr = mr;
2426 new_block->resized = resized;
2427 new_block->used_length = size;
2428 new_block->max_length = max_size;
2429 assert(max_size >= size);
2430 new_block->fd = -1;
2431 new_block->page_size = qemu_real_host_page_size;
2432 new_block->host = host;
2433 if (host) {
2434 new_block->flags |= RAM_PREALLOC;
2436 if (resizeable) {
2437 new_block->flags |= RAM_RESIZEABLE;
2439 ram_block_add(new_block, &local_err, share);
2440 if (local_err) {
2441 g_free(new_block);
2442 error_propagate(errp, local_err);
2443 return NULL;
2445 return new_block;
2448 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2449 MemoryRegion *mr, Error **errp)
2451 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2452 false, mr, errp);
2455 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2456 MemoryRegion *mr, Error **errp)
2458 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2459 share, mr, errp);
2462 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2463 void (*resized)(const char*,
2464 uint64_t length,
2465 void *host),
2466 MemoryRegion *mr, Error **errp)
2468 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2469 false, mr, errp);
2472 static void reclaim_ramblock(RAMBlock *block)
2474 if (block->flags & RAM_PREALLOC) {
2476 } else if (xen_enabled()) {
2477 xen_invalidate_map_cache_entry(block->host);
2478 #ifndef _WIN32
2479 } else if (block->fd >= 0) {
2480 qemu_ram_munmap(block->fd, block->host, block->max_length);
2481 close(block->fd);
2482 #endif
2483 } else {
2484 qemu_anon_ram_free(block->host, block->max_length);
2486 g_free(block);
2489 void qemu_ram_free(RAMBlock *block)
2491 if (!block) {
2492 return;
2495 if (block->host) {
2496 ram_block_notify_remove(block->host, block->max_length);
2499 qemu_mutex_lock_ramlist();
2500 QLIST_REMOVE_RCU(block, next);
2501 ram_list.mru_block = NULL;
2502 /* Write list before version */
2503 smp_wmb();
2504 ram_list.version++;
2505 call_rcu(block, reclaim_ramblock, rcu);
2506 qemu_mutex_unlock_ramlist();
2509 #ifndef _WIN32
2510 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2512 RAMBlock *block;
2513 ram_addr_t offset;
2514 int flags;
2515 void *area, *vaddr;
2517 RAMBLOCK_FOREACH(block) {
2518 offset = addr - block->offset;
2519 if (offset < block->max_length) {
2520 vaddr = ramblock_ptr(block, offset);
2521 if (block->flags & RAM_PREALLOC) {
2523 } else if (xen_enabled()) {
2524 abort();
2525 } else {
2526 flags = MAP_FIXED;
2527 if (block->fd >= 0) {
2528 flags |= (block->flags & RAM_SHARED ?
2529 MAP_SHARED : MAP_PRIVATE);
2530 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2531 flags, block->fd, offset);
2532 } else {
2534 * Remap needs to match alloc. Accelerators that
2535 * set phys_mem_alloc never remap. If they did,
2536 * we'd need a remap hook here.
2538 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2540 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2541 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2542 flags, -1, 0);
2544 if (area != vaddr) {
2545 error_report("Could not remap addr: "
2546 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2547 length, addr);
2548 exit(1);
2550 memory_try_enable_merging(vaddr, length);
2551 qemu_ram_setup_dump(vaddr, length);
2556 #endif /* !_WIN32 */
2558 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2559 * This should not be used for general purpose DMA. Use address_space_map
2560 * or address_space_rw instead. For local memory (e.g. video ram) that the
2561 * device owns, use memory_region_get_ram_ptr.
2563 * Called within RCU critical section.
2565 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2567 RAMBlock *block = ram_block;
2569 if (block == NULL) {
2570 block = qemu_get_ram_block(addr);
2571 addr -= block->offset;
2574 if (xen_enabled() && block->host == NULL) {
2575 /* We need to check if the requested address is in the RAM
2576 * because we don't want to map the entire memory in QEMU.
2577 * In that case just map until the end of the page.
2579 if (block->offset == 0) {
2580 return xen_map_cache(addr, 0, 0, false);
2583 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2585 return ramblock_ptr(block, addr);
2588 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2589 * but takes a size argument.
2591 * Called within RCU critical section.
2593 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2594 hwaddr *size, bool lock)
2596 RAMBlock *block = ram_block;
2597 if (*size == 0) {
2598 return NULL;
2601 if (block == NULL) {
2602 block = qemu_get_ram_block(addr);
2603 addr -= block->offset;
2605 *size = MIN(*size, block->max_length - addr);
2607 if (xen_enabled() && block->host == NULL) {
2608 /* We need to check if the requested address is in the RAM
2609 * because we don't want to map the entire memory in QEMU.
2610 * In that case just map the requested area.
2612 if (block->offset == 0) {
2613 return xen_map_cache(addr, *size, lock, lock);
2616 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2619 return ramblock_ptr(block, addr);
2622 /* Return the offset of a hostpointer within a ramblock */
2623 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2625 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2626 assert((uintptr_t)host >= (uintptr_t)rb->host);
2627 assert(res < rb->max_length);
2629 return res;
2633 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2634 * in that RAMBlock.
2636 * ptr: Host pointer to look up
2637 * round_offset: If true round the result offset down to a page boundary
2638 * *ram_addr: set to result ram_addr
2639 * *offset: set to result offset within the RAMBlock
2641 * Returns: RAMBlock (or NULL if not found)
2643 * By the time this function returns, the returned pointer is not protected
2644 * by RCU anymore. If the caller is not within an RCU critical section and
2645 * does not hold the iothread lock, it must have other means of protecting the
2646 * pointer, such as a reference to the region that includes the incoming
2647 * ram_addr_t.
2649 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2650 ram_addr_t *offset)
2652 RAMBlock *block;
2653 uint8_t *host = ptr;
2655 if (xen_enabled()) {
2656 ram_addr_t ram_addr;
2657 RCU_READ_LOCK_GUARD();
2658 ram_addr = xen_ram_addr_from_mapcache(ptr);
2659 block = qemu_get_ram_block(ram_addr);
2660 if (block) {
2661 *offset = ram_addr - block->offset;
2663 return block;
2666 RCU_READ_LOCK_GUARD();
2667 block = qatomic_rcu_read(&ram_list.mru_block);
2668 if (block && block->host && host - block->host < block->max_length) {
2669 goto found;
2672 RAMBLOCK_FOREACH(block) {
2673 /* This case append when the block is not mapped. */
2674 if (block->host == NULL) {
2675 continue;
2677 if (host - block->host < block->max_length) {
2678 goto found;
2682 return NULL;
2684 found:
2685 *offset = (host - block->host);
2686 if (round_offset) {
2687 *offset &= TARGET_PAGE_MASK;
2689 return block;
2693 * Finds the named RAMBlock
2695 * name: The name of RAMBlock to find
2697 * Returns: RAMBlock (or NULL if not found)
2699 RAMBlock *qemu_ram_block_by_name(const char *name)
2701 RAMBlock *block;
2703 RAMBLOCK_FOREACH(block) {
2704 if (!strcmp(name, block->idstr)) {
2705 return block;
2709 return NULL;
2712 /* Some of the softmmu routines need to translate from a host pointer
2713 (typically a TLB entry) back to a ram offset. */
2714 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2716 RAMBlock *block;
2717 ram_addr_t offset;
2719 block = qemu_ram_block_from_host(ptr, false, &offset);
2720 if (!block) {
2721 return RAM_ADDR_INVALID;
2724 return block->offset + offset;
2727 /* Generate a debug exception if a watchpoint has been hit. */
2728 void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
2729 MemTxAttrs attrs, int flags, uintptr_t ra)
2731 CPUClass *cc = CPU_GET_CLASS(cpu);
2732 CPUWatchpoint *wp;
2734 assert(tcg_enabled());
2735 if (cpu->watchpoint_hit) {
2737 * We re-entered the check after replacing the TB.
2738 * Now raise the debug interrupt so that it will
2739 * trigger after the current instruction.
2741 qemu_mutex_lock_iothread();
2742 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2743 qemu_mutex_unlock_iothread();
2744 return;
2747 addr = cc->adjust_watchpoint_address(cpu, addr, len);
2748 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2749 if (watchpoint_address_matches(wp, addr, len)
2750 && (wp->flags & flags)) {
2751 if (replay_running_debug()) {
2753 * Don't process the watchpoints when we are
2754 * in a reverse debugging operation.
2756 replay_breakpoint();
2757 return;
2759 if (flags == BP_MEM_READ) {
2760 wp->flags |= BP_WATCHPOINT_HIT_READ;
2761 } else {
2762 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2764 wp->hitaddr = MAX(addr, wp->vaddr);
2765 wp->hitattrs = attrs;
2766 if (!cpu->watchpoint_hit) {
2767 if (wp->flags & BP_CPU &&
2768 !cc->debug_check_watchpoint(cpu, wp)) {
2769 wp->flags &= ~BP_WATCHPOINT_HIT;
2770 continue;
2772 cpu->watchpoint_hit = wp;
2774 mmap_lock();
2775 tb_check_watchpoint(cpu, ra);
2776 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2777 cpu->exception_index = EXCP_DEBUG;
2778 mmap_unlock();
2779 cpu_loop_exit_restore(cpu, ra);
2780 } else {
2781 /* Force execution of one insn next time. */
2782 cpu->cflags_next_tb = 1 | curr_cflags();
2783 mmap_unlock();
2784 if (ra) {
2785 cpu_restore_state(cpu, ra, true);
2787 cpu_loop_exit_noexc(cpu);
2790 } else {
2791 wp->flags &= ~BP_WATCHPOINT_HIT;
2796 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2797 MemTxAttrs attrs, void *buf, hwaddr len);
2798 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2799 const void *buf, hwaddr len);
2800 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2801 bool is_write, MemTxAttrs attrs);
2803 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2804 unsigned len, MemTxAttrs attrs)
2806 subpage_t *subpage = opaque;
2807 uint8_t buf[8];
2808 MemTxResult res;
2810 #if defined(DEBUG_SUBPAGE)
2811 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2812 subpage, len, addr);
2813 #endif
2814 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2815 if (res) {
2816 return res;
2818 *data = ldn_p(buf, len);
2819 return MEMTX_OK;
2822 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2823 uint64_t value, unsigned len, MemTxAttrs attrs)
2825 subpage_t *subpage = opaque;
2826 uint8_t buf[8];
2828 #if defined(DEBUG_SUBPAGE)
2829 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2830 " value %"PRIx64"\n",
2831 __func__, subpage, len, addr, value);
2832 #endif
2833 stn_p(buf, len, value);
2834 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2837 static bool subpage_accepts(void *opaque, hwaddr addr,
2838 unsigned len, bool is_write,
2839 MemTxAttrs attrs)
2841 subpage_t *subpage = opaque;
2842 #if defined(DEBUG_SUBPAGE)
2843 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2844 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2845 #endif
2847 return flatview_access_valid(subpage->fv, addr + subpage->base,
2848 len, is_write, attrs);
2851 static const MemoryRegionOps subpage_ops = {
2852 .read_with_attrs = subpage_read,
2853 .write_with_attrs = subpage_write,
2854 .impl.min_access_size = 1,
2855 .impl.max_access_size = 8,
2856 .valid.min_access_size = 1,
2857 .valid.max_access_size = 8,
2858 .valid.accepts = subpage_accepts,
2859 .endianness = DEVICE_NATIVE_ENDIAN,
2862 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2863 uint16_t section)
2865 int idx, eidx;
2867 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2868 return -1;
2869 idx = SUBPAGE_IDX(start);
2870 eidx = SUBPAGE_IDX(end);
2871 #if defined(DEBUG_SUBPAGE)
2872 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2873 __func__, mmio, start, end, idx, eidx, section);
2874 #endif
2875 for (; idx <= eidx; idx++) {
2876 mmio->sub_section[idx] = section;
2879 return 0;
2882 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2884 subpage_t *mmio;
2886 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2887 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2888 mmio->fv = fv;
2889 mmio->base = base;
2890 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2891 NULL, TARGET_PAGE_SIZE);
2892 mmio->iomem.subpage = true;
2893 #if defined(DEBUG_SUBPAGE)
2894 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2895 mmio, base, TARGET_PAGE_SIZE);
2896 #endif
2898 return mmio;
2901 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2903 assert(fv);
2904 MemoryRegionSection section = {
2905 .fv = fv,
2906 .mr = mr,
2907 .offset_within_address_space = 0,
2908 .offset_within_region = 0,
2909 .size = int128_2_64(),
2912 return phys_section_add(map, &section);
2915 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2916 hwaddr index, MemTxAttrs attrs)
2918 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2919 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2920 AddressSpaceDispatch *d = qatomic_rcu_read(&cpuas->memory_dispatch);
2921 MemoryRegionSection *sections = d->map.sections;
2923 return &sections[index & ~TARGET_PAGE_MASK];
2926 static void io_mem_init(void)
2928 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2929 NULL, UINT64_MAX);
2932 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2934 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2935 uint16_t n;
2937 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2938 assert(n == PHYS_SECTION_UNASSIGNED);
2940 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2942 return d;
2945 void address_space_dispatch_free(AddressSpaceDispatch *d)
2947 phys_sections_free(&d->map);
2948 g_free(d);
2951 static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2955 static void tcg_log_global_after_sync(MemoryListener *listener)
2957 CPUAddressSpace *cpuas;
2959 /* Wait for the CPU to end the current TB. This avoids the following
2960 * incorrect race:
2962 * vCPU migration
2963 * ---------------------- -------------------------
2964 * TLB check -> slow path
2965 * notdirty_mem_write
2966 * write to RAM
2967 * mark dirty
2968 * clear dirty flag
2969 * TLB check -> fast path
2970 * read memory
2971 * write to RAM
2973 * by pushing the migration thread's memory read after the vCPU thread has
2974 * written the memory.
2976 if (replay_mode == REPLAY_MODE_NONE) {
2978 * VGA can make calls to this function while updating the screen.
2979 * In record/replay mode this causes a deadlock, because
2980 * run_on_cpu waits for rr mutex. Therefore no races are possible
2981 * in this case and no need for making run_on_cpu when
2982 * record/replay is not enabled.
2984 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2985 run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2989 static void tcg_commit(MemoryListener *listener)
2991 CPUAddressSpace *cpuas;
2992 AddressSpaceDispatch *d;
2994 assert(tcg_enabled());
2995 /* since each CPU stores ram addresses in its TLB cache, we must
2996 reset the modified entries */
2997 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2998 cpu_reloading_memory_map();
2999 /* The CPU and TLB are protected by the iothread lock.
3000 * We reload the dispatch pointer now because cpu_reloading_memory_map()
3001 * may have split the RCU critical section.
3003 d = address_space_to_dispatch(cpuas->as);
3004 qatomic_rcu_set(&cpuas->memory_dispatch, d);
3005 tlb_flush(cpuas->cpu);
3008 static void memory_map_init(void)
3010 system_memory = g_malloc(sizeof(*system_memory));
3012 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
3013 address_space_init(&address_space_memory, system_memory, "memory");
3015 system_io = g_malloc(sizeof(*system_io));
3016 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
3017 65536);
3018 address_space_init(&address_space_io, system_io, "I/O");
3021 MemoryRegion *get_system_memory(void)
3023 return system_memory;
3026 MemoryRegion *get_system_io(void)
3028 return system_io;
3031 #endif /* !defined(CONFIG_USER_ONLY) */
3033 /* physical memory access (slow version, mainly for debug) */
3034 #if defined(CONFIG_USER_ONLY)
3035 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3036 void *ptr, target_ulong len, bool is_write)
3038 int flags;
3039 target_ulong l, page;
3040 void * p;
3041 uint8_t *buf = ptr;
3043 while (len > 0) {
3044 page = addr & TARGET_PAGE_MASK;
3045 l = (page + TARGET_PAGE_SIZE) - addr;
3046 if (l > len)
3047 l = len;
3048 flags = page_get_flags(page);
3049 if (!(flags & PAGE_VALID))
3050 return -1;
3051 if (is_write) {
3052 if (!(flags & PAGE_WRITE))
3053 return -1;
3054 /* XXX: this code should not depend on lock_user */
3055 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
3056 return -1;
3057 memcpy(p, buf, l);
3058 unlock_user(p, addr, l);
3059 } else {
3060 if (!(flags & PAGE_READ))
3061 return -1;
3062 /* XXX: this code should not depend on lock_user */
3063 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
3064 return -1;
3065 memcpy(buf, p, l);
3066 unlock_user(p, addr, 0);
3068 len -= l;
3069 buf += l;
3070 addr += l;
3072 return 0;
3075 #else
3077 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
3078 hwaddr length)
3080 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
3081 addr += memory_region_get_ram_addr(mr);
3083 /* No early return if dirty_log_mask is or becomes 0, because
3084 * cpu_physical_memory_set_dirty_range will still call
3085 * xen_modified_memory.
3087 if (dirty_log_mask) {
3088 dirty_log_mask =
3089 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
3091 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
3092 assert(tcg_enabled());
3093 tb_invalidate_phys_range(addr, addr + length);
3094 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
3096 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
3099 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
3102 * In principle this function would work on other memory region types too,
3103 * but the ROM device use case is the only one where this operation is
3104 * necessary. Other memory regions should use the
3105 * address_space_read/write() APIs.
3107 assert(memory_region_is_romd(mr));
3109 invalidate_and_set_dirty(mr, addr, size);
3112 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
3114 unsigned access_size_max = mr->ops->valid.max_access_size;
3116 /* Regions are assumed to support 1-4 byte accesses unless
3117 otherwise specified. */
3118 if (access_size_max == 0) {
3119 access_size_max = 4;
3122 /* Bound the maximum access by the alignment of the address. */
3123 if (!mr->ops->impl.unaligned) {
3124 unsigned align_size_max = addr & -addr;
3125 if (align_size_max != 0 && align_size_max < access_size_max) {
3126 access_size_max = align_size_max;
3130 /* Don't attempt accesses larger than the maximum. */
3131 if (l > access_size_max) {
3132 l = access_size_max;
3134 l = pow2floor(l);
3136 return l;
3139 static bool prepare_mmio_access(MemoryRegion *mr)
3141 bool unlocked = !qemu_mutex_iothread_locked();
3142 bool release_lock = false;
3144 if (unlocked) {
3145 qemu_mutex_lock_iothread();
3146 unlocked = false;
3147 release_lock = true;
3149 if (mr->flush_coalesced_mmio) {
3150 if (unlocked) {
3151 qemu_mutex_lock_iothread();
3153 qemu_flush_coalesced_mmio_buffer();
3154 if (unlocked) {
3155 qemu_mutex_unlock_iothread();
3159 return release_lock;
3162 /* Called within RCU critical section. */
3163 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
3164 MemTxAttrs attrs,
3165 const void *ptr,
3166 hwaddr len, hwaddr addr1,
3167 hwaddr l, MemoryRegion *mr)
3169 uint8_t *ram_ptr;
3170 uint64_t val;
3171 MemTxResult result = MEMTX_OK;
3172 bool release_lock = false;
3173 const uint8_t *buf = ptr;
3175 for (;;) {
3176 if (!memory_access_is_direct(mr, true)) {
3177 release_lock |= prepare_mmio_access(mr);
3178 l = memory_access_size(mr, l, addr1);
3179 /* XXX: could force current_cpu to NULL to avoid
3180 potential bugs */
3181 val = ldn_he_p(buf, l);
3182 result |= memory_region_dispatch_write(mr, addr1, val,
3183 size_memop(l), attrs);
3184 } else {
3185 /* RAM case */
3186 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3187 memcpy(ram_ptr, buf, l);
3188 invalidate_and_set_dirty(mr, addr1, l);
3191 if (release_lock) {
3192 qemu_mutex_unlock_iothread();
3193 release_lock = false;
3196 len -= l;
3197 buf += l;
3198 addr += l;
3200 if (!len) {
3201 break;
3204 l = len;
3205 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
3208 return result;
3211 /* Called from RCU critical section. */
3212 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
3213 const void *buf, hwaddr len)
3215 hwaddr l;
3216 hwaddr addr1;
3217 MemoryRegion *mr;
3218 MemTxResult result = MEMTX_OK;
3220 l = len;
3221 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
3222 result = flatview_write_continue(fv, addr, attrs, buf, len,
3223 addr1, l, mr);
3225 return result;
3228 /* Called within RCU critical section. */
3229 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
3230 MemTxAttrs attrs, void *ptr,
3231 hwaddr len, hwaddr addr1, hwaddr l,
3232 MemoryRegion *mr)
3234 uint8_t *ram_ptr;
3235 uint64_t val;
3236 MemTxResult result = MEMTX_OK;
3237 bool release_lock = false;
3238 uint8_t *buf = ptr;
3240 for (;;) {
3241 if (!memory_access_is_direct(mr, false)) {
3242 /* I/O case */
3243 release_lock |= prepare_mmio_access(mr);
3244 l = memory_access_size(mr, l, addr1);
3245 result |= memory_region_dispatch_read(mr, addr1, &val,
3246 size_memop(l), attrs);
3247 stn_he_p(buf, l, val);
3248 } else {
3249 /* RAM case */
3250 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3251 memcpy(buf, ram_ptr, l);
3254 if (release_lock) {
3255 qemu_mutex_unlock_iothread();
3256 release_lock = false;
3259 len -= l;
3260 buf += l;
3261 addr += l;
3263 if (!len) {
3264 break;
3267 l = len;
3268 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3271 return result;
3274 /* Called from RCU critical section. */
3275 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
3276 MemTxAttrs attrs, void *buf, hwaddr len)
3278 hwaddr l;
3279 hwaddr addr1;
3280 MemoryRegion *mr;
3282 l = len;
3283 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3284 return flatview_read_continue(fv, addr, attrs, buf, len,
3285 addr1, l, mr);
3288 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3289 MemTxAttrs attrs, void *buf, hwaddr len)
3291 MemTxResult result = MEMTX_OK;
3292 FlatView *fv;
3294 if (len > 0) {
3295 RCU_READ_LOCK_GUARD();
3296 fv = address_space_to_flatview(as);
3297 result = flatview_read(fv, addr, attrs, buf, len);
3300 return result;
3303 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
3304 MemTxAttrs attrs,
3305 const void *buf, hwaddr len)
3307 MemTxResult result = MEMTX_OK;
3308 FlatView *fv;
3310 if (len > 0) {
3311 RCU_READ_LOCK_GUARD();
3312 fv = address_space_to_flatview(as);
3313 result = flatview_write(fv, addr, attrs, buf, len);
3316 return result;
3319 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3320 void *buf, hwaddr len, bool is_write)
3322 if (is_write) {
3323 return address_space_write(as, addr, attrs, buf, len);
3324 } else {
3325 return address_space_read_full(as, addr, attrs, buf, len);
3329 void cpu_physical_memory_rw(hwaddr addr, void *buf,
3330 hwaddr len, bool is_write)
3332 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3333 buf, len, is_write);
3336 enum write_rom_type {
3337 WRITE_DATA,
3338 FLUSH_CACHE,
3341 static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
3342 hwaddr addr,
3343 MemTxAttrs attrs,
3344 const void *ptr,
3345 hwaddr len,
3346 enum write_rom_type type)
3348 hwaddr l;
3349 uint8_t *ram_ptr;
3350 hwaddr addr1;
3351 MemoryRegion *mr;
3352 const uint8_t *buf = ptr;
3354 RCU_READ_LOCK_GUARD();
3355 while (len > 0) {
3356 l = len;
3357 mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
3359 if (!(memory_region_is_ram(mr) ||
3360 memory_region_is_romd(mr))) {
3361 l = memory_access_size(mr, l, addr1);
3362 } else {
3363 /* ROM/RAM case */
3364 ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3365 switch (type) {
3366 case WRITE_DATA:
3367 memcpy(ram_ptr, buf, l);
3368 invalidate_and_set_dirty(mr, addr1, l);
3369 break;
3370 case FLUSH_CACHE:
3371 flush_icache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr + l);
3372 break;
3375 len -= l;
3376 buf += l;
3377 addr += l;
3379 return MEMTX_OK;
3382 /* used for ROM loading : can write in RAM and ROM */
3383 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
3384 MemTxAttrs attrs,
3385 const void *buf, hwaddr len)
3387 return address_space_write_rom_internal(as, addr, attrs,
3388 buf, len, WRITE_DATA);
3391 void cpu_flush_icache_range(hwaddr start, hwaddr len)
3394 * This function should do the same thing as an icache flush that was
3395 * triggered from within the guest. For TCG we are always cache coherent,
3396 * so there is no need to flush anything. For KVM / Xen we need to flush
3397 * the host's instruction cache at least.
3399 if (tcg_enabled()) {
3400 return;
3403 address_space_write_rom_internal(&address_space_memory,
3404 start, MEMTXATTRS_UNSPECIFIED,
3405 NULL, len, FLUSH_CACHE);
3408 typedef struct {
3409 MemoryRegion *mr;
3410 void *buffer;
3411 hwaddr addr;
3412 hwaddr len;
3413 bool in_use;
3414 } BounceBuffer;
3416 static BounceBuffer bounce;
3418 typedef struct MapClient {
3419 QEMUBH *bh;
3420 QLIST_ENTRY(MapClient) link;
3421 } MapClient;
3423 QemuMutex map_client_list_lock;
3424 static QLIST_HEAD(, MapClient) map_client_list
3425 = QLIST_HEAD_INITIALIZER(map_client_list);
3427 static void cpu_unregister_map_client_do(MapClient *client)
3429 QLIST_REMOVE(client, link);
3430 g_free(client);
3433 static void cpu_notify_map_clients_locked(void)
3435 MapClient *client;
3437 while (!QLIST_EMPTY(&map_client_list)) {
3438 client = QLIST_FIRST(&map_client_list);
3439 qemu_bh_schedule(client->bh);
3440 cpu_unregister_map_client_do(client);
3444 void cpu_register_map_client(QEMUBH *bh)
3446 MapClient *client = g_malloc(sizeof(*client));
3448 qemu_mutex_lock(&map_client_list_lock);
3449 client->bh = bh;
3450 QLIST_INSERT_HEAD(&map_client_list, client, link);
3451 if (!qatomic_read(&bounce.in_use)) {
3452 cpu_notify_map_clients_locked();
3454 qemu_mutex_unlock(&map_client_list_lock);
3457 void cpu_exec_init_all(void)
3459 qemu_mutex_init(&ram_list.mutex);
3460 /* The data structures we set up here depend on knowing the page size,
3461 * so no more changes can be made after this point.
3462 * In an ideal world, nothing we did before we had finished the
3463 * machine setup would care about the target page size, and we could
3464 * do this much later, rather than requiring board models to state
3465 * up front what their requirements are.
3467 finalize_target_page_bits();
3468 io_mem_init();
3469 memory_map_init();
3470 qemu_mutex_init(&map_client_list_lock);
3473 void cpu_unregister_map_client(QEMUBH *bh)
3475 MapClient *client;
3477 qemu_mutex_lock(&map_client_list_lock);
3478 QLIST_FOREACH(client, &map_client_list, link) {
3479 if (client->bh == bh) {
3480 cpu_unregister_map_client_do(client);
3481 break;
3484 qemu_mutex_unlock(&map_client_list_lock);
3487 static void cpu_notify_map_clients(void)
3489 qemu_mutex_lock(&map_client_list_lock);
3490 cpu_notify_map_clients_locked();
3491 qemu_mutex_unlock(&map_client_list_lock);
3494 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
3495 bool is_write, MemTxAttrs attrs)
3497 MemoryRegion *mr;
3498 hwaddr l, xlat;
3500 while (len > 0) {
3501 l = len;
3502 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3503 if (!memory_access_is_direct(mr, is_write)) {
3504 l = memory_access_size(mr, l, addr);
3505 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3506 return false;
3510 len -= l;
3511 addr += l;
3513 return true;
3516 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3517 hwaddr len, bool is_write,
3518 MemTxAttrs attrs)
3520 FlatView *fv;
3521 bool result;
3523 RCU_READ_LOCK_GUARD();
3524 fv = address_space_to_flatview(as);
3525 result = flatview_access_valid(fv, addr, len, is_write, attrs);
3526 return result;
3529 static hwaddr
3530 flatview_extend_translation(FlatView *fv, hwaddr addr,
3531 hwaddr target_len,
3532 MemoryRegion *mr, hwaddr base, hwaddr len,
3533 bool is_write, MemTxAttrs attrs)
3535 hwaddr done = 0;
3536 hwaddr xlat;
3537 MemoryRegion *this_mr;
3539 for (;;) {
3540 target_len -= len;
3541 addr += len;
3542 done += len;
3543 if (target_len == 0) {
3544 return done;
3547 len = target_len;
3548 this_mr = flatview_translate(fv, addr, &xlat,
3549 &len, is_write, attrs);
3550 if (this_mr != mr || xlat != base + done) {
3551 return done;
3556 /* Map a physical memory region into a host virtual address.
3557 * May map a subset of the requested range, given by and returned in *plen.
3558 * May return NULL if resources needed to perform the mapping are exhausted.
3559 * Use only for reads OR writes - not for read-modify-write operations.
3560 * Use cpu_register_map_client() to know when retrying the map operation is
3561 * likely to succeed.
3563 void *address_space_map(AddressSpace *as,
3564 hwaddr addr,
3565 hwaddr *plen,
3566 bool is_write,
3567 MemTxAttrs attrs)
3569 hwaddr len = *plen;
3570 hwaddr l, xlat;
3571 MemoryRegion *mr;
3572 void *ptr;
3573 FlatView *fv;
3575 if (len == 0) {
3576 return NULL;
3579 l = len;
3580 RCU_READ_LOCK_GUARD();
3581 fv = address_space_to_flatview(as);
3582 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3584 if (!memory_access_is_direct(mr, is_write)) {
3585 if (qatomic_xchg(&bounce.in_use, true)) {
3586 *plen = 0;
3587 return NULL;
3589 /* Avoid unbounded allocations */
3590 l = MIN(l, TARGET_PAGE_SIZE);
3591 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3592 bounce.addr = addr;
3593 bounce.len = l;
3595 memory_region_ref(mr);
3596 bounce.mr = mr;
3597 if (!is_write) {
3598 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3599 bounce.buffer, l);
3602 *plen = l;
3603 return bounce.buffer;
3607 memory_region_ref(mr);
3608 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3609 l, is_write, attrs);
3610 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3612 return ptr;
3615 /* Unmaps a memory region previously mapped by address_space_map().
3616 * Will also mark the memory as dirty if is_write is true. access_len gives
3617 * the amount of memory that was actually read or written by the caller.
3619 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3620 bool is_write, hwaddr access_len)
3622 if (buffer != bounce.buffer) {
3623 MemoryRegion *mr;
3624 ram_addr_t addr1;
3626 mr = memory_region_from_host(buffer, &addr1);
3627 assert(mr != NULL);
3628 if (is_write) {
3629 invalidate_and_set_dirty(mr, addr1, access_len);
3631 if (xen_enabled()) {
3632 xen_invalidate_map_cache_entry(buffer);
3634 memory_region_unref(mr);
3635 return;
3637 if (is_write) {
3638 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3639 bounce.buffer, access_len);
3641 qemu_vfree(bounce.buffer);
3642 bounce.buffer = NULL;
3643 memory_region_unref(bounce.mr);
3644 qatomic_mb_set(&bounce.in_use, false);
3645 cpu_notify_map_clients();
3648 void *cpu_physical_memory_map(hwaddr addr,
3649 hwaddr *plen,
3650 bool is_write)
3652 return address_space_map(&address_space_memory, addr, plen, is_write,
3653 MEMTXATTRS_UNSPECIFIED);
3656 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3657 bool is_write, hwaddr access_len)
3659 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3662 #define ARG1_DECL AddressSpace *as
3663 #define ARG1 as
3664 #define SUFFIX
3665 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3666 #define RCU_READ_LOCK(...) rcu_read_lock()
3667 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3668 #include "memory_ldst.c.inc"
3670 int64_t address_space_cache_init(MemoryRegionCache *cache,
3671 AddressSpace *as,
3672 hwaddr addr,
3673 hwaddr len,
3674 bool is_write)
3676 AddressSpaceDispatch *d;
3677 hwaddr l;
3678 MemoryRegion *mr;
3680 assert(len > 0);
3682 l = len;
3683 cache->fv = address_space_get_flatview(as);
3684 d = flatview_to_dispatch(cache->fv);
3685 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3687 mr = cache->mrs.mr;
3688 memory_region_ref(mr);
3689 if (memory_access_is_direct(mr, is_write)) {
3690 /* We don't care about the memory attributes here as we're only
3691 * doing this if we found actual RAM, which behaves the same
3692 * regardless of attributes; so UNSPECIFIED is fine.
3694 l = flatview_extend_translation(cache->fv, addr, len, mr,
3695 cache->xlat, l, is_write,
3696 MEMTXATTRS_UNSPECIFIED);
3697 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3698 } else {
3699 cache->ptr = NULL;
3702 cache->len = l;
3703 cache->is_write = is_write;
3704 return l;
3707 void address_space_cache_invalidate(MemoryRegionCache *cache,
3708 hwaddr addr,
3709 hwaddr access_len)
3711 assert(cache->is_write);
3712 if (likely(cache->ptr)) {
3713 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3717 void address_space_cache_destroy(MemoryRegionCache *cache)
3719 if (!cache->mrs.mr) {
3720 return;
3723 if (xen_enabled()) {
3724 xen_invalidate_map_cache_entry(cache->ptr);
3726 memory_region_unref(cache->mrs.mr);
3727 flatview_unref(cache->fv);
3728 cache->mrs.mr = NULL;
3729 cache->fv = NULL;
3732 /* Called from RCU critical section. This function has the same
3733 * semantics as address_space_translate, but it only works on a
3734 * predefined range of a MemoryRegion that was mapped with
3735 * address_space_cache_init.
3737 static inline MemoryRegion *address_space_translate_cached(
3738 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3739 hwaddr *plen, bool is_write, MemTxAttrs attrs)
3741 MemoryRegionSection section;
3742 MemoryRegion *mr;
3743 IOMMUMemoryRegion *iommu_mr;
3744 AddressSpace *target_as;
3746 assert(!cache->ptr);
3747 *xlat = addr + cache->xlat;
3749 mr = cache->mrs.mr;
3750 iommu_mr = memory_region_get_iommu(mr);
3751 if (!iommu_mr) {
3752 /* MMIO region. */
3753 return mr;
3756 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3757 NULL, is_write, true,
3758 &target_as, attrs);
3759 return section.mr;
3762 /* Called from RCU critical section. address_space_read_cached uses this
3763 * out of line function when the target is an MMIO or IOMMU region.
3765 MemTxResult
3766 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3767 void *buf, hwaddr len)
3769 hwaddr addr1, l;
3770 MemoryRegion *mr;
3772 l = len;
3773 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3774 MEMTXATTRS_UNSPECIFIED);
3775 return flatview_read_continue(cache->fv,
3776 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3777 addr1, l, mr);
3780 /* Called from RCU critical section. address_space_write_cached uses this
3781 * out of line function when the target is an MMIO or IOMMU region.
3783 MemTxResult
3784 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3785 const void *buf, hwaddr len)
3787 hwaddr addr1, l;
3788 MemoryRegion *mr;
3790 l = len;
3791 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3792 MEMTXATTRS_UNSPECIFIED);
3793 return flatview_write_continue(cache->fv,
3794 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3795 addr1, l, mr);
3798 #define ARG1_DECL MemoryRegionCache *cache
3799 #define ARG1 cache
3800 #define SUFFIX _cached_slow
3801 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3802 #define RCU_READ_LOCK() ((void)0)
3803 #define RCU_READ_UNLOCK() ((void)0)
3804 #include "memory_ldst.c.inc"
3806 /* virtual memory access for debug (includes writing to ROM) */
3807 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3808 void *ptr, target_ulong len, bool is_write)
3810 hwaddr phys_addr;
3811 target_ulong l, page;
3812 uint8_t *buf = ptr;
3814 cpu_synchronize_state(cpu);
3815 while (len > 0) {
3816 int asidx;
3817 MemTxAttrs attrs;
3818 MemTxResult res;
3820 page = addr & TARGET_PAGE_MASK;
3821 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3822 asidx = cpu_asidx_from_attrs(cpu, attrs);
3823 /* if no physical page mapped, return an error */
3824 if (phys_addr == -1)
3825 return -1;
3826 l = (page + TARGET_PAGE_SIZE) - addr;
3827 if (l > len)
3828 l = len;
3829 phys_addr += (addr & ~TARGET_PAGE_MASK);
3830 if (is_write) {
3831 res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3832 attrs, buf, l);
3833 } else {
3834 res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3835 attrs, buf, l);
3837 if (res != MEMTX_OK) {
3838 return -1;
3840 len -= l;
3841 buf += l;
3842 addr += l;
3844 return 0;
3848 * Allows code that needs to deal with migration bitmaps etc to still be built
3849 * target independent.
3851 size_t qemu_target_page_size(void)
3853 return TARGET_PAGE_SIZE;
3856 int qemu_target_page_bits(void)
3858 return TARGET_PAGE_BITS;
3861 int qemu_target_page_bits_min(void)
3863 return TARGET_PAGE_BITS_MIN;
3865 #endif
3867 bool target_words_bigendian(void)
3869 #if defined(TARGET_WORDS_BIGENDIAN)
3870 return true;
3871 #else
3872 return false;
3873 #endif
3876 #ifndef CONFIG_USER_ONLY
3877 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3879 MemoryRegion*mr;
3880 hwaddr l = 1;
3881 bool res;
3883 RCU_READ_LOCK_GUARD();
3884 mr = address_space_translate(&address_space_memory,
3885 phys_addr, &phys_addr, &l, false,
3886 MEMTXATTRS_UNSPECIFIED);
3888 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3889 return res;
3892 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3894 RAMBlock *block;
3895 int ret = 0;
3897 RCU_READ_LOCK_GUARD();
3898 RAMBLOCK_FOREACH(block) {
3899 ret = func(block, opaque);
3900 if (ret) {
3901 break;
3904 return ret;
3908 * Unmap pages of memory from start to start+length such that
3909 * they a) read as 0, b) Trigger whatever fault mechanism
3910 * the OS provides for postcopy.
3911 * The pages must be unmapped by the end of the function.
3912 * Returns: 0 on success, none-0 on failure
3915 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3917 int ret = -1;
3919 uint8_t *host_startaddr = rb->host + start;
3921 if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
3922 error_report("ram_block_discard_range: Unaligned start address: %p",
3923 host_startaddr);
3924 goto err;
3927 if ((start + length) <= rb->used_length) {
3928 bool need_madvise, need_fallocate;
3929 if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
3930 error_report("ram_block_discard_range: Unaligned length: %zx",
3931 length);
3932 goto err;
3935 errno = ENOTSUP; /* If we are missing MADVISE etc */
3937 /* The logic here is messy;
3938 * madvise DONTNEED fails for hugepages
3939 * fallocate works on hugepages and shmem
3941 need_madvise = (rb->page_size == qemu_host_page_size);
3942 need_fallocate = rb->fd != -1;
3943 if (need_fallocate) {
3944 /* For a file, this causes the area of the file to be zero'd
3945 * if read, and for hugetlbfs also causes it to be unmapped
3946 * so a userfault will trigger.
3948 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3949 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3950 start, length);
3951 if (ret) {
3952 ret = -errno;
3953 error_report("ram_block_discard_range: Failed to fallocate "
3954 "%s:%" PRIx64 " +%zx (%d)",
3955 rb->idstr, start, length, ret);
3956 goto err;
3958 #else
3959 ret = -ENOSYS;
3960 error_report("ram_block_discard_range: fallocate not available/file"
3961 "%s:%" PRIx64 " +%zx (%d)",
3962 rb->idstr, start, length, ret);
3963 goto err;
3964 #endif
3966 if (need_madvise) {
3967 /* For normal RAM this causes it to be unmapped,
3968 * for shared memory it causes the local mapping to disappear
3969 * and to fall back on the file contents (which we just
3970 * fallocate'd away).
3972 #if defined(CONFIG_MADVISE)
3973 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3974 if (ret) {
3975 ret = -errno;
3976 error_report("ram_block_discard_range: Failed to discard range "
3977 "%s:%" PRIx64 " +%zx (%d)",
3978 rb->idstr, start, length, ret);
3979 goto err;
3981 #else
3982 ret = -ENOSYS;
3983 error_report("ram_block_discard_range: MADVISE not available"
3984 "%s:%" PRIx64 " +%zx (%d)",
3985 rb->idstr, start, length, ret);
3986 goto err;
3987 #endif
3989 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3990 need_madvise, need_fallocate, ret);
3991 } else {
3992 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3993 "/%zx/" RAM_ADDR_FMT")",
3994 rb->idstr, start, length, rb->used_length);
3997 err:
3998 return ret;
4001 bool ramblock_is_pmem(RAMBlock *rb)
4003 return rb->flags & RAM_PMEM;
4006 #endif
4008 void page_size_init(void)
4010 /* NOTE: we can always suppose that qemu_host_page_size >=
4011 TARGET_PAGE_SIZE */
4012 if (qemu_host_page_size == 0) {
4013 qemu_host_page_size = qemu_real_host_page_size;
4015 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
4016 qemu_host_page_size = TARGET_PAGE_SIZE;
4018 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;
4021 #if !defined(CONFIG_USER_ONLY)
4023 static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
4025 if (start == end - 1) {
4026 qemu_printf("\t%3d ", start);
4027 } else {
4028 qemu_printf("\t%3d..%-3d ", start, end - 1);
4030 qemu_printf(" skip=%d ", skip);
4031 if (ptr == PHYS_MAP_NODE_NIL) {
4032 qemu_printf(" ptr=NIL");
4033 } else if (!skip) {
4034 qemu_printf(" ptr=#%d", ptr);
4035 } else {
4036 qemu_printf(" ptr=[%d]", ptr);
4038 qemu_printf("\n");
4041 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
4042 int128_sub((size), int128_one())) : 0)
4044 void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
4046 int i;
4048 qemu_printf(" Dispatch\n");
4049 qemu_printf(" Physical sections\n");
4051 for (i = 0; i < d->map.sections_nb; ++i) {
4052 MemoryRegionSection *s = d->map.sections + i;
4053 const char *names[] = { " [unassigned]", " [not dirty]",
4054 " [ROM]", " [watch]" };
4056 qemu_printf(" #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx
4057 " %s%s%s%s%s",
4059 s->offset_within_address_space,
4060 s->offset_within_address_space + MR_SIZE(s->mr->size),
4061 s->mr->name ? s->mr->name : "(noname)",
4062 i < ARRAY_SIZE(names) ? names[i] : "",
4063 s->mr == root ? " [ROOT]" : "",
4064 s == d->mru_section ? " [MRU]" : "",
4065 s->mr->is_iommu ? " [iommu]" : "");
4067 if (s->mr->alias) {
4068 qemu_printf(" alias=%s", s->mr->alias->name ?
4069 s->mr->alias->name : "noname");
4071 qemu_printf("\n");
4074 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
4075 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
4076 for (i = 0; i < d->map.nodes_nb; ++i) {
4077 int j, jprev;
4078 PhysPageEntry prev;
4079 Node *n = d->map.nodes + i;
4081 qemu_printf(" [%d]\n", i);
4083 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
4084 PhysPageEntry *pe = *n + j;
4086 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
4087 continue;
4090 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
4092 jprev = j;
4093 prev = *pe;
4096 if (jprev != ARRAY_SIZE(*n)) {
4097 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
4103 * If positive, discarding RAM is disabled. If negative, discarding RAM is
4104 * required to work and cannot be disabled.
4106 static int ram_block_discard_disabled;
4108 int ram_block_discard_disable(bool state)
4110 int old;
4112 if (!state) {
4113 qatomic_dec(&ram_block_discard_disabled);
4114 return 0;
4117 do {
4118 old = qatomic_read(&ram_block_discard_disabled);
4119 if (old < 0) {
4120 return -EBUSY;
4122 } while (qatomic_cmpxchg(&ram_block_discard_disabled,
4123 old, old + 1) != old);
4124 return 0;
4127 int ram_block_discard_require(bool state)
4129 int old;
4131 if (!state) {
4132 qatomic_inc(&ram_block_discard_disabled);
4133 return 0;
4136 do {
4137 old = qatomic_read(&ram_block_discard_disabled);
4138 if (old > 0) {
4139 return -EBUSY;
4141 } while (qatomic_cmpxchg(&ram_block_discard_disabled,
4142 old, old - 1) != old);
4143 return 0;
4146 bool ram_block_discard_is_disabled(void)
4148 return qatomic_read(&ram_block_discard_disabled) > 0;
4151 bool ram_block_discard_is_required(void)
4153 return qatomic_read(&ram_block_discard_disabled) < 0;
4156 #endif