migration: not wait RDMA_CM_EVENT_DISCONNECTED event after rdma_disconnect
[qemu/ar7.git] / exec.c
blobaf90e914cf4a5b5e585b5783e898f40673d7a59d
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/>.
19 #include "qemu/osdep.h"
20 #include "qapi/error.h"
22 #include "qemu/cutils.h"
23 #include "cpu.h"
24 #include "exec/exec-all.h"
25 #include "exec/target_page.h"
26 #include "tcg.h"
27 #include "hw/qdev-core.h"
28 #include "hw/qdev-properties.h"
29 #if !defined(CONFIG_USER_ONLY)
30 #include "hw/boards.h"
31 #include "hw/xen/xen.h"
32 #endif
33 #include "sysemu/kvm.h"
34 #include "sysemu/sysemu.h"
35 #include "qemu/timer.h"
36 #include "qemu/config-file.h"
37 #include "qemu/error-report.h"
38 #if defined(CONFIG_USER_ONLY)
39 #include "qemu.h"
40 #else /* !CONFIG_USER_ONLY */
41 #include "hw/hw.h"
42 #include "exec/memory.h"
43 #include "exec/ioport.h"
44 #include "sysemu/dma.h"
45 #include "sysemu/numa.h"
46 #include "sysemu/hw_accel.h"
47 #include "exec/address-spaces.h"
48 #include "sysemu/xen-mapcache.h"
49 #include "trace-root.h"
51 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
52 #include <linux/falloc.h>
53 #endif
55 #endif
56 #include "qemu/rcu_queue.h"
57 #include "qemu/main-loop.h"
58 #include "translate-all.h"
59 #include "sysemu/replay.h"
61 #include "exec/memory-internal.h"
62 #include "exec/ram_addr.h"
63 #include "exec/log.h"
65 #include "migration/vmstate.h"
67 #include "qemu/range.h"
68 #ifndef _WIN32
69 #include "qemu/mmap-alloc.h"
70 #endif
72 #include "monitor/monitor.h"
74 //#define DEBUG_SUBPAGE
76 #if !defined(CONFIG_USER_ONLY)
77 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
78 * are protected by the ramlist lock.
80 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
82 static MemoryRegion *system_memory;
83 static MemoryRegion *system_io;
85 AddressSpace address_space_io;
86 AddressSpace address_space_memory;
88 MemoryRegion io_mem_rom, io_mem_notdirty;
89 static MemoryRegion io_mem_unassigned;
91 /* RAM is pre-allocated and passed into qemu_ram_alloc_from_ptr */
92 #define RAM_PREALLOC (1 << 0)
94 /* RAM is mmap-ed with MAP_SHARED */
95 #define RAM_SHARED (1 << 1)
97 /* Only a portion of RAM (used_length) is actually used, and migrated.
98 * This used_length size can change across reboots.
100 #define RAM_RESIZEABLE (1 << 2)
102 /* UFFDIO_ZEROPAGE is available on this RAMBlock to atomically
103 * zero the page and wake waiting processes.
104 * (Set during postcopy)
106 #define RAM_UF_ZEROPAGE (1 << 3)
108 /* RAM can be migrated */
109 #define RAM_MIGRATABLE (1 << 4)
110 #endif
112 #ifdef TARGET_PAGE_BITS_VARY
113 int target_page_bits;
114 bool target_page_bits_decided;
115 #endif
117 struct CPUTailQ cpus = QTAILQ_HEAD_INITIALIZER(cpus);
118 /* current CPU in the current thread. It is only valid inside
119 cpu_exec() */
120 __thread CPUState *current_cpu;
121 /* 0 = Do not count executed instructions.
122 1 = Precise instruction counting.
123 2 = Adaptive rate instruction counting. */
124 int use_icount;
126 uintptr_t qemu_host_page_size;
127 intptr_t qemu_host_page_mask;
129 bool set_preferred_target_page_bits(int bits)
131 /* The target page size is the lowest common denominator for all
132 * the CPUs in the system, so we can only make it smaller, never
133 * larger. And we can't make it smaller once we've committed to
134 * a particular size.
136 #ifdef TARGET_PAGE_BITS_VARY
137 assert(bits >= TARGET_PAGE_BITS_MIN);
138 if (target_page_bits == 0 || target_page_bits > bits) {
139 if (target_page_bits_decided) {
140 return false;
142 target_page_bits = bits;
144 #endif
145 return true;
148 #if !defined(CONFIG_USER_ONLY)
150 static void finalize_target_page_bits(void)
152 #ifdef TARGET_PAGE_BITS_VARY
153 if (target_page_bits == 0) {
154 target_page_bits = TARGET_PAGE_BITS_MIN;
156 target_page_bits_decided = true;
157 #endif
160 typedef struct PhysPageEntry PhysPageEntry;
162 struct PhysPageEntry {
163 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
164 uint32_t skip : 6;
165 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
166 uint32_t ptr : 26;
169 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
171 /* Size of the L2 (and L3, etc) page tables. */
172 #define ADDR_SPACE_BITS 64
174 #define P_L2_BITS 9
175 #define P_L2_SIZE (1 << P_L2_BITS)
177 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
179 typedef PhysPageEntry Node[P_L2_SIZE];
181 typedef struct PhysPageMap {
182 struct rcu_head rcu;
184 unsigned sections_nb;
185 unsigned sections_nb_alloc;
186 unsigned nodes_nb;
187 unsigned nodes_nb_alloc;
188 Node *nodes;
189 MemoryRegionSection *sections;
190 } PhysPageMap;
192 struct AddressSpaceDispatch {
193 MemoryRegionSection *mru_section;
194 /* This is a multi-level map on the physical address space.
195 * The bottom level has pointers to MemoryRegionSections.
197 PhysPageEntry phys_map;
198 PhysPageMap map;
201 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
202 typedef struct subpage_t {
203 MemoryRegion iomem;
204 FlatView *fv;
205 hwaddr base;
206 uint16_t sub_section[];
207 } subpage_t;
209 #define PHYS_SECTION_UNASSIGNED 0
210 #define PHYS_SECTION_NOTDIRTY 1
211 #define PHYS_SECTION_ROM 2
212 #define PHYS_SECTION_WATCH 3
214 static void io_mem_init(void);
215 static void memory_map_init(void);
216 static void tcg_commit(MemoryListener *listener);
218 static MemoryRegion io_mem_watch;
221 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
222 * @cpu: the CPU whose AddressSpace this is
223 * @as: the AddressSpace itself
224 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
225 * @tcg_as_listener: listener for tracking changes to the AddressSpace
227 struct CPUAddressSpace {
228 CPUState *cpu;
229 AddressSpace *as;
230 struct AddressSpaceDispatch *memory_dispatch;
231 MemoryListener tcg_as_listener;
234 struct DirtyBitmapSnapshot {
235 ram_addr_t start;
236 ram_addr_t end;
237 unsigned long dirty[];
240 #endif
242 #if !defined(CONFIG_USER_ONLY)
244 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
246 static unsigned alloc_hint = 16;
247 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
248 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, alloc_hint);
249 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, map->nodes_nb + nodes);
250 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
251 alloc_hint = map->nodes_nb_alloc;
255 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
257 unsigned i;
258 uint32_t ret;
259 PhysPageEntry e;
260 PhysPageEntry *p;
262 ret = map->nodes_nb++;
263 p = map->nodes[ret];
264 assert(ret != PHYS_MAP_NODE_NIL);
265 assert(ret != map->nodes_nb_alloc);
267 e.skip = leaf ? 0 : 1;
268 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
269 for (i = 0; i < P_L2_SIZE; ++i) {
270 memcpy(&p[i], &e, sizeof(e));
272 return ret;
275 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
276 hwaddr *index, hwaddr *nb, uint16_t leaf,
277 int level)
279 PhysPageEntry *p;
280 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
282 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
283 lp->ptr = phys_map_node_alloc(map, level == 0);
285 p = map->nodes[lp->ptr];
286 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
288 while (*nb && lp < &p[P_L2_SIZE]) {
289 if ((*index & (step - 1)) == 0 && *nb >= step) {
290 lp->skip = 0;
291 lp->ptr = leaf;
292 *index += step;
293 *nb -= step;
294 } else {
295 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
297 ++lp;
301 static void phys_page_set(AddressSpaceDispatch *d,
302 hwaddr index, hwaddr nb,
303 uint16_t leaf)
305 /* Wildly overreserve - it doesn't matter much. */
306 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
308 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
311 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
312 * and update our entry so we can skip it and go directly to the destination.
314 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
316 unsigned valid_ptr = P_L2_SIZE;
317 int valid = 0;
318 PhysPageEntry *p;
319 int i;
321 if (lp->ptr == PHYS_MAP_NODE_NIL) {
322 return;
325 p = nodes[lp->ptr];
326 for (i = 0; i < P_L2_SIZE; i++) {
327 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
328 continue;
331 valid_ptr = i;
332 valid++;
333 if (p[i].skip) {
334 phys_page_compact(&p[i], nodes);
338 /* We can only compress if there's only one child. */
339 if (valid != 1) {
340 return;
343 assert(valid_ptr < P_L2_SIZE);
345 /* Don't compress if it won't fit in the # of bits we have. */
346 if (lp->skip + p[valid_ptr].skip >= (1 << 3)) {
347 return;
350 lp->ptr = p[valid_ptr].ptr;
351 if (!p[valid_ptr].skip) {
352 /* If our only child is a leaf, make this a leaf. */
353 /* By design, we should have made this node a leaf to begin with so we
354 * should never reach here.
355 * But since it's so simple to handle this, let's do it just in case we
356 * change this rule.
358 lp->skip = 0;
359 } else {
360 lp->skip += p[valid_ptr].skip;
364 void address_space_dispatch_compact(AddressSpaceDispatch *d)
366 if (d->phys_map.skip) {
367 phys_page_compact(&d->phys_map, d->map.nodes);
371 static inline bool section_covers_addr(const MemoryRegionSection *section,
372 hwaddr addr)
374 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
375 * the section must cover the entire address space.
377 return int128_gethi(section->size) ||
378 range_covers_byte(section->offset_within_address_space,
379 int128_getlo(section->size), addr);
382 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
384 PhysPageEntry lp = d->phys_map, *p;
385 Node *nodes = d->map.nodes;
386 MemoryRegionSection *sections = d->map.sections;
387 hwaddr index = addr >> TARGET_PAGE_BITS;
388 int i;
390 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
391 if (lp.ptr == PHYS_MAP_NODE_NIL) {
392 return &sections[PHYS_SECTION_UNASSIGNED];
394 p = nodes[lp.ptr];
395 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
398 if (section_covers_addr(&sections[lp.ptr], addr)) {
399 return &sections[lp.ptr];
400 } else {
401 return &sections[PHYS_SECTION_UNASSIGNED];
405 bool memory_region_is_unassigned(MemoryRegion *mr)
407 return mr != &io_mem_rom && mr != &io_mem_notdirty && !mr->rom_device
408 && mr != &io_mem_watch;
411 /* Called from RCU critical section */
412 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
413 hwaddr addr,
414 bool resolve_subpage)
416 MemoryRegionSection *section = atomic_read(&d->mru_section);
417 subpage_t *subpage;
419 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
420 !section_covers_addr(section, addr)) {
421 section = phys_page_find(d, addr);
422 atomic_set(&d->mru_section, section);
424 if (resolve_subpage && section->mr->subpage) {
425 subpage = container_of(section->mr, subpage_t, iomem);
426 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
428 return section;
431 /* Called from RCU critical section */
432 static MemoryRegionSection *
433 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
434 hwaddr *plen, bool resolve_subpage)
436 MemoryRegionSection *section;
437 MemoryRegion *mr;
438 Int128 diff;
440 section = address_space_lookup_region(d, addr, resolve_subpage);
441 /* Compute offset within MemoryRegionSection */
442 addr -= section->offset_within_address_space;
444 /* Compute offset within MemoryRegion */
445 *xlat = addr + section->offset_within_region;
447 mr = section->mr;
449 /* MMIO registers can be expected to perform full-width accesses based only
450 * on their address, without considering adjacent registers that could
451 * decode to completely different MemoryRegions. When such registers
452 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
453 * regions overlap wildly. For this reason we cannot clamp the accesses
454 * here.
456 * If the length is small (as is the case for address_space_ldl/stl),
457 * everything works fine. If the incoming length is large, however,
458 * the caller really has to do the clamping through memory_access_size.
460 if (memory_region_is_ram(mr)) {
461 diff = int128_sub(section->size, int128_make64(addr));
462 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
464 return section;
468 * address_space_translate_iommu - translate an address through an IOMMU
469 * memory region and then through the target address space.
471 * @iommu_mr: the IOMMU memory region that we start the translation from
472 * @addr: the address to be translated through the MMU
473 * @xlat: the translated address offset within the destination memory region.
474 * It cannot be %NULL.
475 * @plen_out: valid read/write length of the translated address. It
476 * cannot be %NULL.
477 * @page_mask_out: page mask for the translated address. This
478 * should only be meaningful for IOMMU translated
479 * addresses, since there may be huge pages that this bit
480 * would tell. It can be %NULL if we don't care about it.
481 * @is_write: whether the translation operation is for write
482 * @is_mmio: whether this can be MMIO, set true if it can
483 * @target_as: the address space targeted by the IOMMU
484 * @attrs: transaction attributes
486 * This function is called from RCU critical section. It is the common
487 * part of flatview_do_translate and address_space_translate_cached.
489 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
490 hwaddr *xlat,
491 hwaddr *plen_out,
492 hwaddr *page_mask_out,
493 bool is_write,
494 bool is_mmio,
495 AddressSpace **target_as,
496 MemTxAttrs attrs)
498 MemoryRegionSection *section;
499 hwaddr page_mask = (hwaddr)-1;
501 do {
502 hwaddr addr = *xlat;
503 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
504 IOMMUTLBEntry iotlb = imrc->translate(iommu_mr, addr, is_write ?
505 IOMMU_WO : IOMMU_RO);
507 if (!(iotlb.perm & (1 << is_write))) {
508 goto unassigned;
511 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
512 | (addr & iotlb.addr_mask));
513 page_mask &= iotlb.addr_mask;
514 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
515 *target_as = iotlb.target_as;
517 section = address_space_translate_internal(
518 address_space_to_dispatch(iotlb.target_as), addr, xlat,
519 plen_out, is_mmio);
521 iommu_mr = memory_region_get_iommu(section->mr);
522 } while (unlikely(iommu_mr));
524 if (page_mask_out) {
525 *page_mask_out = page_mask;
527 return *section;
529 unassigned:
530 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
534 * flatview_do_translate - translate an address in FlatView
536 * @fv: the flat view that we want to translate on
537 * @addr: the address to be translated in above address space
538 * @xlat: the translated address offset within memory region. It
539 * cannot be @NULL.
540 * @plen_out: valid read/write length of the translated address. It
541 * can be @NULL when we don't care about it.
542 * @page_mask_out: page mask for the translated address. This
543 * should only be meaningful for IOMMU translated
544 * addresses, since there may be huge pages that this bit
545 * would tell. It can be @NULL if we don't care about it.
546 * @is_write: whether the translation operation is for write
547 * @is_mmio: whether this can be MMIO, set true if it can
548 * @target_as: the address space targeted by the IOMMU
549 * @attrs: memory transaction attributes
551 * This function is called from RCU critical section
553 static MemoryRegionSection flatview_do_translate(FlatView *fv,
554 hwaddr addr,
555 hwaddr *xlat,
556 hwaddr *plen_out,
557 hwaddr *page_mask_out,
558 bool is_write,
559 bool is_mmio,
560 AddressSpace **target_as,
561 MemTxAttrs attrs)
563 MemoryRegionSection *section;
564 IOMMUMemoryRegion *iommu_mr;
565 hwaddr plen = (hwaddr)(-1);
567 if (!plen_out) {
568 plen_out = &plen;
571 section = address_space_translate_internal(
572 flatview_to_dispatch(fv), addr, xlat,
573 plen_out, is_mmio);
575 iommu_mr = memory_region_get_iommu(section->mr);
576 if (unlikely(iommu_mr)) {
577 return address_space_translate_iommu(iommu_mr, xlat,
578 plen_out, page_mask_out,
579 is_write, is_mmio,
580 target_as, attrs);
582 if (page_mask_out) {
583 /* Not behind an IOMMU, use default page size. */
584 *page_mask_out = ~TARGET_PAGE_MASK;
587 return *section;
590 /* Called from RCU critical section */
591 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
592 bool is_write, MemTxAttrs attrs)
594 MemoryRegionSection section;
595 hwaddr xlat, page_mask;
598 * This can never be MMIO, and we don't really care about plen,
599 * but page mask.
601 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
602 NULL, &page_mask, is_write, false, &as,
603 attrs);
605 /* Illegal translation */
606 if (section.mr == &io_mem_unassigned) {
607 goto iotlb_fail;
610 /* Convert memory region offset into address space offset */
611 xlat += section.offset_within_address_space -
612 section.offset_within_region;
614 return (IOMMUTLBEntry) {
615 .target_as = as,
616 .iova = addr & ~page_mask,
617 .translated_addr = xlat & ~page_mask,
618 .addr_mask = page_mask,
619 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
620 .perm = IOMMU_RW,
623 iotlb_fail:
624 return (IOMMUTLBEntry) {0};
627 /* Called from RCU critical section */
628 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
629 hwaddr *plen, bool is_write,
630 MemTxAttrs attrs)
632 MemoryRegion *mr;
633 MemoryRegionSection section;
634 AddressSpace *as = NULL;
636 /* This can be MMIO, so setup MMIO bit. */
637 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
638 is_write, true, &as, attrs);
639 mr = section.mr;
641 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
642 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
643 *plen = MIN(page, *plen);
646 return mr;
649 /* Called from RCU critical section */
650 MemoryRegionSection *
651 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
652 hwaddr *xlat, hwaddr *plen)
654 MemoryRegionSection *section;
655 AddressSpaceDispatch *d = atomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
657 section = address_space_translate_internal(d, addr, xlat, plen, false);
659 assert(!memory_region_is_iommu(section->mr));
660 return section;
662 #endif
664 #if !defined(CONFIG_USER_ONLY)
666 static int cpu_common_post_load(void *opaque, int version_id)
668 CPUState *cpu = opaque;
670 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
671 version_id is increased. */
672 cpu->interrupt_request &= ~0x01;
673 tlb_flush(cpu);
675 /* loadvm has just updated the content of RAM, bypassing the
676 * usual mechanisms that ensure we flush TBs for writes to
677 * memory we've translated code from. So we must flush all TBs,
678 * which will now be stale.
680 tb_flush(cpu);
682 return 0;
685 static int cpu_common_pre_load(void *opaque)
687 CPUState *cpu = opaque;
689 cpu->exception_index = -1;
691 return 0;
694 static bool cpu_common_exception_index_needed(void *opaque)
696 CPUState *cpu = opaque;
698 return tcg_enabled() && cpu->exception_index != -1;
701 static const VMStateDescription vmstate_cpu_common_exception_index = {
702 .name = "cpu_common/exception_index",
703 .version_id = 1,
704 .minimum_version_id = 1,
705 .needed = cpu_common_exception_index_needed,
706 .fields = (VMStateField[]) {
707 VMSTATE_INT32(exception_index, CPUState),
708 VMSTATE_END_OF_LIST()
712 static bool cpu_common_crash_occurred_needed(void *opaque)
714 CPUState *cpu = opaque;
716 return cpu->crash_occurred;
719 static const VMStateDescription vmstate_cpu_common_crash_occurred = {
720 .name = "cpu_common/crash_occurred",
721 .version_id = 1,
722 .minimum_version_id = 1,
723 .needed = cpu_common_crash_occurred_needed,
724 .fields = (VMStateField[]) {
725 VMSTATE_BOOL(crash_occurred, CPUState),
726 VMSTATE_END_OF_LIST()
730 const VMStateDescription vmstate_cpu_common = {
731 .name = "cpu_common",
732 .version_id = 1,
733 .minimum_version_id = 1,
734 .pre_load = cpu_common_pre_load,
735 .post_load = cpu_common_post_load,
736 .fields = (VMStateField[]) {
737 VMSTATE_UINT32(halted, CPUState),
738 VMSTATE_UINT32(interrupt_request, CPUState),
739 VMSTATE_END_OF_LIST()
741 .subsections = (const VMStateDescription*[]) {
742 &vmstate_cpu_common_exception_index,
743 &vmstate_cpu_common_crash_occurred,
744 NULL
748 #endif
750 CPUState *qemu_get_cpu(int index)
752 CPUState *cpu;
754 CPU_FOREACH(cpu) {
755 if (cpu->cpu_index == index) {
756 return cpu;
760 return NULL;
763 #if !defined(CONFIG_USER_ONLY)
764 void cpu_address_space_init(CPUState *cpu, int asidx,
765 const char *prefix, MemoryRegion *mr)
767 CPUAddressSpace *newas;
768 AddressSpace *as = g_new0(AddressSpace, 1);
769 char *as_name;
771 assert(mr);
772 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
773 address_space_init(as, mr, as_name);
774 g_free(as_name);
776 /* Target code should have set num_ases before calling us */
777 assert(asidx < cpu->num_ases);
779 if (asidx == 0) {
780 /* address space 0 gets the convenience alias */
781 cpu->as = as;
784 /* KVM cannot currently support multiple address spaces. */
785 assert(asidx == 0 || !kvm_enabled());
787 if (!cpu->cpu_ases) {
788 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
791 newas = &cpu->cpu_ases[asidx];
792 newas->cpu = cpu;
793 newas->as = as;
794 if (tcg_enabled()) {
795 newas->tcg_as_listener.commit = tcg_commit;
796 memory_listener_register(&newas->tcg_as_listener, as);
800 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
802 /* Return the AddressSpace corresponding to the specified index */
803 return cpu->cpu_ases[asidx].as;
805 #endif
807 void cpu_exec_unrealizefn(CPUState *cpu)
809 CPUClass *cc = CPU_GET_CLASS(cpu);
811 cpu_list_remove(cpu);
813 if (cc->vmsd != NULL) {
814 vmstate_unregister(NULL, cc->vmsd, cpu);
816 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
817 vmstate_unregister(NULL, &vmstate_cpu_common, cpu);
821 Property cpu_common_props[] = {
822 #ifndef CONFIG_USER_ONLY
823 /* Create a memory property for softmmu CPU object,
824 * so users can wire up its memory. (This can't go in qom/cpu.c
825 * because that file is compiled only once for both user-mode
826 * and system builds.) The default if no link is set up is to use
827 * the system address space.
829 DEFINE_PROP_LINK("memory", CPUState, memory, TYPE_MEMORY_REGION,
830 MemoryRegion *),
831 #endif
832 DEFINE_PROP_END_OF_LIST(),
835 void cpu_exec_initfn(CPUState *cpu)
837 cpu->as = NULL;
838 cpu->num_ases = 0;
840 #ifndef CONFIG_USER_ONLY
841 cpu->thread_id = qemu_get_thread_id();
842 cpu->memory = system_memory;
843 object_ref(OBJECT(cpu->memory));
844 #endif
847 void cpu_exec_realizefn(CPUState *cpu, Error **errp)
849 CPUClass *cc = CPU_GET_CLASS(cpu);
850 static bool tcg_target_initialized;
852 cpu_list_add(cpu);
854 if (tcg_enabled() && !tcg_target_initialized) {
855 tcg_target_initialized = true;
856 cc->tcg_initialize();
859 #ifndef CONFIG_USER_ONLY
860 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
861 vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
863 if (cc->vmsd != NULL) {
864 vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);
866 #endif
869 const char *parse_cpu_model(const char *cpu_model)
871 ObjectClass *oc;
872 CPUClass *cc;
873 gchar **model_pieces;
874 const char *cpu_type;
876 model_pieces = g_strsplit(cpu_model, ",", 2);
878 oc = cpu_class_by_name(CPU_RESOLVING_TYPE, model_pieces[0]);
879 if (oc == NULL) {
880 error_report("unable to find CPU model '%s'", model_pieces[0]);
881 g_strfreev(model_pieces);
882 exit(EXIT_FAILURE);
885 cpu_type = object_class_get_name(oc);
886 cc = CPU_CLASS(oc);
887 cc->parse_features(cpu_type, model_pieces[1], &error_fatal);
888 g_strfreev(model_pieces);
889 return cpu_type;
892 #if defined(CONFIG_USER_ONLY)
893 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
895 mmap_lock();
896 tb_lock();
897 tb_invalidate_phys_page_range(pc, pc + 1, 0);
898 tb_unlock();
899 mmap_unlock();
901 #else
902 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
904 MemTxAttrs attrs;
905 hwaddr phys = cpu_get_phys_page_attrs_debug(cpu, pc, &attrs);
906 int asidx = cpu_asidx_from_attrs(cpu, attrs);
907 if (phys != -1) {
908 /* Locks grabbed by tb_invalidate_phys_addr */
909 tb_invalidate_phys_addr(cpu->cpu_ases[asidx].as,
910 phys | (pc & ~TARGET_PAGE_MASK), attrs);
913 #endif
915 #if defined(CONFIG_USER_ONLY)
916 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
921 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
922 int flags)
924 return -ENOSYS;
927 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
931 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
932 int flags, CPUWatchpoint **watchpoint)
934 return -ENOSYS;
936 #else
937 /* Add a watchpoint. */
938 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
939 int flags, CPUWatchpoint **watchpoint)
941 CPUWatchpoint *wp;
943 /* forbid ranges which are empty or run off the end of the address space */
944 if (len == 0 || (addr + len - 1) < addr) {
945 error_report("tried to set invalid watchpoint at %"
946 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
947 return -EINVAL;
949 wp = g_malloc(sizeof(*wp));
951 wp->vaddr = addr;
952 wp->len = len;
953 wp->flags = flags;
955 /* keep all GDB-injected watchpoints in front */
956 if (flags & BP_GDB) {
957 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
958 } else {
959 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
962 tlb_flush_page(cpu, addr);
964 if (watchpoint)
965 *watchpoint = wp;
966 return 0;
969 /* Remove a specific watchpoint. */
970 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
971 int flags)
973 CPUWatchpoint *wp;
975 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
976 if (addr == wp->vaddr && len == wp->len
977 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
978 cpu_watchpoint_remove_by_ref(cpu, wp);
979 return 0;
982 return -ENOENT;
985 /* Remove a specific watchpoint by reference. */
986 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
988 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
990 tlb_flush_page(cpu, watchpoint->vaddr);
992 g_free(watchpoint);
995 /* Remove all matching watchpoints. */
996 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
998 CPUWatchpoint *wp, *next;
1000 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
1001 if (wp->flags & mask) {
1002 cpu_watchpoint_remove_by_ref(cpu, wp);
1007 /* Return true if this watchpoint address matches the specified
1008 * access (ie the address range covered by the watchpoint overlaps
1009 * partially or completely with the address range covered by the
1010 * access).
1012 static inline bool cpu_watchpoint_address_matches(CPUWatchpoint *wp,
1013 vaddr addr,
1014 vaddr len)
1016 /* We know the lengths are non-zero, but a little caution is
1017 * required to avoid errors in the case where the range ends
1018 * exactly at the top of the address space and so addr + len
1019 * wraps round to zero.
1021 vaddr wpend = wp->vaddr + wp->len - 1;
1022 vaddr addrend = addr + len - 1;
1024 return !(addr > wpend || wp->vaddr > addrend);
1027 #endif
1029 /* Add a breakpoint. */
1030 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
1031 CPUBreakpoint **breakpoint)
1033 CPUBreakpoint *bp;
1035 bp = g_malloc(sizeof(*bp));
1037 bp->pc = pc;
1038 bp->flags = flags;
1040 /* keep all GDB-injected breakpoints in front */
1041 if (flags & BP_GDB) {
1042 QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
1043 } else {
1044 QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
1047 breakpoint_invalidate(cpu, pc);
1049 if (breakpoint) {
1050 *breakpoint = bp;
1052 return 0;
1055 /* Remove a specific breakpoint. */
1056 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
1058 CPUBreakpoint *bp;
1060 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
1061 if (bp->pc == pc && bp->flags == flags) {
1062 cpu_breakpoint_remove_by_ref(cpu, bp);
1063 return 0;
1066 return -ENOENT;
1069 /* Remove a specific breakpoint by reference. */
1070 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
1072 QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);
1074 breakpoint_invalidate(cpu, breakpoint->pc);
1076 g_free(breakpoint);
1079 /* Remove all matching breakpoints. */
1080 void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
1082 CPUBreakpoint *bp, *next;
1084 QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
1085 if (bp->flags & mask) {
1086 cpu_breakpoint_remove_by_ref(cpu, bp);
1091 /* enable or disable single step mode. EXCP_DEBUG is returned by the
1092 CPU loop after each instruction */
1093 void cpu_single_step(CPUState *cpu, int enabled)
1095 if (cpu->singlestep_enabled != enabled) {
1096 cpu->singlestep_enabled = enabled;
1097 if (kvm_enabled()) {
1098 kvm_update_guest_debug(cpu, 0);
1099 } else {
1100 /* must flush all the translated code to avoid inconsistencies */
1101 /* XXX: only flush what is necessary */
1102 tb_flush(cpu);
1107 void cpu_abort(CPUState *cpu, const char *fmt, ...)
1109 va_list ap;
1110 va_list ap2;
1112 va_start(ap, fmt);
1113 va_copy(ap2, ap);
1114 fprintf(stderr, "qemu: fatal: ");
1115 vfprintf(stderr, fmt, ap);
1116 fprintf(stderr, "\n");
1117 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1118 if (qemu_log_separate()) {
1119 qemu_log_lock();
1120 qemu_log("qemu: fatal: ");
1121 qemu_log_vprintf(fmt, ap2);
1122 qemu_log("\n");
1123 log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1124 qemu_log_flush();
1125 qemu_log_unlock();
1126 qemu_log_close();
1128 va_end(ap2);
1129 va_end(ap);
1130 replay_finish();
1131 #if defined(CONFIG_USER_ONLY)
1133 struct sigaction act;
1134 sigfillset(&act.sa_mask);
1135 act.sa_handler = SIG_DFL;
1136 sigaction(SIGABRT, &act, NULL);
1138 #endif
1139 abort();
1142 #if !defined(CONFIG_USER_ONLY)
1143 /* Called from RCU critical section */
1144 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
1146 RAMBlock *block;
1148 block = atomic_rcu_read(&ram_list.mru_block);
1149 if (block && addr - block->offset < block->max_length) {
1150 return block;
1152 RAMBLOCK_FOREACH(block) {
1153 if (addr - block->offset < block->max_length) {
1154 goto found;
1158 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1159 abort();
1161 found:
1162 /* It is safe to write mru_block outside the iothread lock. This
1163 * is what happens:
1165 * mru_block = xxx
1166 * rcu_read_unlock()
1167 * xxx removed from list
1168 * rcu_read_lock()
1169 * read mru_block
1170 * mru_block = NULL;
1171 * call_rcu(reclaim_ramblock, xxx);
1172 * rcu_read_unlock()
1174 * atomic_rcu_set is not needed here. The block was already published
1175 * when it was placed into the list. Here we're just making an extra
1176 * copy of the pointer.
1178 ram_list.mru_block = block;
1179 return block;
1182 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1184 CPUState *cpu;
1185 ram_addr_t start1;
1186 RAMBlock *block;
1187 ram_addr_t end;
1189 end = TARGET_PAGE_ALIGN(start + length);
1190 start &= TARGET_PAGE_MASK;
1192 rcu_read_lock();
1193 block = qemu_get_ram_block(start);
1194 assert(block == qemu_get_ram_block(end - 1));
1195 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1196 CPU_FOREACH(cpu) {
1197 tlb_reset_dirty(cpu, start1, length);
1199 rcu_read_unlock();
1202 /* Note: start and end must be within the same ram block. */
1203 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1204 ram_addr_t length,
1205 unsigned client)
1207 DirtyMemoryBlocks *blocks;
1208 unsigned long end, page;
1209 bool dirty = false;
1211 if (length == 0) {
1212 return false;
1215 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1216 page = start >> TARGET_PAGE_BITS;
1218 rcu_read_lock();
1220 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1222 while (page < end) {
1223 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1224 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1225 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1227 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1228 offset, num);
1229 page += num;
1232 rcu_read_unlock();
1234 if (dirty && tcg_enabled()) {
1235 tlb_reset_dirty_range_all(start, length);
1238 return dirty;
1241 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1242 (ram_addr_t start, ram_addr_t length, unsigned client)
1244 DirtyMemoryBlocks *blocks;
1245 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1246 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1247 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1248 DirtyBitmapSnapshot *snap;
1249 unsigned long page, end, dest;
1251 snap = g_malloc0(sizeof(*snap) +
1252 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1253 snap->start = first;
1254 snap->end = last;
1256 page = first >> TARGET_PAGE_BITS;
1257 end = last >> TARGET_PAGE_BITS;
1258 dest = 0;
1260 rcu_read_lock();
1262 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1264 while (page < end) {
1265 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1266 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1267 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1269 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1270 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1271 offset >>= BITS_PER_LEVEL;
1273 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1274 blocks->blocks[idx] + offset,
1275 num);
1276 page += num;
1277 dest += num >> BITS_PER_LEVEL;
1280 rcu_read_unlock();
1282 if (tcg_enabled()) {
1283 tlb_reset_dirty_range_all(start, length);
1286 return snap;
1289 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1290 ram_addr_t start,
1291 ram_addr_t length)
1293 unsigned long page, end;
1295 assert(start >= snap->start);
1296 assert(start + length <= snap->end);
1298 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1299 page = (start - snap->start) >> TARGET_PAGE_BITS;
1301 while (page < end) {
1302 if (test_bit(page, snap->dirty)) {
1303 return true;
1305 page++;
1307 return false;
1310 /* Called from RCU critical section */
1311 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1312 MemoryRegionSection *section,
1313 target_ulong vaddr,
1314 hwaddr paddr, hwaddr xlat,
1315 int prot,
1316 target_ulong *address)
1318 hwaddr iotlb;
1319 CPUWatchpoint *wp;
1321 if (memory_region_is_ram(section->mr)) {
1322 /* Normal RAM. */
1323 iotlb = memory_region_get_ram_addr(section->mr) + xlat;
1324 if (!section->readonly) {
1325 iotlb |= PHYS_SECTION_NOTDIRTY;
1326 } else {
1327 iotlb |= PHYS_SECTION_ROM;
1329 } else {
1330 AddressSpaceDispatch *d;
1332 d = flatview_to_dispatch(section->fv);
1333 iotlb = section - d->map.sections;
1334 iotlb += xlat;
1337 /* Make accesses to pages with watchpoints go via the
1338 watchpoint trap routines. */
1339 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1340 if (cpu_watchpoint_address_matches(wp, vaddr, TARGET_PAGE_SIZE)) {
1341 /* Avoid trapping reads of pages with a write breakpoint. */
1342 if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
1343 iotlb = PHYS_SECTION_WATCH + paddr;
1344 *address |= TLB_MMIO;
1345 break;
1350 return iotlb;
1352 #endif /* defined(CONFIG_USER_ONLY) */
1354 #if !defined(CONFIG_USER_ONLY)
1356 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
1357 uint16_t section);
1358 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1360 static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
1361 qemu_anon_ram_alloc;
1364 * Set a custom physical guest memory alloator.
1365 * Accelerators with unusual needs may need this. Hopefully, we can
1366 * get rid of it eventually.
1368 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
1370 phys_mem_alloc = alloc;
1373 static uint16_t phys_section_add(PhysPageMap *map,
1374 MemoryRegionSection *section)
1376 /* The physical section number is ORed with a page-aligned
1377 * pointer to produce the iotlb entries. Thus it should
1378 * never overflow into the page-aligned value.
1380 assert(map->sections_nb < TARGET_PAGE_SIZE);
1382 if (map->sections_nb == map->sections_nb_alloc) {
1383 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1384 map->sections = g_renew(MemoryRegionSection, map->sections,
1385 map->sections_nb_alloc);
1387 map->sections[map->sections_nb] = *section;
1388 memory_region_ref(section->mr);
1389 return map->sections_nb++;
1392 static void phys_section_destroy(MemoryRegion *mr)
1394 bool have_sub_page = mr->subpage;
1396 memory_region_unref(mr);
1398 if (have_sub_page) {
1399 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1400 object_unref(OBJECT(&subpage->iomem));
1401 g_free(subpage);
1405 static void phys_sections_free(PhysPageMap *map)
1407 while (map->sections_nb > 0) {
1408 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1409 phys_section_destroy(section->mr);
1411 g_free(map->sections);
1412 g_free(map->nodes);
1415 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1417 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1418 subpage_t *subpage;
1419 hwaddr base = section->offset_within_address_space
1420 & TARGET_PAGE_MASK;
1421 MemoryRegionSection *existing = phys_page_find(d, base);
1422 MemoryRegionSection subsection = {
1423 .offset_within_address_space = base,
1424 .size = int128_make64(TARGET_PAGE_SIZE),
1426 hwaddr start, end;
1428 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1430 if (!(existing->mr->subpage)) {
1431 subpage = subpage_init(fv, base);
1432 subsection.fv = fv;
1433 subsection.mr = &subpage->iomem;
1434 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1435 phys_section_add(&d->map, &subsection));
1436 } else {
1437 subpage = container_of(existing->mr, subpage_t, iomem);
1439 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1440 end = start + int128_get64(section->size) - 1;
1441 subpage_register(subpage, start, end,
1442 phys_section_add(&d->map, section));
1446 static void register_multipage(FlatView *fv,
1447 MemoryRegionSection *section)
1449 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1450 hwaddr start_addr = section->offset_within_address_space;
1451 uint16_t section_index = phys_section_add(&d->map, section);
1452 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1453 TARGET_PAGE_BITS));
1455 assert(num_pages);
1456 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1459 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1461 MemoryRegionSection now = *section, remain = *section;
1462 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1464 if (now.offset_within_address_space & ~TARGET_PAGE_MASK) {
1465 uint64_t left = TARGET_PAGE_ALIGN(now.offset_within_address_space)
1466 - now.offset_within_address_space;
1468 now.size = int128_min(int128_make64(left), now.size);
1469 register_subpage(fv, &now);
1470 } else {
1471 now.size = int128_zero();
1473 while (int128_ne(remain.size, now.size)) {
1474 remain.size = int128_sub(remain.size, now.size);
1475 remain.offset_within_address_space += int128_get64(now.size);
1476 remain.offset_within_region += int128_get64(now.size);
1477 now = remain;
1478 if (int128_lt(remain.size, page_size)) {
1479 register_subpage(fv, &now);
1480 } else if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1481 now.size = page_size;
1482 register_subpage(fv, &now);
1483 } else {
1484 now.size = int128_and(now.size, int128_neg(page_size));
1485 register_multipage(fv, &now);
1490 void qemu_flush_coalesced_mmio_buffer(void)
1492 if (kvm_enabled())
1493 kvm_flush_coalesced_mmio_buffer();
1496 void qemu_mutex_lock_ramlist(void)
1498 qemu_mutex_lock(&ram_list.mutex);
1501 void qemu_mutex_unlock_ramlist(void)
1503 qemu_mutex_unlock(&ram_list.mutex);
1506 void ram_block_dump(Monitor *mon)
1508 RAMBlock *block;
1509 char *psize;
1511 rcu_read_lock();
1512 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1513 "Block Name", "PSize", "Offset", "Used", "Total");
1514 RAMBLOCK_FOREACH(block) {
1515 psize = size_to_str(block->page_size);
1516 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1517 " 0x%016" PRIx64 "\n", block->idstr, psize,
1518 (uint64_t)block->offset,
1519 (uint64_t)block->used_length,
1520 (uint64_t)block->max_length);
1521 g_free(psize);
1523 rcu_read_unlock();
1526 #ifdef __linux__
1528 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1529 * may or may not name the same files / on the same filesystem now as
1530 * when we actually open and map them. Iterate over the file
1531 * descriptors instead, and use qemu_fd_getpagesize().
1533 static int find_max_supported_pagesize(Object *obj, void *opaque)
1535 long *hpsize_min = opaque;
1537 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1538 long hpsize = host_memory_backend_pagesize(MEMORY_BACKEND(obj));
1540 if (hpsize < *hpsize_min) {
1541 *hpsize_min = hpsize;
1545 return 0;
1548 long qemu_getrampagesize(void)
1550 long hpsize = LONG_MAX;
1551 long mainrampagesize;
1552 Object *memdev_root;
1554 mainrampagesize = qemu_mempath_getpagesize(mem_path);
1556 /* it's possible we have memory-backend objects with
1557 * hugepage-backed RAM. these may get mapped into system
1558 * address space via -numa parameters or memory hotplug
1559 * hooks. we want to take these into account, but we
1560 * also want to make sure these supported hugepage
1561 * sizes are applicable across the entire range of memory
1562 * we may boot from, so we take the min across all
1563 * backends, and assume normal pages in cases where a
1564 * backend isn't backed by hugepages.
1566 memdev_root = object_resolve_path("/objects", NULL);
1567 if (memdev_root) {
1568 object_child_foreach(memdev_root, find_max_supported_pagesize, &hpsize);
1570 if (hpsize == LONG_MAX) {
1571 /* No additional memory regions found ==> Report main RAM page size */
1572 return mainrampagesize;
1575 /* If NUMA is disabled or the NUMA nodes are not backed with a
1576 * memory-backend, then there is at least one node using "normal" RAM,
1577 * so if its page size is smaller we have got to report that size instead.
1579 if (hpsize > mainrampagesize &&
1580 (nb_numa_nodes == 0 || numa_info[0].node_memdev == NULL)) {
1581 static bool warned;
1582 if (!warned) {
1583 error_report("Huge page support disabled (n/a for main memory).");
1584 warned = true;
1586 return mainrampagesize;
1589 return hpsize;
1591 #else
1592 long qemu_getrampagesize(void)
1594 return getpagesize();
1596 #endif
1598 #ifdef __linux__
1599 static int64_t get_file_size(int fd)
1601 int64_t size = lseek(fd, 0, SEEK_END);
1602 if (size < 0) {
1603 return -errno;
1605 return size;
1608 static int file_ram_open(const char *path,
1609 const char *region_name,
1610 bool *created,
1611 Error **errp)
1613 char *filename;
1614 char *sanitized_name;
1615 char *c;
1616 int fd = -1;
1618 *created = false;
1619 for (;;) {
1620 fd = open(path, O_RDWR);
1621 if (fd >= 0) {
1622 /* @path names an existing file, use it */
1623 break;
1625 if (errno == ENOENT) {
1626 /* @path names a file that doesn't exist, create it */
1627 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1628 if (fd >= 0) {
1629 *created = true;
1630 break;
1632 } else if (errno == EISDIR) {
1633 /* @path names a directory, create a file there */
1634 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1635 sanitized_name = g_strdup(region_name);
1636 for (c = sanitized_name; *c != '\0'; c++) {
1637 if (*c == '/') {
1638 *c = '_';
1642 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1643 sanitized_name);
1644 g_free(sanitized_name);
1646 fd = mkstemp(filename);
1647 if (fd >= 0) {
1648 unlink(filename);
1649 g_free(filename);
1650 break;
1652 g_free(filename);
1654 if (errno != EEXIST && errno != EINTR) {
1655 error_setg_errno(errp, errno,
1656 "can't open backing store %s for guest RAM",
1657 path);
1658 return -1;
1661 * Try again on EINTR and EEXIST. The latter happens when
1662 * something else creates the file between our two open().
1666 return fd;
1669 static void *file_ram_alloc(RAMBlock *block,
1670 ram_addr_t memory,
1671 int fd,
1672 bool truncate,
1673 Error **errp)
1675 void *area;
1677 block->page_size = qemu_fd_getpagesize(fd);
1678 if (block->mr->align % block->page_size) {
1679 error_setg(errp, "alignment 0x%" PRIx64
1680 " must be multiples of page size 0x%zx",
1681 block->mr->align, block->page_size);
1682 return NULL;
1684 block->mr->align = MAX(block->page_size, block->mr->align);
1685 #if defined(__s390x__)
1686 if (kvm_enabled()) {
1687 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1689 #endif
1691 if (memory < block->page_size) {
1692 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1693 "or larger than page size 0x%zx",
1694 memory, block->page_size);
1695 return NULL;
1698 memory = ROUND_UP(memory, block->page_size);
1701 * ftruncate is not supported by hugetlbfs in older
1702 * hosts, so don't bother bailing out on errors.
1703 * If anything goes wrong with it under other filesystems,
1704 * mmap will fail.
1706 * Do not truncate the non-empty backend file to avoid corrupting
1707 * the existing data in the file. Disabling shrinking is not
1708 * enough. For example, the current vNVDIMM implementation stores
1709 * the guest NVDIMM labels at the end of the backend file. If the
1710 * backend file is later extended, QEMU will not be able to find
1711 * those labels. Therefore, extending the non-empty backend file
1712 * is disabled as well.
1714 if (truncate && ftruncate(fd, memory)) {
1715 perror("ftruncate");
1718 area = qemu_ram_mmap(fd, memory, block->mr->align,
1719 block->flags & RAM_SHARED);
1720 if (area == MAP_FAILED) {
1721 error_setg_errno(errp, errno,
1722 "unable to map backing store for guest RAM");
1723 return NULL;
1726 if (mem_prealloc) {
1727 os_mem_prealloc(fd, area, memory, smp_cpus, errp);
1728 if (errp && *errp) {
1729 qemu_ram_munmap(area, memory);
1730 return NULL;
1734 block->fd = fd;
1735 return area;
1737 #endif
1739 /* Allocate space within the ram_addr_t space that governs the
1740 * dirty bitmaps.
1741 * Called with the ramlist lock held.
1743 static ram_addr_t find_ram_offset(ram_addr_t size)
1745 RAMBlock *block, *next_block;
1746 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1748 assert(size != 0); /* it would hand out same offset multiple times */
1750 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1751 return 0;
1754 RAMBLOCK_FOREACH(block) {
1755 ram_addr_t candidate, next = RAM_ADDR_MAX;
1757 /* Align blocks to start on a 'long' in the bitmap
1758 * which makes the bitmap sync'ing take the fast path.
1760 candidate = block->offset + block->max_length;
1761 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1763 /* Search for the closest following block
1764 * and find the gap.
1766 RAMBLOCK_FOREACH(next_block) {
1767 if (next_block->offset >= candidate) {
1768 next = MIN(next, next_block->offset);
1772 /* If it fits remember our place and remember the size
1773 * of gap, but keep going so that we might find a smaller
1774 * gap to fill so avoiding fragmentation.
1776 if (next - candidate >= size && next - candidate < mingap) {
1777 offset = candidate;
1778 mingap = next - candidate;
1781 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1784 if (offset == RAM_ADDR_MAX) {
1785 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1786 (uint64_t)size);
1787 abort();
1790 trace_find_ram_offset(size, offset);
1792 return offset;
1795 unsigned long last_ram_page(void)
1797 RAMBlock *block;
1798 ram_addr_t last = 0;
1800 rcu_read_lock();
1801 RAMBLOCK_FOREACH(block) {
1802 last = MAX(last, block->offset + block->max_length);
1804 rcu_read_unlock();
1805 return last >> TARGET_PAGE_BITS;
1808 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1810 int ret;
1812 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1813 if (!machine_dump_guest_core(current_machine)) {
1814 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1815 if (ret) {
1816 perror("qemu_madvise");
1817 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1818 "but dump_guest_core=off specified\n");
1823 const char *qemu_ram_get_idstr(RAMBlock *rb)
1825 return rb->idstr;
1828 bool qemu_ram_is_shared(RAMBlock *rb)
1830 return rb->flags & RAM_SHARED;
1833 /* Note: Only set at the start of postcopy */
1834 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1836 return rb->flags & RAM_UF_ZEROPAGE;
1839 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1841 rb->flags |= RAM_UF_ZEROPAGE;
1844 bool qemu_ram_is_migratable(RAMBlock *rb)
1846 return rb->flags & RAM_MIGRATABLE;
1849 void qemu_ram_set_migratable(RAMBlock *rb)
1851 rb->flags |= RAM_MIGRATABLE;
1854 void qemu_ram_unset_migratable(RAMBlock *rb)
1856 rb->flags &= ~RAM_MIGRATABLE;
1859 /* Called with iothread lock held. */
1860 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1862 RAMBlock *block;
1864 assert(new_block);
1865 assert(!new_block->idstr[0]);
1867 if (dev) {
1868 char *id = qdev_get_dev_path(dev);
1869 if (id) {
1870 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1871 g_free(id);
1874 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1876 rcu_read_lock();
1877 RAMBLOCK_FOREACH(block) {
1878 if (block != new_block &&
1879 !strcmp(block->idstr, new_block->idstr)) {
1880 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1881 new_block->idstr);
1882 abort();
1885 rcu_read_unlock();
1888 /* Called with iothread lock held. */
1889 void qemu_ram_unset_idstr(RAMBlock *block)
1891 /* FIXME: arch_init.c assumes that this is not called throughout
1892 * migration. Ignore the problem since hot-unplug during migration
1893 * does not work anyway.
1895 if (block) {
1896 memset(block->idstr, 0, sizeof(block->idstr));
1900 size_t qemu_ram_pagesize(RAMBlock *rb)
1902 return rb->page_size;
1905 /* Returns the largest size of page in use */
1906 size_t qemu_ram_pagesize_largest(void)
1908 RAMBlock *block;
1909 size_t largest = 0;
1911 RAMBLOCK_FOREACH(block) {
1912 largest = MAX(largest, qemu_ram_pagesize(block));
1915 return largest;
1918 static int memory_try_enable_merging(void *addr, size_t len)
1920 if (!machine_mem_merge(current_machine)) {
1921 /* disabled by the user */
1922 return 0;
1925 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1928 /* Only legal before guest might have detected the memory size: e.g. on
1929 * incoming migration, or right after reset.
1931 * As memory core doesn't know how is memory accessed, it is up to
1932 * resize callback to update device state and/or add assertions to detect
1933 * misuse, if necessary.
1935 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1937 assert(block);
1939 newsize = HOST_PAGE_ALIGN(newsize);
1941 if (block->used_length == newsize) {
1942 return 0;
1945 if (!(block->flags & RAM_RESIZEABLE)) {
1946 error_setg_errno(errp, EINVAL,
1947 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1948 " in != 0x" RAM_ADDR_FMT, block->idstr,
1949 newsize, block->used_length);
1950 return -EINVAL;
1953 if (block->max_length < newsize) {
1954 error_setg_errno(errp, EINVAL,
1955 "Length too large: %s: 0x" RAM_ADDR_FMT
1956 " > 0x" RAM_ADDR_FMT, block->idstr,
1957 newsize, block->max_length);
1958 return -EINVAL;
1961 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1962 block->used_length = newsize;
1963 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1964 DIRTY_CLIENTS_ALL);
1965 memory_region_set_size(block->mr, newsize);
1966 if (block->resized) {
1967 block->resized(block->idstr, newsize, block->host);
1969 return 0;
1972 /* Called with ram_list.mutex held */
1973 static void dirty_memory_extend(ram_addr_t old_ram_size,
1974 ram_addr_t new_ram_size)
1976 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1977 DIRTY_MEMORY_BLOCK_SIZE);
1978 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1979 DIRTY_MEMORY_BLOCK_SIZE);
1980 int i;
1982 /* Only need to extend if block count increased */
1983 if (new_num_blocks <= old_num_blocks) {
1984 return;
1987 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1988 DirtyMemoryBlocks *old_blocks;
1989 DirtyMemoryBlocks *new_blocks;
1990 int j;
1992 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
1993 new_blocks = g_malloc(sizeof(*new_blocks) +
1994 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1996 if (old_num_blocks) {
1997 memcpy(new_blocks->blocks, old_blocks->blocks,
1998 old_num_blocks * sizeof(old_blocks->blocks[0]));
2001 for (j = old_num_blocks; j < new_num_blocks; j++) {
2002 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
2005 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
2007 if (old_blocks) {
2008 g_free_rcu(old_blocks, rcu);
2013 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
2015 RAMBlock *block;
2016 RAMBlock *last_block = NULL;
2017 ram_addr_t old_ram_size, new_ram_size;
2018 Error *err = NULL;
2020 old_ram_size = last_ram_page();
2022 qemu_mutex_lock_ramlist();
2023 new_block->offset = find_ram_offset(new_block->max_length);
2025 if (!new_block->host) {
2026 if (xen_enabled()) {
2027 xen_ram_alloc(new_block->offset, new_block->max_length,
2028 new_block->mr, &err);
2029 if (err) {
2030 error_propagate(errp, err);
2031 qemu_mutex_unlock_ramlist();
2032 return;
2034 } else {
2035 new_block->host = phys_mem_alloc(new_block->max_length,
2036 &new_block->mr->align, shared);
2037 if (!new_block->host) {
2038 error_setg_errno(errp, errno,
2039 "cannot set up guest memory '%s'",
2040 memory_region_name(new_block->mr));
2041 qemu_mutex_unlock_ramlist();
2042 return;
2044 memory_try_enable_merging(new_block->host, new_block->max_length);
2048 new_ram_size = MAX(old_ram_size,
2049 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
2050 if (new_ram_size > old_ram_size) {
2051 dirty_memory_extend(old_ram_size, new_ram_size);
2053 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2054 * QLIST (which has an RCU-friendly variant) does not have insertion at
2055 * tail, so save the last element in last_block.
2057 RAMBLOCK_FOREACH(block) {
2058 last_block = block;
2059 if (block->max_length < new_block->max_length) {
2060 break;
2063 if (block) {
2064 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
2065 } else if (last_block) {
2066 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
2067 } else { /* list is empty */
2068 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
2070 ram_list.mru_block = NULL;
2072 /* Write list before version */
2073 smp_wmb();
2074 ram_list.version++;
2075 qemu_mutex_unlock_ramlist();
2077 cpu_physical_memory_set_dirty_range(new_block->offset,
2078 new_block->used_length,
2079 DIRTY_CLIENTS_ALL);
2081 if (new_block->host) {
2082 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2083 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2084 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
2085 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
2086 ram_block_notify_add(new_block->host, new_block->max_length);
2090 #ifdef __linux__
2091 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2092 bool share, int fd,
2093 Error **errp)
2095 RAMBlock *new_block;
2096 Error *local_err = NULL;
2097 int64_t file_size;
2099 if (xen_enabled()) {
2100 error_setg(errp, "-mem-path not supported with Xen");
2101 return NULL;
2104 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2105 error_setg(errp,
2106 "host lacks kvm mmu notifiers, -mem-path unsupported");
2107 return NULL;
2110 if (phys_mem_alloc != qemu_anon_ram_alloc) {
2112 * file_ram_alloc() needs to allocate just like
2113 * phys_mem_alloc, but we haven't bothered to provide
2114 * a hook there.
2116 error_setg(errp,
2117 "-mem-path not supported with this accelerator");
2118 return NULL;
2121 size = HOST_PAGE_ALIGN(size);
2122 file_size = get_file_size(fd);
2123 if (file_size > 0 && file_size < size) {
2124 error_setg(errp, "backing store %s size 0x%" PRIx64
2125 " does not match 'size' option 0x" RAM_ADDR_FMT,
2126 mem_path, file_size, size);
2127 return NULL;
2130 new_block = g_malloc0(sizeof(*new_block));
2131 new_block->mr = mr;
2132 new_block->used_length = size;
2133 new_block->max_length = size;
2134 new_block->flags = share ? RAM_SHARED : 0;
2135 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
2136 if (!new_block->host) {
2137 g_free(new_block);
2138 return NULL;
2141 ram_block_add(new_block, &local_err, share);
2142 if (local_err) {
2143 g_free(new_block);
2144 error_propagate(errp, local_err);
2145 return NULL;
2147 return new_block;
2152 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2153 bool share, const char *mem_path,
2154 Error **errp)
2156 int fd;
2157 bool created;
2158 RAMBlock *block;
2160 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2161 if (fd < 0) {
2162 return NULL;
2165 block = qemu_ram_alloc_from_fd(size, mr, share, fd, errp);
2166 if (!block) {
2167 if (created) {
2168 unlink(mem_path);
2170 close(fd);
2171 return NULL;
2174 return block;
2176 #endif
2178 static
2179 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2180 void (*resized)(const char*,
2181 uint64_t length,
2182 void *host),
2183 void *host, bool resizeable, bool share,
2184 MemoryRegion *mr, Error **errp)
2186 RAMBlock *new_block;
2187 Error *local_err = NULL;
2189 size = HOST_PAGE_ALIGN(size);
2190 max_size = HOST_PAGE_ALIGN(max_size);
2191 new_block = g_malloc0(sizeof(*new_block));
2192 new_block->mr = mr;
2193 new_block->resized = resized;
2194 new_block->used_length = size;
2195 new_block->max_length = max_size;
2196 assert(max_size >= size);
2197 new_block->fd = -1;
2198 new_block->page_size = getpagesize();
2199 new_block->host = host;
2200 if (host) {
2201 new_block->flags |= RAM_PREALLOC;
2203 if (resizeable) {
2204 new_block->flags |= RAM_RESIZEABLE;
2206 ram_block_add(new_block, &local_err, share);
2207 if (local_err) {
2208 g_free(new_block);
2209 error_propagate(errp, local_err);
2210 return NULL;
2212 return new_block;
2215 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2216 MemoryRegion *mr, Error **errp)
2218 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2219 false, mr, errp);
2222 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2223 MemoryRegion *mr, Error **errp)
2225 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2226 share, mr, errp);
2229 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2230 void (*resized)(const char*,
2231 uint64_t length,
2232 void *host),
2233 MemoryRegion *mr, Error **errp)
2235 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2236 false, mr, errp);
2239 static void reclaim_ramblock(RAMBlock *block)
2241 if (block->flags & RAM_PREALLOC) {
2243 } else if (xen_enabled()) {
2244 xen_invalidate_map_cache_entry(block->host);
2245 #ifndef _WIN32
2246 } else if (block->fd >= 0) {
2247 qemu_ram_munmap(block->host, block->max_length);
2248 close(block->fd);
2249 #endif
2250 } else {
2251 qemu_anon_ram_free(block->host, block->max_length);
2253 g_free(block);
2256 void qemu_ram_free(RAMBlock *block)
2258 if (!block) {
2259 return;
2262 if (block->host) {
2263 ram_block_notify_remove(block->host, block->max_length);
2266 qemu_mutex_lock_ramlist();
2267 QLIST_REMOVE_RCU(block, next);
2268 ram_list.mru_block = NULL;
2269 /* Write list before version */
2270 smp_wmb();
2271 ram_list.version++;
2272 call_rcu(block, reclaim_ramblock, rcu);
2273 qemu_mutex_unlock_ramlist();
2276 #ifndef _WIN32
2277 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2279 RAMBlock *block;
2280 ram_addr_t offset;
2281 int flags;
2282 void *area, *vaddr;
2284 RAMBLOCK_FOREACH(block) {
2285 offset = addr - block->offset;
2286 if (offset < block->max_length) {
2287 vaddr = ramblock_ptr(block, offset);
2288 if (block->flags & RAM_PREALLOC) {
2290 } else if (xen_enabled()) {
2291 abort();
2292 } else {
2293 flags = MAP_FIXED;
2294 if (block->fd >= 0) {
2295 flags |= (block->flags & RAM_SHARED ?
2296 MAP_SHARED : MAP_PRIVATE);
2297 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2298 flags, block->fd, offset);
2299 } else {
2301 * Remap needs to match alloc. Accelerators that
2302 * set phys_mem_alloc never remap. If they did,
2303 * we'd need a remap hook here.
2305 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2307 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2308 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2309 flags, -1, 0);
2311 if (area != vaddr) {
2312 error_report("Could not remap addr: "
2313 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2314 length, addr);
2315 exit(1);
2317 memory_try_enable_merging(vaddr, length);
2318 qemu_ram_setup_dump(vaddr, length);
2323 #endif /* !_WIN32 */
2325 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2326 * This should not be used for general purpose DMA. Use address_space_map
2327 * or address_space_rw instead. For local memory (e.g. video ram) that the
2328 * device owns, use memory_region_get_ram_ptr.
2330 * Called within RCU critical section.
2332 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2334 RAMBlock *block = ram_block;
2336 if (block == NULL) {
2337 block = qemu_get_ram_block(addr);
2338 addr -= block->offset;
2341 if (xen_enabled() && block->host == NULL) {
2342 /* We need to check if the requested address is in the RAM
2343 * because we don't want to map the entire memory in QEMU.
2344 * In that case just map until the end of the page.
2346 if (block->offset == 0) {
2347 return xen_map_cache(addr, 0, 0, false);
2350 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2352 return ramblock_ptr(block, addr);
2355 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2356 * but takes a size argument.
2358 * Called within RCU critical section.
2360 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2361 hwaddr *size, bool lock)
2363 RAMBlock *block = ram_block;
2364 if (*size == 0) {
2365 return NULL;
2368 if (block == NULL) {
2369 block = qemu_get_ram_block(addr);
2370 addr -= block->offset;
2372 *size = MIN(*size, block->max_length - addr);
2374 if (xen_enabled() && block->host == NULL) {
2375 /* We need to check if the requested address is in the RAM
2376 * because we don't want to map the entire memory in QEMU.
2377 * In that case just map the requested area.
2379 if (block->offset == 0) {
2380 return xen_map_cache(addr, *size, lock, lock);
2383 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2386 return ramblock_ptr(block, addr);
2389 /* Return the offset of a hostpointer within a ramblock */
2390 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2392 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2393 assert((uintptr_t)host >= (uintptr_t)rb->host);
2394 assert(res < rb->max_length);
2396 return res;
2400 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2401 * in that RAMBlock.
2403 * ptr: Host pointer to look up
2404 * round_offset: If true round the result offset down to a page boundary
2405 * *ram_addr: set to result ram_addr
2406 * *offset: set to result offset within the RAMBlock
2408 * Returns: RAMBlock (or NULL if not found)
2410 * By the time this function returns, the returned pointer is not protected
2411 * by RCU anymore. If the caller is not within an RCU critical section and
2412 * does not hold the iothread lock, it must have other means of protecting the
2413 * pointer, such as a reference to the region that includes the incoming
2414 * ram_addr_t.
2416 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2417 ram_addr_t *offset)
2419 RAMBlock *block;
2420 uint8_t *host = ptr;
2422 if (xen_enabled()) {
2423 ram_addr_t ram_addr;
2424 rcu_read_lock();
2425 ram_addr = xen_ram_addr_from_mapcache(ptr);
2426 block = qemu_get_ram_block(ram_addr);
2427 if (block) {
2428 *offset = ram_addr - block->offset;
2430 rcu_read_unlock();
2431 return block;
2434 rcu_read_lock();
2435 block = atomic_rcu_read(&ram_list.mru_block);
2436 if (block && block->host && host - block->host < block->max_length) {
2437 goto found;
2440 RAMBLOCK_FOREACH(block) {
2441 /* This case append when the block is not mapped. */
2442 if (block->host == NULL) {
2443 continue;
2445 if (host - block->host < block->max_length) {
2446 goto found;
2450 rcu_read_unlock();
2451 return NULL;
2453 found:
2454 *offset = (host - block->host);
2455 if (round_offset) {
2456 *offset &= TARGET_PAGE_MASK;
2458 rcu_read_unlock();
2459 return block;
2463 * Finds the named RAMBlock
2465 * name: The name of RAMBlock to find
2467 * Returns: RAMBlock (or NULL if not found)
2469 RAMBlock *qemu_ram_block_by_name(const char *name)
2471 RAMBlock *block;
2473 RAMBLOCK_FOREACH(block) {
2474 if (!strcmp(name, block->idstr)) {
2475 return block;
2479 return NULL;
2482 /* Some of the softmmu routines need to translate from a host pointer
2483 (typically a TLB entry) back to a ram offset. */
2484 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2486 RAMBlock *block;
2487 ram_addr_t offset;
2489 block = qemu_ram_block_from_host(ptr, false, &offset);
2490 if (!block) {
2491 return RAM_ADDR_INVALID;
2494 return block->offset + offset;
2497 /* Called within RCU critical section. */
2498 void memory_notdirty_write_prepare(NotDirtyInfo *ndi,
2499 CPUState *cpu,
2500 vaddr mem_vaddr,
2501 ram_addr_t ram_addr,
2502 unsigned size)
2504 ndi->cpu = cpu;
2505 ndi->ram_addr = ram_addr;
2506 ndi->mem_vaddr = mem_vaddr;
2507 ndi->size = size;
2508 ndi->locked = false;
2510 assert(tcg_enabled());
2511 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
2512 ndi->locked = true;
2513 tb_lock();
2514 tb_invalidate_phys_page_fast(ram_addr, size);
2518 /* Called within RCU critical section. */
2519 void memory_notdirty_write_complete(NotDirtyInfo *ndi)
2521 if (ndi->locked) {
2522 tb_unlock();
2525 /* Set both VGA and migration bits for simplicity and to remove
2526 * the notdirty callback faster.
2528 cpu_physical_memory_set_dirty_range(ndi->ram_addr, ndi->size,
2529 DIRTY_CLIENTS_NOCODE);
2530 /* we remove the notdirty callback only if the code has been
2531 flushed */
2532 if (!cpu_physical_memory_is_clean(ndi->ram_addr)) {
2533 tlb_set_dirty(ndi->cpu, ndi->mem_vaddr);
2537 /* Called within RCU critical section. */
2538 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2539 uint64_t val, unsigned size)
2541 NotDirtyInfo ndi;
2543 memory_notdirty_write_prepare(&ndi, current_cpu, current_cpu->mem_io_vaddr,
2544 ram_addr, size);
2546 switch (size) {
2547 case 1:
2548 stb_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2549 break;
2550 case 2:
2551 stw_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2552 break;
2553 case 4:
2554 stl_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2555 break;
2556 case 8:
2557 stq_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2558 break;
2559 default:
2560 abort();
2562 memory_notdirty_write_complete(&ndi);
2565 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
2566 unsigned size, bool is_write,
2567 MemTxAttrs attrs)
2569 return is_write;
2572 static const MemoryRegionOps notdirty_mem_ops = {
2573 .write = notdirty_mem_write,
2574 .valid.accepts = notdirty_mem_accepts,
2575 .endianness = DEVICE_NATIVE_ENDIAN,
2576 .valid = {
2577 .min_access_size = 1,
2578 .max_access_size = 8,
2579 .unaligned = false,
2581 .impl = {
2582 .min_access_size = 1,
2583 .max_access_size = 8,
2584 .unaligned = false,
2588 /* Generate a debug exception if a watchpoint has been hit. */
2589 static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
2591 CPUState *cpu = current_cpu;
2592 CPUClass *cc = CPU_GET_CLASS(cpu);
2593 target_ulong vaddr;
2594 CPUWatchpoint *wp;
2596 assert(tcg_enabled());
2597 if (cpu->watchpoint_hit) {
2598 /* We re-entered the check after replacing the TB. Now raise
2599 * the debug interrupt so that is will trigger after the
2600 * current instruction. */
2601 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2602 return;
2604 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
2605 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
2606 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2607 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2608 && (wp->flags & flags)) {
2609 if (flags == BP_MEM_READ) {
2610 wp->flags |= BP_WATCHPOINT_HIT_READ;
2611 } else {
2612 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2614 wp->hitaddr = vaddr;
2615 wp->hitattrs = attrs;
2616 if (!cpu->watchpoint_hit) {
2617 if (wp->flags & BP_CPU &&
2618 !cc->debug_check_watchpoint(cpu, wp)) {
2619 wp->flags &= ~BP_WATCHPOINT_HIT;
2620 continue;
2622 cpu->watchpoint_hit = wp;
2624 /* Both tb_lock and iothread_mutex will be reset when
2625 * cpu_loop_exit or cpu_loop_exit_noexc longjmp
2626 * back into the cpu_exec main loop.
2628 tb_lock();
2629 tb_check_watchpoint(cpu);
2630 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2631 cpu->exception_index = EXCP_DEBUG;
2632 cpu_loop_exit(cpu);
2633 } else {
2634 /* Force execution of one insn next time. */
2635 cpu->cflags_next_tb = 1 | curr_cflags();
2636 cpu_loop_exit_noexc(cpu);
2639 } else {
2640 wp->flags &= ~BP_WATCHPOINT_HIT;
2645 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2646 so these check for a hit then pass through to the normal out-of-line
2647 phys routines. */
2648 static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2649 unsigned size, MemTxAttrs attrs)
2651 MemTxResult res;
2652 uint64_t data;
2653 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2654 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2656 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2657 switch (size) {
2658 case 1:
2659 data = address_space_ldub(as, addr, attrs, &res);
2660 break;
2661 case 2:
2662 data = address_space_lduw(as, addr, attrs, &res);
2663 break;
2664 case 4:
2665 data = address_space_ldl(as, addr, attrs, &res);
2666 break;
2667 case 8:
2668 data = address_space_ldq(as, addr, attrs, &res);
2669 break;
2670 default: abort();
2672 *pdata = data;
2673 return res;
2676 static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2677 uint64_t val, unsigned size,
2678 MemTxAttrs attrs)
2680 MemTxResult res;
2681 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2682 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2684 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2685 switch (size) {
2686 case 1:
2687 address_space_stb(as, addr, val, attrs, &res);
2688 break;
2689 case 2:
2690 address_space_stw(as, addr, val, attrs, &res);
2691 break;
2692 case 4:
2693 address_space_stl(as, addr, val, attrs, &res);
2694 break;
2695 case 8:
2696 address_space_stq(as, addr, val, attrs, &res);
2697 break;
2698 default: abort();
2700 return res;
2703 static const MemoryRegionOps watch_mem_ops = {
2704 .read_with_attrs = watch_mem_read,
2705 .write_with_attrs = watch_mem_write,
2706 .endianness = DEVICE_NATIVE_ENDIAN,
2707 .valid = {
2708 .min_access_size = 1,
2709 .max_access_size = 8,
2710 .unaligned = false,
2712 .impl = {
2713 .min_access_size = 1,
2714 .max_access_size = 8,
2715 .unaligned = false,
2719 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2720 MemTxAttrs attrs, uint8_t *buf, int len);
2721 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2722 const uint8_t *buf, int len);
2723 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
2724 bool is_write, MemTxAttrs attrs);
2726 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2727 unsigned len, MemTxAttrs attrs)
2729 subpage_t *subpage = opaque;
2730 uint8_t buf[8];
2731 MemTxResult res;
2733 #if defined(DEBUG_SUBPAGE)
2734 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2735 subpage, len, addr);
2736 #endif
2737 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2738 if (res) {
2739 return res;
2741 switch (len) {
2742 case 1:
2743 *data = ldub_p(buf);
2744 return MEMTX_OK;
2745 case 2:
2746 *data = lduw_p(buf);
2747 return MEMTX_OK;
2748 case 4:
2749 *data = ldl_p(buf);
2750 return MEMTX_OK;
2751 case 8:
2752 *data = ldq_p(buf);
2753 return MEMTX_OK;
2754 default:
2755 abort();
2759 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2760 uint64_t value, unsigned len, MemTxAttrs attrs)
2762 subpage_t *subpage = opaque;
2763 uint8_t buf[8];
2765 #if defined(DEBUG_SUBPAGE)
2766 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2767 " value %"PRIx64"\n",
2768 __func__, subpage, len, addr, value);
2769 #endif
2770 switch (len) {
2771 case 1:
2772 stb_p(buf, value);
2773 break;
2774 case 2:
2775 stw_p(buf, value);
2776 break;
2777 case 4:
2778 stl_p(buf, value);
2779 break;
2780 case 8:
2781 stq_p(buf, value);
2782 break;
2783 default:
2784 abort();
2786 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2789 static bool subpage_accepts(void *opaque, hwaddr addr,
2790 unsigned len, bool is_write,
2791 MemTxAttrs attrs)
2793 subpage_t *subpage = opaque;
2794 #if defined(DEBUG_SUBPAGE)
2795 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2796 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2797 #endif
2799 return flatview_access_valid(subpage->fv, addr + subpage->base,
2800 len, is_write, attrs);
2803 static const MemoryRegionOps subpage_ops = {
2804 .read_with_attrs = subpage_read,
2805 .write_with_attrs = subpage_write,
2806 .impl.min_access_size = 1,
2807 .impl.max_access_size = 8,
2808 .valid.min_access_size = 1,
2809 .valid.max_access_size = 8,
2810 .valid.accepts = subpage_accepts,
2811 .endianness = DEVICE_NATIVE_ENDIAN,
2814 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
2815 uint16_t section)
2817 int idx, eidx;
2819 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2820 return -1;
2821 idx = SUBPAGE_IDX(start);
2822 eidx = SUBPAGE_IDX(end);
2823 #if defined(DEBUG_SUBPAGE)
2824 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2825 __func__, mmio, start, end, idx, eidx, section);
2826 #endif
2827 for (; idx <= eidx; idx++) {
2828 mmio->sub_section[idx] = section;
2831 return 0;
2834 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2836 subpage_t *mmio;
2838 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2839 mmio->fv = fv;
2840 mmio->base = base;
2841 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2842 NULL, TARGET_PAGE_SIZE);
2843 mmio->iomem.subpage = true;
2844 #if defined(DEBUG_SUBPAGE)
2845 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2846 mmio, base, TARGET_PAGE_SIZE);
2847 #endif
2848 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
2850 return mmio;
2853 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2855 assert(fv);
2856 MemoryRegionSection section = {
2857 .fv = fv,
2858 .mr = mr,
2859 .offset_within_address_space = 0,
2860 .offset_within_region = 0,
2861 .size = int128_2_64(),
2864 return phys_section_add(map, &section);
2867 static void readonly_mem_write(void *opaque, hwaddr addr,
2868 uint64_t val, unsigned size)
2870 /* Ignore any write to ROM. */
2873 static bool readonly_mem_accepts(void *opaque, hwaddr addr,
2874 unsigned size, bool is_write,
2875 MemTxAttrs attrs)
2877 return is_write;
2880 /* This will only be used for writes, because reads are special cased
2881 * to directly access the underlying host ram.
2883 static const MemoryRegionOps readonly_mem_ops = {
2884 .write = readonly_mem_write,
2885 .valid.accepts = readonly_mem_accepts,
2886 .endianness = DEVICE_NATIVE_ENDIAN,
2887 .valid = {
2888 .min_access_size = 1,
2889 .max_access_size = 8,
2890 .unaligned = false,
2892 .impl = {
2893 .min_access_size = 1,
2894 .max_access_size = 8,
2895 .unaligned = false,
2899 MemoryRegion *iotlb_to_region(CPUState *cpu, hwaddr index, MemTxAttrs attrs)
2901 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2902 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2903 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
2904 MemoryRegionSection *sections = d->map.sections;
2906 return sections[index & ~TARGET_PAGE_MASK].mr;
2909 static void io_mem_init(void)
2911 memory_region_init_io(&io_mem_rom, NULL, &readonly_mem_ops,
2912 NULL, NULL, UINT64_MAX);
2913 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2914 NULL, UINT64_MAX);
2916 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
2917 * which can be called without the iothread mutex.
2919 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
2920 NULL, UINT64_MAX);
2921 memory_region_clear_global_locking(&io_mem_notdirty);
2923 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
2924 NULL, UINT64_MAX);
2927 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2929 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2930 uint16_t n;
2932 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2933 assert(n == PHYS_SECTION_UNASSIGNED);
2934 n = dummy_section(&d->map, fv, &io_mem_notdirty);
2935 assert(n == PHYS_SECTION_NOTDIRTY);
2936 n = dummy_section(&d->map, fv, &io_mem_rom);
2937 assert(n == PHYS_SECTION_ROM);
2938 n = dummy_section(&d->map, fv, &io_mem_watch);
2939 assert(n == PHYS_SECTION_WATCH);
2941 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2943 return d;
2946 void address_space_dispatch_free(AddressSpaceDispatch *d)
2948 phys_sections_free(&d->map);
2949 g_free(d);
2952 static void tcg_commit(MemoryListener *listener)
2954 CPUAddressSpace *cpuas;
2955 AddressSpaceDispatch *d;
2957 /* since each CPU stores ram addresses in its TLB cache, we must
2958 reset the modified entries */
2959 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2960 cpu_reloading_memory_map();
2961 /* The CPU and TLB are protected by the iothread lock.
2962 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2963 * may have split the RCU critical section.
2965 d = address_space_to_dispatch(cpuas->as);
2966 atomic_rcu_set(&cpuas->memory_dispatch, d);
2967 tlb_flush(cpuas->cpu);
2970 static void memory_map_init(void)
2972 system_memory = g_malloc(sizeof(*system_memory));
2974 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2975 address_space_init(&address_space_memory, system_memory, "memory");
2977 system_io = g_malloc(sizeof(*system_io));
2978 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2979 65536);
2980 address_space_init(&address_space_io, system_io, "I/O");
2983 MemoryRegion *get_system_memory(void)
2985 return system_memory;
2988 MemoryRegion *get_system_io(void)
2990 return system_io;
2993 #endif /* !defined(CONFIG_USER_ONLY) */
2995 /* physical memory access (slow version, mainly for debug) */
2996 #if defined(CONFIG_USER_ONLY)
2997 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
2998 uint8_t *buf, int len, int is_write)
3000 int l, flags;
3001 target_ulong page;
3002 void * p;
3004 while (len > 0) {
3005 page = addr & TARGET_PAGE_MASK;
3006 l = (page + TARGET_PAGE_SIZE) - addr;
3007 if (l > len)
3008 l = len;
3009 flags = page_get_flags(page);
3010 if (!(flags & PAGE_VALID))
3011 return -1;
3012 if (is_write) {
3013 if (!(flags & PAGE_WRITE))
3014 return -1;
3015 /* XXX: this code should not depend on lock_user */
3016 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
3017 return -1;
3018 memcpy(p, buf, l);
3019 unlock_user(p, addr, l);
3020 } else {
3021 if (!(flags & PAGE_READ))
3022 return -1;
3023 /* XXX: this code should not depend on lock_user */
3024 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
3025 return -1;
3026 memcpy(buf, p, l);
3027 unlock_user(p, addr, 0);
3029 len -= l;
3030 buf += l;
3031 addr += l;
3033 return 0;
3036 #else
3038 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
3039 hwaddr length)
3041 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
3042 addr += memory_region_get_ram_addr(mr);
3044 /* No early return if dirty_log_mask is or becomes 0, because
3045 * cpu_physical_memory_set_dirty_range will still call
3046 * xen_modified_memory.
3048 if (dirty_log_mask) {
3049 dirty_log_mask =
3050 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
3052 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
3053 assert(tcg_enabled());
3054 tb_lock();
3055 tb_invalidate_phys_range(addr, addr + length);
3056 tb_unlock();
3057 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
3059 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
3062 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
3064 unsigned access_size_max = mr->ops->valid.max_access_size;
3066 /* Regions are assumed to support 1-4 byte accesses unless
3067 otherwise specified. */
3068 if (access_size_max == 0) {
3069 access_size_max = 4;
3072 /* Bound the maximum access by the alignment of the address. */
3073 if (!mr->ops->impl.unaligned) {
3074 unsigned align_size_max = addr & -addr;
3075 if (align_size_max != 0 && align_size_max < access_size_max) {
3076 access_size_max = align_size_max;
3080 /* Don't attempt accesses larger than the maximum. */
3081 if (l > access_size_max) {
3082 l = access_size_max;
3084 l = pow2floor(l);
3086 return l;
3089 static bool prepare_mmio_access(MemoryRegion *mr)
3091 bool unlocked = !qemu_mutex_iothread_locked();
3092 bool release_lock = false;
3094 if (unlocked && mr->global_locking) {
3095 qemu_mutex_lock_iothread();
3096 unlocked = false;
3097 release_lock = true;
3099 if (mr->flush_coalesced_mmio) {
3100 if (unlocked) {
3101 qemu_mutex_lock_iothread();
3103 qemu_flush_coalesced_mmio_buffer();
3104 if (unlocked) {
3105 qemu_mutex_unlock_iothread();
3109 return release_lock;
3112 /* Called within RCU critical section. */
3113 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
3114 MemTxAttrs attrs,
3115 const uint8_t *buf,
3116 int len, hwaddr addr1,
3117 hwaddr l, MemoryRegion *mr)
3119 uint8_t *ptr;
3120 uint64_t val;
3121 MemTxResult result = MEMTX_OK;
3122 bool release_lock = false;
3124 for (;;) {
3125 if (!memory_access_is_direct(mr, true)) {
3126 release_lock |= prepare_mmio_access(mr);
3127 l = memory_access_size(mr, l, addr1);
3128 /* XXX: could force current_cpu to NULL to avoid
3129 potential bugs */
3130 switch (l) {
3131 case 8:
3132 /* 64 bit write access */
3133 val = ldq_p(buf);
3134 result |= memory_region_dispatch_write(mr, addr1, val, 8,
3135 attrs);
3136 break;
3137 case 4:
3138 /* 32 bit write access */
3139 val = (uint32_t)ldl_p(buf);
3140 result |= memory_region_dispatch_write(mr, addr1, val, 4,
3141 attrs);
3142 break;
3143 case 2:
3144 /* 16 bit write access */
3145 val = lduw_p(buf);
3146 result |= memory_region_dispatch_write(mr, addr1, val, 2,
3147 attrs);
3148 break;
3149 case 1:
3150 /* 8 bit write access */
3151 val = ldub_p(buf);
3152 result |= memory_region_dispatch_write(mr, addr1, val, 1,
3153 attrs);
3154 break;
3155 default:
3156 abort();
3158 } else {
3159 /* RAM case */
3160 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3161 memcpy(ptr, buf, l);
3162 invalidate_and_set_dirty(mr, addr1, l);
3165 if (release_lock) {
3166 qemu_mutex_unlock_iothread();
3167 release_lock = false;
3170 len -= l;
3171 buf += l;
3172 addr += l;
3174 if (!len) {
3175 break;
3178 l = len;
3179 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
3182 return result;
3185 /* Called from RCU critical section. */
3186 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
3187 const uint8_t *buf, int len)
3189 hwaddr l;
3190 hwaddr addr1;
3191 MemoryRegion *mr;
3192 MemTxResult result = MEMTX_OK;
3194 l = len;
3195 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
3196 result = flatview_write_continue(fv, addr, attrs, buf, len,
3197 addr1, l, mr);
3199 return result;
3202 /* Called within RCU critical section. */
3203 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
3204 MemTxAttrs attrs, uint8_t *buf,
3205 int len, hwaddr addr1, hwaddr l,
3206 MemoryRegion *mr)
3208 uint8_t *ptr;
3209 uint64_t val;
3210 MemTxResult result = MEMTX_OK;
3211 bool release_lock = false;
3213 for (;;) {
3214 if (!memory_access_is_direct(mr, false)) {
3215 /* I/O case */
3216 release_lock |= prepare_mmio_access(mr);
3217 l = memory_access_size(mr, l, addr1);
3218 switch (l) {
3219 case 8:
3220 /* 64 bit read access */
3221 result |= memory_region_dispatch_read(mr, addr1, &val, 8,
3222 attrs);
3223 stq_p(buf, val);
3224 break;
3225 case 4:
3226 /* 32 bit read access */
3227 result |= memory_region_dispatch_read(mr, addr1, &val, 4,
3228 attrs);
3229 stl_p(buf, val);
3230 break;
3231 case 2:
3232 /* 16 bit read access */
3233 result |= memory_region_dispatch_read(mr, addr1, &val, 2,
3234 attrs);
3235 stw_p(buf, val);
3236 break;
3237 case 1:
3238 /* 8 bit read access */
3239 result |= memory_region_dispatch_read(mr, addr1, &val, 1,
3240 attrs);
3241 stb_p(buf, val);
3242 break;
3243 default:
3244 abort();
3246 } else {
3247 /* RAM case */
3248 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3249 memcpy(buf, ptr, l);
3252 if (release_lock) {
3253 qemu_mutex_unlock_iothread();
3254 release_lock = false;
3257 len -= l;
3258 buf += l;
3259 addr += l;
3261 if (!len) {
3262 break;
3265 l = len;
3266 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3269 return result;
3272 /* Called from RCU critical section. */
3273 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
3274 MemTxAttrs attrs, uint8_t *buf, int len)
3276 hwaddr l;
3277 hwaddr addr1;
3278 MemoryRegion *mr;
3280 l = len;
3281 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3282 return flatview_read_continue(fv, addr, attrs, buf, len,
3283 addr1, l, mr);
3286 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3287 MemTxAttrs attrs, uint8_t *buf, int len)
3289 MemTxResult result = MEMTX_OK;
3290 FlatView *fv;
3292 if (len > 0) {
3293 rcu_read_lock();
3294 fv = address_space_to_flatview(as);
3295 result = flatview_read(fv, addr, attrs, buf, len);
3296 rcu_read_unlock();
3299 return result;
3302 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
3303 MemTxAttrs attrs,
3304 const uint8_t *buf, int len)
3306 MemTxResult result = MEMTX_OK;
3307 FlatView *fv;
3309 if (len > 0) {
3310 rcu_read_lock();
3311 fv = address_space_to_flatview(as);
3312 result = flatview_write(fv, addr, attrs, buf, len);
3313 rcu_read_unlock();
3316 return result;
3319 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3320 uint8_t *buf, int 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, uint8_t *buf,
3330 int len, int 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 void cpu_physical_memory_write_rom_internal(AddressSpace *as,
3342 hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
3344 hwaddr l;
3345 uint8_t *ptr;
3346 hwaddr addr1;
3347 MemoryRegion *mr;
3349 rcu_read_lock();
3350 while (len > 0) {
3351 l = len;
3352 mr = address_space_translate(as, addr, &addr1, &l, true,
3353 MEMTXATTRS_UNSPECIFIED);
3355 if (!(memory_region_is_ram(mr) ||
3356 memory_region_is_romd(mr))) {
3357 l = memory_access_size(mr, l, addr1);
3358 } else {
3359 /* ROM/RAM case */
3360 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3361 switch (type) {
3362 case WRITE_DATA:
3363 memcpy(ptr, buf, l);
3364 invalidate_and_set_dirty(mr, addr1, l);
3365 break;
3366 case FLUSH_CACHE:
3367 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
3368 break;
3371 len -= l;
3372 buf += l;
3373 addr += l;
3375 rcu_read_unlock();
3378 /* used for ROM loading : can write in RAM and ROM */
3379 void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
3380 const uint8_t *buf, int len)
3382 cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
3385 void cpu_flush_icache_range(hwaddr start, int len)
3388 * This function should do the same thing as an icache flush that was
3389 * triggered from within the guest. For TCG we are always cache coherent,
3390 * so there is no need to flush anything. For KVM / Xen we need to flush
3391 * the host's instruction cache at least.
3393 if (tcg_enabled()) {
3394 return;
3397 cpu_physical_memory_write_rom_internal(&address_space_memory,
3398 start, NULL, len, FLUSH_CACHE);
3401 typedef struct {
3402 MemoryRegion *mr;
3403 void *buffer;
3404 hwaddr addr;
3405 hwaddr len;
3406 bool in_use;
3407 } BounceBuffer;
3409 static BounceBuffer bounce;
3411 typedef struct MapClient {
3412 QEMUBH *bh;
3413 QLIST_ENTRY(MapClient) link;
3414 } MapClient;
3416 QemuMutex map_client_list_lock;
3417 static QLIST_HEAD(map_client_list, MapClient) map_client_list
3418 = QLIST_HEAD_INITIALIZER(map_client_list);
3420 static void cpu_unregister_map_client_do(MapClient *client)
3422 QLIST_REMOVE(client, link);
3423 g_free(client);
3426 static void cpu_notify_map_clients_locked(void)
3428 MapClient *client;
3430 while (!QLIST_EMPTY(&map_client_list)) {
3431 client = QLIST_FIRST(&map_client_list);
3432 qemu_bh_schedule(client->bh);
3433 cpu_unregister_map_client_do(client);
3437 void cpu_register_map_client(QEMUBH *bh)
3439 MapClient *client = g_malloc(sizeof(*client));
3441 qemu_mutex_lock(&map_client_list_lock);
3442 client->bh = bh;
3443 QLIST_INSERT_HEAD(&map_client_list, client, link);
3444 if (!atomic_read(&bounce.in_use)) {
3445 cpu_notify_map_clients_locked();
3447 qemu_mutex_unlock(&map_client_list_lock);
3450 void cpu_exec_init_all(void)
3452 qemu_mutex_init(&ram_list.mutex);
3453 /* The data structures we set up here depend on knowing the page size,
3454 * so no more changes can be made after this point.
3455 * In an ideal world, nothing we did before we had finished the
3456 * machine setup would care about the target page size, and we could
3457 * do this much later, rather than requiring board models to state
3458 * up front what their requirements are.
3460 finalize_target_page_bits();
3461 io_mem_init();
3462 memory_map_init();
3463 qemu_mutex_init(&map_client_list_lock);
3466 void cpu_unregister_map_client(QEMUBH *bh)
3468 MapClient *client;
3470 qemu_mutex_lock(&map_client_list_lock);
3471 QLIST_FOREACH(client, &map_client_list, link) {
3472 if (client->bh == bh) {
3473 cpu_unregister_map_client_do(client);
3474 break;
3477 qemu_mutex_unlock(&map_client_list_lock);
3480 static void cpu_notify_map_clients(void)
3482 qemu_mutex_lock(&map_client_list_lock);
3483 cpu_notify_map_clients_locked();
3484 qemu_mutex_unlock(&map_client_list_lock);
3487 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
3488 bool is_write, MemTxAttrs attrs)
3490 MemoryRegion *mr;
3491 hwaddr l, xlat;
3493 while (len > 0) {
3494 l = len;
3495 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3496 if (!memory_access_is_direct(mr, is_write)) {
3497 l = memory_access_size(mr, l, addr);
3498 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3499 return false;
3503 len -= l;
3504 addr += l;
3506 return true;
3509 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3510 int len, bool is_write,
3511 MemTxAttrs attrs)
3513 FlatView *fv;
3514 bool result;
3516 rcu_read_lock();
3517 fv = address_space_to_flatview(as);
3518 result = flatview_access_valid(fv, addr, len, is_write, attrs);
3519 rcu_read_unlock();
3520 return result;
3523 static hwaddr
3524 flatview_extend_translation(FlatView *fv, hwaddr addr,
3525 hwaddr target_len,
3526 MemoryRegion *mr, hwaddr base, hwaddr len,
3527 bool is_write, MemTxAttrs attrs)
3529 hwaddr done = 0;
3530 hwaddr xlat;
3531 MemoryRegion *this_mr;
3533 for (;;) {
3534 target_len -= len;
3535 addr += len;
3536 done += len;
3537 if (target_len == 0) {
3538 return done;
3541 len = target_len;
3542 this_mr = flatview_translate(fv, addr, &xlat,
3543 &len, is_write, attrs);
3544 if (this_mr != mr || xlat != base + done) {
3545 return done;
3550 /* Map a physical memory region into a host virtual address.
3551 * May map a subset of the requested range, given by and returned in *plen.
3552 * May return NULL if resources needed to perform the mapping are exhausted.
3553 * Use only for reads OR writes - not for read-modify-write operations.
3554 * Use cpu_register_map_client() to know when retrying the map operation is
3555 * likely to succeed.
3557 void *address_space_map(AddressSpace *as,
3558 hwaddr addr,
3559 hwaddr *plen,
3560 bool is_write,
3561 MemTxAttrs attrs)
3563 hwaddr len = *plen;
3564 hwaddr l, xlat;
3565 MemoryRegion *mr;
3566 void *ptr;
3567 FlatView *fv;
3569 if (len == 0) {
3570 return NULL;
3573 l = len;
3574 rcu_read_lock();
3575 fv = address_space_to_flatview(as);
3576 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3578 if (!memory_access_is_direct(mr, is_write)) {
3579 if (atomic_xchg(&bounce.in_use, true)) {
3580 rcu_read_unlock();
3581 return NULL;
3583 /* Avoid unbounded allocations */
3584 l = MIN(l, TARGET_PAGE_SIZE);
3585 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3586 bounce.addr = addr;
3587 bounce.len = l;
3589 memory_region_ref(mr);
3590 bounce.mr = mr;
3591 if (!is_write) {
3592 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3593 bounce.buffer, l);
3596 rcu_read_unlock();
3597 *plen = l;
3598 return bounce.buffer;
3602 memory_region_ref(mr);
3603 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3604 l, is_write, attrs);
3605 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3606 rcu_read_unlock();
3608 return ptr;
3611 /* Unmaps a memory region previously mapped by address_space_map().
3612 * Will also mark the memory as dirty if is_write == 1. access_len gives
3613 * the amount of memory that was actually read or written by the caller.
3615 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3616 int is_write, hwaddr access_len)
3618 if (buffer != bounce.buffer) {
3619 MemoryRegion *mr;
3620 ram_addr_t addr1;
3622 mr = memory_region_from_host(buffer, &addr1);
3623 assert(mr != NULL);
3624 if (is_write) {
3625 invalidate_and_set_dirty(mr, addr1, access_len);
3627 if (xen_enabled()) {
3628 xen_invalidate_map_cache_entry(buffer);
3630 memory_region_unref(mr);
3631 return;
3633 if (is_write) {
3634 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3635 bounce.buffer, access_len);
3637 qemu_vfree(bounce.buffer);
3638 bounce.buffer = NULL;
3639 memory_region_unref(bounce.mr);
3640 atomic_mb_set(&bounce.in_use, false);
3641 cpu_notify_map_clients();
3644 void *cpu_physical_memory_map(hwaddr addr,
3645 hwaddr *plen,
3646 int is_write)
3648 return address_space_map(&address_space_memory, addr, plen, is_write,
3649 MEMTXATTRS_UNSPECIFIED);
3652 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3653 int is_write, hwaddr access_len)
3655 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3658 #define ARG1_DECL AddressSpace *as
3659 #define ARG1 as
3660 #define SUFFIX
3661 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3662 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3663 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3664 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3665 #define RCU_READ_LOCK(...) rcu_read_lock()
3666 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3667 #include "memory_ldst.inc.c"
3669 int64_t address_space_cache_init(MemoryRegionCache *cache,
3670 AddressSpace *as,
3671 hwaddr addr,
3672 hwaddr len,
3673 bool is_write)
3675 AddressSpaceDispatch *d;
3676 hwaddr l;
3677 MemoryRegion *mr;
3679 assert(len > 0);
3681 l = len;
3682 cache->fv = address_space_get_flatview(as);
3683 d = flatview_to_dispatch(cache->fv);
3684 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3686 mr = cache->mrs.mr;
3687 memory_region_ref(mr);
3688 if (memory_access_is_direct(mr, is_write)) {
3689 /* We don't care about the memory attributes here as we're only
3690 * doing this if we found actual RAM, which behaves the same
3691 * regardless of attributes; so UNSPECIFIED is fine.
3693 l = flatview_extend_translation(cache->fv, addr, len, mr,
3694 cache->xlat, l, is_write,
3695 MEMTXATTRS_UNSPECIFIED);
3696 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3697 } else {
3698 cache->ptr = NULL;
3701 cache->len = l;
3702 cache->is_write = is_write;
3703 return l;
3706 void address_space_cache_invalidate(MemoryRegionCache *cache,
3707 hwaddr addr,
3708 hwaddr access_len)
3710 assert(cache->is_write);
3711 if (likely(cache->ptr)) {
3712 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3716 void address_space_cache_destroy(MemoryRegionCache *cache)
3718 if (!cache->mrs.mr) {
3719 return;
3722 if (xen_enabled()) {
3723 xen_invalidate_map_cache_entry(cache->ptr);
3725 memory_region_unref(cache->mrs.mr);
3726 flatview_unref(cache->fv);
3727 cache->mrs.mr = NULL;
3728 cache->fv = NULL;
3731 /* Called from RCU critical section. This function has the same
3732 * semantics as address_space_translate, but it only works on a
3733 * predefined range of a MemoryRegion that was mapped with
3734 * address_space_cache_init.
3736 static inline MemoryRegion *address_space_translate_cached(
3737 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3738 hwaddr *plen, bool is_write, MemTxAttrs attrs)
3740 MemoryRegionSection section;
3741 MemoryRegion *mr;
3742 IOMMUMemoryRegion *iommu_mr;
3743 AddressSpace *target_as;
3745 assert(!cache->ptr);
3746 *xlat = addr + cache->xlat;
3748 mr = cache->mrs.mr;
3749 iommu_mr = memory_region_get_iommu(mr);
3750 if (!iommu_mr) {
3751 /* MMIO region. */
3752 return mr;
3755 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3756 NULL, is_write, true,
3757 &target_as, attrs);
3758 return section.mr;
3761 /* Called from RCU critical section. address_space_read_cached uses this
3762 * out of line function when the target is an MMIO or IOMMU region.
3764 void
3765 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3766 void *buf, int len)
3768 hwaddr addr1, l;
3769 MemoryRegion *mr;
3771 l = len;
3772 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3773 MEMTXATTRS_UNSPECIFIED);
3774 flatview_read_continue(cache->fv,
3775 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3776 addr1, l, mr);
3779 /* Called from RCU critical section. address_space_write_cached uses this
3780 * out of line function when the target is an MMIO or IOMMU region.
3782 void
3783 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3784 const void *buf, int len)
3786 hwaddr addr1, l;
3787 MemoryRegion *mr;
3789 l = len;
3790 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3791 MEMTXATTRS_UNSPECIFIED);
3792 flatview_write_continue(cache->fv,
3793 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3794 addr1, l, mr);
3797 #define ARG1_DECL MemoryRegionCache *cache
3798 #define ARG1 cache
3799 #define SUFFIX _cached_slow
3800 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3801 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3802 #define MAP_RAM(mr, ofs) (cache->ptr + (ofs - cache->xlat))
3803 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3804 #define RCU_READ_LOCK() ((void)0)
3805 #define RCU_READ_UNLOCK() ((void)0)
3806 #include "memory_ldst.inc.c"
3808 /* virtual memory access for debug (includes writing to ROM) */
3809 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3810 uint8_t *buf, int len, int is_write)
3812 int l;
3813 hwaddr phys_addr;
3814 target_ulong page;
3816 cpu_synchronize_state(cpu);
3817 while (len > 0) {
3818 int asidx;
3819 MemTxAttrs attrs;
3821 page = addr & TARGET_PAGE_MASK;
3822 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3823 asidx = cpu_asidx_from_attrs(cpu, attrs);
3824 /* if no physical page mapped, return an error */
3825 if (phys_addr == -1)
3826 return -1;
3827 l = (page + TARGET_PAGE_SIZE) - addr;
3828 if (l > len)
3829 l = len;
3830 phys_addr += (addr & ~TARGET_PAGE_MASK);
3831 if (is_write) {
3832 cpu_physical_memory_write_rom(cpu->cpu_ases[asidx].as,
3833 phys_addr, buf, l);
3834 } else {
3835 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3836 MEMTXATTRS_UNSPECIFIED,
3837 buf, l, 0);
3839 len -= l;
3840 buf += l;
3841 addr += l;
3843 return 0;
3847 * Allows code that needs to deal with migration bitmaps etc to still be built
3848 * target independent.
3850 size_t qemu_target_page_size(void)
3852 return TARGET_PAGE_SIZE;
3855 int qemu_target_page_bits(void)
3857 return TARGET_PAGE_BITS;
3860 int qemu_target_page_bits_min(void)
3862 return TARGET_PAGE_BITS_MIN;
3864 #endif
3867 * A helper function for the _utterly broken_ virtio device model to find out if
3868 * it's running on a big endian machine. Don't do this at home kids!
3870 bool target_words_bigendian(void);
3871 bool target_words_bigendian(void)
3873 #if defined(TARGET_WORDS_BIGENDIAN)
3874 return true;
3875 #else
3876 return false;
3877 #endif
3880 #ifndef CONFIG_USER_ONLY
3881 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3883 MemoryRegion*mr;
3884 hwaddr l = 1;
3885 bool res;
3887 rcu_read_lock();
3888 mr = address_space_translate(&address_space_memory,
3889 phys_addr, &phys_addr, &l, false,
3890 MEMTXATTRS_UNSPECIFIED);
3892 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3893 rcu_read_unlock();
3894 return res;
3897 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3899 RAMBlock *block;
3900 int ret = 0;
3902 rcu_read_lock();
3903 RAMBLOCK_FOREACH(block) {
3904 ret = func(block->idstr, block->host, block->offset,
3905 block->used_length, opaque);
3906 if (ret) {
3907 break;
3910 rcu_read_unlock();
3911 return ret;
3914 int qemu_ram_foreach_migratable_block(RAMBlockIterFunc func, void *opaque)
3916 RAMBlock *block;
3917 int ret = 0;
3919 rcu_read_lock();
3920 RAMBLOCK_FOREACH(block) {
3921 if (!qemu_ram_is_migratable(block)) {
3922 continue;
3924 ret = func(block->idstr, block->host, block->offset,
3925 block->used_length, opaque);
3926 if (ret) {
3927 break;
3930 rcu_read_unlock();
3931 return ret;
3935 * Unmap pages of memory from start to start+length such that
3936 * they a) read as 0, b) Trigger whatever fault mechanism
3937 * the OS provides for postcopy.
3938 * The pages must be unmapped by the end of the function.
3939 * Returns: 0 on success, none-0 on failure
3942 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3944 int ret = -1;
3946 uint8_t *host_startaddr = rb->host + start;
3948 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
3949 error_report("ram_block_discard_range: Unaligned start address: %p",
3950 host_startaddr);
3951 goto err;
3954 if ((start + length) <= rb->used_length) {
3955 bool need_madvise, need_fallocate;
3956 uint8_t *host_endaddr = host_startaddr + length;
3957 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
3958 error_report("ram_block_discard_range: Unaligned end address: %p",
3959 host_endaddr);
3960 goto err;
3963 errno = ENOTSUP; /* If we are missing MADVISE etc */
3965 /* The logic here is messy;
3966 * madvise DONTNEED fails for hugepages
3967 * fallocate works on hugepages and shmem
3969 need_madvise = (rb->page_size == qemu_host_page_size);
3970 need_fallocate = rb->fd != -1;
3971 if (need_fallocate) {
3972 /* For a file, this causes the area of the file to be zero'd
3973 * if read, and for hugetlbfs also causes it to be unmapped
3974 * so a userfault will trigger.
3976 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3977 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3978 start, length);
3979 if (ret) {
3980 ret = -errno;
3981 error_report("ram_block_discard_range: Failed to fallocate "
3982 "%s:%" PRIx64 " +%zx (%d)",
3983 rb->idstr, start, length, ret);
3984 goto err;
3986 #else
3987 ret = -ENOSYS;
3988 error_report("ram_block_discard_range: fallocate not available/file"
3989 "%s:%" PRIx64 " +%zx (%d)",
3990 rb->idstr, start, length, ret);
3991 goto err;
3992 #endif
3994 if (need_madvise) {
3995 /* For normal RAM this causes it to be unmapped,
3996 * for shared memory it causes the local mapping to disappear
3997 * and to fall back on the file contents (which we just
3998 * fallocate'd away).
4000 #if defined(CONFIG_MADVISE)
4001 ret = madvise(host_startaddr, length, MADV_DONTNEED);
4002 if (ret) {
4003 ret = -errno;
4004 error_report("ram_block_discard_range: Failed to discard range "
4005 "%s:%" PRIx64 " +%zx (%d)",
4006 rb->idstr, start, length, ret);
4007 goto err;
4009 #else
4010 ret = -ENOSYS;
4011 error_report("ram_block_discard_range: MADVISE not available"
4012 "%s:%" PRIx64 " +%zx (%d)",
4013 rb->idstr, start, length, ret);
4014 goto err;
4015 #endif
4017 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
4018 need_madvise, need_fallocate, ret);
4019 } else {
4020 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
4021 "/%zx/" RAM_ADDR_FMT")",
4022 rb->idstr, start, length, rb->used_length);
4025 err:
4026 return ret;
4029 #endif
4031 void page_size_init(void)
4033 /* NOTE: we can always suppose that qemu_host_page_size >=
4034 TARGET_PAGE_SIZE */
4035 if (qemu_host_page_size == 0) {
4036 qemu_host_page_size = qemu_real_host_page_size;
4038 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
4039 qemu_host_page_size = TARGET_PAGE_SIZE;
4041 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;
4044 #if !defined(CONFIG_USER_ONLY)
4046 static void mtree_print_phys_entries(fprintf_function mon, void *f,
4047 int start, int end, int skip, int ptr)
4049 if (start == end - 1) {
4050 mon(f, "\t%3d ", start);
4051 } else {
4052 mon(f, "\t%3d..%-3d ", start, end - 1);
4054 mon(f, " skip=%d ", skip);
4055 if (ptr == PHYS_MAP_NODE_NIL) {
4056 mon(f, " ptr=NIL");
4057 } else if (!skip) {
4058 mon(f, " ptr=#%d", ptr);
4059 } else {
4060 mon(f, " ptr=[%d]", ptr);
4062 mon(f, "\n");
4065 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
4066 int128_sub((size), int128_one())) : 0)
4068 void mtree_print_dispatch(fprintf_function mon, void *f,
4069 AddressSpaceDispatch *d, MemoryRegion *root)
4071 int i;
4073 mon(f, " Dispatch\n");
4074 mon(f, " Physical sections\n");
4076 for (i = 0; i < d->map.sections_nb; ++i) {
4077 MemoryRegionSection *s = d->map.sections + i;
4078 const char *names[] = { " [unassigned]", " [not dirty]",
4079 " [ROM]", " [watch]" };
4081 mon(f, " #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx " %s%s%s%s%s",
4083 s->offset_within_address_space,
4084 s->offset_within_address_space + MR_SIZE(s->mr->size),
4085 s->mr->name ? s->mr->name : "(noname)",
4086 i < ARRAY_SIZE(names) ? names[i] : "",
4087 s->mr == root ? " [ROOT]" : "",
4088 s == d->mru_section ? " [MRU]" : "",
4089 s->mr->is_iommu ? " [iommu]" : "");
4091 if (s->mr->alias) {
4092 mon(f, " alias=%s", s->mr->alias->name ?
4093 s->mr->alias->name : "noname");
4095 mon(f, "\n");
4098 mon(f, " Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
4099 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
4100 for (i = 0; i < d->map.nodes_nb; ++i) {
4101 int j, jprev;
4102 PhysPageEntry prev;
4103 Node *n = d->map.nodes + i;
4105 mon(f, " [%d]\n", i);
4107 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
4108 PhysPageEntry *pe = *n + j;
4110 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
4111 continue;
4114 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
4116 jprev = j;
4117 prev = *pe;
4120 if (jprev != ARRAY_SIZE(*n)) {
4121 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
4126 #endif