Merge tag 'v2.10.0-rc1'
[qemu/ar7.git] / exec.c
blob354de0fe8f88b80ad436a320c0f529f35548567d
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"
21 #ifndef _WIN32
22 #endif
24 #include "qemu/cutils.h"
25 #include "cpu.h"
26 #include "exec/exec-all.h"
27 #include "exec/target_page.h"
28 #include "tcg.h"
29 #include "hw/qdev-core.h"
30 #include "hw/qdev-properties.h"
31 #if !defined(CONFIG_USER_ONLY)
32 #include "hw/boards.h"
33 #include "hw/xen/xen.h"
34 #endif
35 #include "sysemu/kvm.h"
36 #include "sysemu/sysemu.h"
37 #include "qemu/timer.h"
38 #include "qemu/config-file.h"
39 #include "qemu/error-report.h"
40 #if defined(CONFIG_USER_ONLY)
41 #include "qemu.h"
42 #else /* !CONFIG_USER_ONLY */
43 #include "hw/hw.h"
44 #include "exec/memory.h"
45 #include "exec/ioport.h"
46 #include "sysemu/dma.h"
47 #include "sysemu/numa.h"
48 #include "sysemu/hw_accel.h"
49 #include "exec/address-spaces.h"
50 #include "sysemu/xen-mapcache.h"
51 #include "trace-root.h"
53 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
54 #include <fcntl.h>
55 #include <linux/falloc.h>
56 #endif
58 #endif
59 #include "exec/cpu-all.h"
60 #include "qemu/rcu_queue.h"
61 #include "qemu/main-loop.h"
62 #include "translate-all.h"
63 #include "sysemu/replay.h"
65 #include "exec/memory-internal.h"
66 #include "exec/ram_addr.h"
67 #include "exec/log.h"
69 #include "migration/vmstate.h"
71 #include "qemu/range.h"
72 #ifndef _WIN32
73 #include "qemu/mmap-alloc.h"
74 #endif
76 #include "monitor/monitor.h"
78 //#define DEBUG_SUBPAGE
80 #if !defined(CONFIG_USER_ONLY)
81 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
82 * are protected by the ramlist lock.
84 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
86 static MemoryRegion *system_memory;
87 static MemoryRegion *system_io;
89 AddressSpace address_space_io;
90 AddressSpace address_space_memory;
92 MemoryRegion io_mem_rom, io_mem_notdirty;
93 static MemoryRegion io_mem_unassigned;
95 /* RAM is pre-allocated and passed into qemu_ram_alloc_from_ptr */
96 #define RAM_PREALLOC (1 << 0)
98 /* RAM is mmap-ed with MAP_SHARED */
99 #define RAM_SHARED (1 << 1)
101 /* Only a portion of RAM (used_length) is actually used, and migrated.
102 * This used_length size can change across reboots.
104 #define RAM_RESIZEABLE (1 << 2)
106 #endif
108 #ifdef TARGET_PAGE_BITS_VARY
109 int target_page_bits;
110 bool target_page_bits_decided;
111 #endif
113 struct CPUTailQ cpus = QTAILQ_HEAD_INITIALIZER(cpus);
114 /* current CPU in the current thread. It is only valid inside
115 cpu_exec() */
116 __thread CPUState *current_cpu;
117 /* 0 = Do not count executed instructions.
118 1 = Precise instruction counting.
119 2 = Adaptive rate instruction counting. */
120 int use_icount;
122 uintptr_t qemu_host_page_size;
123 intptr_t qemu_host_page_mask;
124 uintptr_t qemu_real_host_page_size;
125 intptr_t qemu_real_host_page_mask;
127 bool set_preferred_target_page_bits(int bits)
129 /* The target page size is the lowest common denominator for all
130 * the CPUs in the system, so we can only make it smaller, never
131 * larger. And we can't make it smaller once we've committed to
132 * a particular size.
134 #ifdef TARGET_PAGE_BITS_VARY
135 assert(bits >= TARGET_PAGE_BITS_MIN);
136 if (target_page_bits == 0 || target_page_bits > bits) {
137 if (target_page_bits_decided) {
138 return false;
140 target_page_bits = bits;
142 #endif
143 return true;
146 #if !defined(CONFIG_USER_ONLY)
148 static void finalize_target_page_bits(void)
150 #ifdef TARGET_PAGE_BITS_VARY
151 if (target_page_bits == 0) {
152 target_page_bits = TARGET_PAGE_BITS_MIN;
154 target_page_bits_decided = true;
155 #endif
158 typedef struct PhysPageEntry PhysPageEntry;
160 struct PhysPageEntry {
161 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
162 uint32_t skip : 6;
163 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
164 uint32_t ptr : 26;
167 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
169 /* Size of the L2 (and L3, etc) page tables. */
170 #define ADDR_SPACE_BITS 64
172 #define P_L2_BITS 9
173 #define P_L2_SIZE (1 << P_L2_BITS)
175 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
177 typedef PhysPageEntry Node[P_L2_SIZE];
179 typedef struct PhysPageMap {
180 struct rcu_head rcu;
182 unsigned sections_nb;
183 unsigned sections_nb_alloc;
184 unsigned nodes_nb;
185 unsigned nodes_nb_alloc;
186 Node *nodes;
187 MemoryRegionSection *sections;
188 } PhysPageMap;
190 struct AddressSpaceDispatch {
191 struct rcu_head rcu;
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;
199 AddressSpace *as;
202 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
203 typedef struct subpage_t {
204 MemoryRegion iomem;
205 AddressSpace *as;
206 hwaddr base;
207 uint16_t sub_section[];
208 } subpage_t;
210 #define PHYS_SECTION_UNASSIGNED 0
211 #define PHYS_SECTION_NOTDIRTY 1
212 #define PHYS_SECTION_ROM 2
213 #define PHYS_SECTION_WATCH 3
215 static void io_mem_init(void);
216 static void memory_map_init(void);
217 static void tcg_commit(MemoryListener *listener);
219 static MemoryRegion io_mem_watch;
222 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
223 * @cpu: the CPU whose AddressSpace this is
224 * @as: the AddressSpace itself
225 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
226 * @tcg_as_listener: listener for tracking changes to the AddressSpace
228 struct CPUAddressSpace {
229 CPUState *cpu;
230 AddressSpace *as;
231 struct AddressSpaceDispatch *memory_dispatch;
232 MemoryListener tcg_as_listener;
235 struct DirtyBitmapSnapshot {
236 ram_addr_t start;
237 ram_addr_t end;
238 unsigned long dirty[];
241 #endif
243 #if !defined(CONFIG_USER_ONLY)
245 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
247 static unsigned alloc_hint = 16;
248 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
249 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, alloc_hint);
250 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, map->nodes_nb + nodes);
251 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
252 alloc_hint = map->nodes_nb_alloc;
256 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
258 unsigned i;
259 uint32_t ret;
260 PhysPageEntry e;
261 PhysPageEntry *p;
263 ret = map->nodes_nb++;
264 p = map->nodes[ret];
265 assert(ret != PHYS_MAP_NODE_NIL);
266 assert(ret != map->nodes_nb_alloc);
268 e.skip = leaf ? 0 : 1;
269 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
270 for (i = 0; i < P_L2_SIZE; ++i) {
271 memcpy(&p[i], &e, sizeof(e));
273 return ret;
276 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
277 hwaddr *index, hwaddr *nb, uint16_t leaf,
278 int level)
280 PhysPageEntry *p;
281 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
283 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
284 lp->ptr = phys_map_node_alloc(map, level == 0);
286 p = map->nodes[lp->ptr];
287 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
289 while (*nb && lp < &p[P_L2_SIZE]) {
290 if ((*index & (step - 1)) == 0 && *nb >= step) {
291 lp->skip = 0;
292 lp->ptr = leaf;
293 *index += step;
294 *nb -= step;
295 } else {
296 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
298 ++lp;
302 static void phys_page_set(AddressSpaceDispatch *d,
303 hwaddr index, hwaddr nb,
304 uint16_t leaf)
306 /* Wildly overreserve - it doesn't matter much. */
307 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
309 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
312 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
313 * and update our entry so we can skip it and go directly to the destination.
315 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
317 unsigned valid_ptr = P_L2_SIZE;
318 int valid = 0;
319 PhysPageEntry *p;
320 int i;
322 if (lp->ptr == PHYS_MAP_NODE_NIL) {
323 return;
326 p = nodes[lp->ptr];
327 for (i = 0; i < P_L2_SIZE; i++) {
328 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
329 continue;
332 valid_ptr = i;
333 valid++;
334 if (p[i].skip) {
335 phys_page_compact(&p[i], nodes);
339 /* We can only compress if there's only one child. */
340 if (valid != 1) {
341 return;
344 assert(valid_ptr < P_L2_SIZE);
346 /* Don't compress if it won't fit in the # of bits we have. */
347 if (lp->skip + p[valid_ptr].skip >= (1 << 3)) {
348 return;
351 lp->ptr = p[valid_ptr].ptr;
352 if (!p[valid_ptr].skip) {
353 /* If our only child is a leaf, make this a leaf. */
354 /* By design, we should have made this node a leaf to begin with so we
355 * should never reach here.
356 * But since it's so simple to handle this, let's do it just in case we
357 * change this rule.
359 lp->skip = 0;
360 } else {
361 lp->skip += p[valid_ptr].skip;
365 static void phys_page_compact_all(AddressSpaceDispatch *d, int nodes_nb)
367 if (d->phys_map.skip) {
368 phys_page_compact(&d->phys_map, d->map.nodes);
372 static inline bool section_covers_addr(const MemoryRegionSection *section,
373 hwaddr addr)
375 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
376 * the section must cover the entire address space.
378 return int128_gethi(section->size) ||
379 range_covers_byte(section->offset_within_address_space,
380 int128_getlo(section->size), addr);
383 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
385 PhysPageEntry lp = d->phys_map, *p;
386 Node *nodes = d->map.nodes;
387 MemoryRegionSection *sections = d->map.sections;
388 hwaddr index = addr >> TARGET_PAGE_BITS;
389 int i;
391 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
392 if (lp.ptr == PHYS_MAP_NODE_NIL) {
393 return &sections[PHYS_SECTION_UNASSIGNED];
395 p = nodes[lp.ptr];
396 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
399 if (section_covers_addr(&sections[lp.ptr], addr)) {
400 return &sections[lp.ptr];
401 } else {
402 return &sections[PHYS_SECTION_UNASSIGNED];
406 bool memory_region_is_unassigned(MemoryRegion *mr)
408 return mr != &io_mem_rom && mr != &io_mem_notdirty && !mr->rom_device
409 && mr != &io_mem_watch;
412 /* Called from RCU critical section */
413 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
414 hwaddr addr,
415 bool resolve_subpage)
417 MemoryRegionSection *section = atomic_read(&d->mru_section);
418 subpage_t *subpage;
419 bool update;
421 if (section && section != &d->map.sections[PHYS_SECTION_UNASSIGNED] &&
422 section_covers_addr(section, addr)) {
423 update = false;
424 } else {
425 section = phys_page_find(d, addr);
426 update = true;
428 if (resolve_subpage && section->mr->subpage) {
429 subpage = container_of(section->mr, subpage_t, iomem);
430 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
432 if (update) {
433 atomic_set(&d->mru_section, section);
435 return section;
438 /* Called from RCU critical section */
439 static MemoryRegionSection *
440 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
441 hwaddr *plen, bool resolve_subpage)
443 MemoryRegionSection *section;
444 MemoryRegion *mr;
445 Int128 diff;
447 section = address_space_lookup_region(d, addr, resolve_subpage);
448 /* Compute offset within MemoryRegionSection */
449 addr -= section->offset_within_address_space;
451 /* Compute offset within MemoryRegion */
452 *xlat = addr + section->offset_within_region;
454 mr = section->mr;
456 /* MMIO registers can be expected to perform full-width accesses based only
457 * on their address, without considering adjacent registers that could
458 * decode to completely different MemoryRegions. When such registers
459 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
460 * regions overlap wildly. For this reason we cannot clamp the accesses
461 * here.
463 * If the length is small (as is the case for address_space_ldl/stl),
464 * everything works fine. If the incoming length is large, however,
465 * the caller really has to do the clamping through memory_access_size.
467 if (memory_region_is_ram(mr)) {
468 diff = int128_sub(section->size, int128_make64(addr));
469 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
471 return section;
474 /* Called from RCU critical section */
475 static MemoryRegionSection address_space_do_translate(AddressSpace *as,
476 hwaddr addr,
477 hwaddr *xlat,
478 hwaddr *plen,
479 bool is_write,
480 bool is_mmio)
482 IOMMUTLBEntry iotlb;
483 MemoryRegionSection *section;
484 IOMMUMemoryRegion *iommu_mr;
485 IOMMUMemoryRegionClass *imrc;
487 for (;;) {
488 AddressSpaceDispatch *d = atomic_rcu_read(&as->dispatch);
489 section = address_space_translate_internal(d, addr, &addr, plen, is_mmio);
491 iommu_mr = memory_region_get_iommu(section->mr);
492 if (!iommu_mr) {
493 break;
495 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
497 iotlb = imrc->translate(iommu_mr, addr, is_write ?
498 IOMMU_WO : IOMMU_RO);
499 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
500 | (addr & iotlb.addr_mask));
501 *plen = MIN(*plen, (addr | iotlb.addr_mask) - addr + 1);
502 if (!(iotlb.perm & (1 << is_write))) {
503 goto translate_fail;
506 as = iotlb.target_as;
509 *xlat = addr;
511 return *section;
513 translate_fail:
514 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
517 /* Called from RCU critical section */
518 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
519 bool is_write)
521 MemoryRegionSection section;
522 hwaddr xlat, plen;
524 /* Try to get maximum page mask during translation. */
525 plen = (hwaddr)-1;
527 /* This can never be MMIO. */
528 section = address_space_do_translate(as, addr, &xlat, &plen,
529 is_write, false);
531 /* Illegal translation */
532 if (section.mr == &io_mem_unassigned) {
533 goto iotlb_fail;
536 /* Convert memory region offset into address space offset */
537 xlat += section.offset_within_address_space -
538 section.offset_within_region;
540 if (plen == (hwaddr)-1) {
542 * We use default page size here. Logically it only happens
543 * for identity mappings.
545 plen = TARGET_PAGE_SIZE;
548 /* Convert to address mask */
549 plen -= 1;
551 return (IOMMUTLBEntry) {
552 .target_as = section.address_space,
553 .iova = addr & ~plen,
554 .translated_addr = xlat & ~plen,
555 .addr_mask = plen,
556 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
557 .perm = IOMMU_RW,
560 iotlb_fail:
561 return (IOMMUTLBEntry) {0};
564 /* Called from RCU critical section */
565 MemoryRegion *address_space_translate(AddressSpace *as, hwaddr addr,
566 hwaddr *xlat, hwaddr *plen,
567 bool is_write)
569 MemoryRegion *mr;
570 MemoryRegionSection section;
572 /* This can be MMIO, so setup MMIO bit. */
573 section = address_space_do_translate(as, addr, xlat, plen, is_write, true);
574 mr = section.mr;
576 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
577 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
578 *plen = MIN(page, *plen);
581 return mr;
584 /* Called from RCU critical section */
585 MemoryRegionSection *
586 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
587 hwaddr *xlat, hwaddr *plen)
589 MemoryRegionSection *section;
590 AddressSpaceDispatch *d = atomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
592 section = address_space_translate_internal(d, addr, xlat, plen, false);
594 assert(!memory_region_is_iommu(section->mr));
595 return section;
597 #endif
599 #if !defined(CONFIG_USER_ONLY)
601 static int cpu_common_post_load(void *opaque, int version_id)
603 CPUState *cpu = opaque;
605 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
606 version_id is increased. */
607 cpu->interrupt_request &= ~0x01;
608 tlb_flush(cpu);
610 return 0;
613 static int cpu_common_pre_load(void *opaque)
615 CPUState *cpu = opaque;
617 cpu->exception_index = -1;
619 return 0;
622 static bool cpu_common_exception_index_needed(void *opaque)
624 CPUState *cpu = opaque;
626 return tcg_enabled() && cpu->exception_index != -1;
629 static const VMStateDescription vmstate_cpu_common_exception_index = {
630 .name = "cpu_common/exception_index",
631 .version_id = 1,
632 .minimum_version_id = 1,
633 .needed = cpu_common_exception_index_needed,
634 .fields = (VMStateField[]) {
635 VMSTATE_INT32(exception_index, CPUState),
636 VMSTATE_END_OF_LIST()
640 static bool cpu_common_crash_occurred_needed(void *opaque)
642 CPUState *cpu = opaque;
644 return cpu->crash_occurred;
647 static const VMStateDescription vmstate_cpu_common_crash_occurred = {
648 .name = "cpu_common/crash_occurred",
649 .version_id = 1,
650 .minimum_version_id = 1,
651 .needed = cpu_common_crash_occurred_needed,
652 .fields = (VMStateField[]) {
653 VMSTATE_BOOL(crash_occurred, CPUState),
654 VMSTATE_END_OF_LIST()
658 const VMStateDescription vmstate_cpu_common = {
659 .name = "cpu_common",
660 .version_id = 1,
661 .minimum_version_id = 1,
662 .pre_load = cpu_common_pre_load,
663 .post_load = cpu_common_post_load,
664 .fields = (VMStateField[]) {
665 VMSTATE_UINT32(halted, CPUState),
666 VMSTATE_UINT32(interrupt_request, CPUState),
667 VMSTATE_END_OF_LIST()
669 .subsections = (const VMStateDescription*[]) {
670 &vmstate_cpu_common_exception_index,
671 &vmstate_cpu_common_crash_occurred,
672 NULL
676 #endif
678 CPUState *qemu_get_cpu(int index)
680 CPUState *cpu;
682 CPU_FOREACH(cpu) {
683 if (cpu->cpu_index == index) {
684 return cpu;
688 return NULL;
691 #if !defined(CONFIG_USER_ONLY)
692 void cpu_address_space_init(CPUState *cpu, AddressSpace *as, int asidx)
694 CPUAddressSpace *newas;
696 /* Target code should have set num_ases before calling us */
697 assert(asidx < cpu->num_ases);
699 if (asidx == 0) {
700 /* address space 0 gets the convenience alias */
701 cpu->as = as;
704 /* KVM cannot currently support multiple address spaces. */
705 assert(asidx == 0 || !kvm_enabled());
707 if (!cpu->cpu_ases) {
708 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
711 newas = &cpu->cpu_ases[asidx];
712 newas->cpu = cpu;
713 newas->as = as;
714 if (tcg_enabled()) {
715 newas->tcg_as_listener.commit = tcg_commit;
716 memory_listener_register(&newas->tcg_as_listener, as);
720 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
722 /* Return the AddressSpace corresponding to the specified index */
723 return cpu->cpu_ases[asidx].as;
725 #endif
727 void cpu_exec_unrealizefn(CPUState *cpu)
729 CPUClass *cc = CPU_GET_CLASS(cpu);
731 cpu_list_remove(cpu);
733 if (cc->vmsd != NULL) {
734 vmstate_unregister(NULL, cc->vmsd, cpu);
736 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
737 vmstate_unregister(NULL, &vmstate_cpu_common, cpu);
741 Property cpu_common_props[] = {
742 #ifndef CONFIG_USER_ONLY
743 /* Create a memory property for softmmu CPU object,
744 * so users can wire up its memory. (This can't go in qom/cpu.c
745 * because that file is compiled only once for both user-mode
746 * and system builds.) The default if no link is set up is to use
747 * the system address space.
749 DEFINE_PROP_LINK("memory", CPUState, memory, TYPE_MEMORY_REGION,
750 MemoryRegion *),
751 #endif
752 DEFINE_PROP_END_OF_LIST(),
755 void cpu_exec_initfn(CPUState *cpu)
757 #ifdef TARGET_WORDS_BIGENDIAN
758 cpu->bigendian = true;
759 #else
760 cpu->bigendian = false;
761 #endif
762 cpu->as = NULL;
763 cpu->num_ases = 0;
765 #ifndef CONFIG_USER_ONLY
766 cpu->thread_id = qemu_get_thread_id();
767 cpu->memory = system_memory;
768 object_ref(OBJECT(cpu->memory));
769 #endif
772 void cpu_exec_realizefn(CPUState *cpu, Error **errp)
774 CPUClass *cc ATTRIBUTE_UNUSED = CPU_GET_CLASS(cpu);
776 cpu_list_add(cpu);
778 #ifndef CONFIG_USER_ONLY
779 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
780 vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
782 if (cc->vmsd != NULL) {
783 vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);
785 #endif
788 #if defined(CONFIG_USER_ONLY)
789 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
791 mmap_lock();
792 tb_lock();
793 tb_invalidate_phys_page_range(pc, pc + 1, 0);
794 tb_unlock();
795 mmap_unlock();
797 #else
798 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
800 MemTxAttrs attrs;
801 hwaddr phys = cpu_get_phys_page_attrs_debug(cpu, pc, &attrs);
802 int asidx = cpu_asidx_from_attrs(cpu, attrs);
803 if (phys != -1) {
804 /* Locks grabbed by tb_invalidate_phys_addr */
805 tb_invalidate_phys_addr(cpu->cpu_ases[asidx].as,
806 phys | (pc & ~TARGET_PAGE_MASK));
809 #endif
811 #if defined(CONFIG_USER_ONLY)
812 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
817 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
818 int flags)
820 return -ENOSYS;
823 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
827 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
828 int flags, CPUWatchpoint **watchpoint)
830 return -ENOSYS;
832 #else
833 /* Add a watchpoint. */
834 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
835 int flags, CPUWatchpoint **watchpoint)
837 CPUWatchpoint *wp;
839 /* forbid ranges which are empty or run off the end of the address space */
840 if (len == 0 || (addr + len - 1) < addr) {
841 error_report("tried to set invalid watchpoint at %"
842 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
843 return -EINVAL;
845 wp = g_malloc(sizeof(*wp));
847 wp->vaddr = addr;
848 wp->len = len;
849 wp->flags = flags;
851 /* keep all GDB-injected watchpoints in front */
852 if (flags & BP_GDB) {
853 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
854 } else {
855 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
858 tlb_flush_page(cpu, addr);
860 if (watchpoint)
861 *watchpoint = wp;
862 return 0;
865 /* Remove a specific watchpoint. */
866 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
867 int flags)
869 CPUWatchpoint *wp;
871 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
872 if (addr == wp->vaddr && len == wp->len
873 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
874 cpu_watchpoint_remove_by_ref(cpu, wp);
875 return 0;
878 return -ENOENT;
881 /* Remove a specific watchpoint by reference. */
882 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
884 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
886 tlb_flush_page(cpu, watchpoint->vaddr);
888 g_free(watchpoint);
891 /* Remove all matching watchpoints. */
892 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
894 CPUWatchpoint *wp, *next;
896 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
897 if (wp->flags & mask) {
898 cpu_watchpoint_remove_by_ref(cpu, wp);
903 /* Return true if this watchpoint address matches the specified
904 * access (ie the address range covered by the watchpoint overlaps
905 * partially or completely with the address range covered by the
906 * access).
908 static inline bool cpu_watchpoint_address_matches(CPUWatchpoint *wp,
909 vaddr addr,
910 vaddr len)
912 /* We know the lengths are non-zero, but a little caution is
913 * required to avoid errors in the case where the range ends
914 * exactly at the top of the address space and so addr + len
915 * wraps round to zero.
917 vaddr wpend = wp->vaddr + wp->len - 1;
918 vaddr addrend = addr + len - 1;
920 return !(addr > wpend || wp->vaddr > addrend);
923 #endif
925 /* Add a breakpoint. */
926 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
927 CPUBreakpoint **breakpoint)
929 CPUBreakpoint *bp;
931 bp = g_malloc(sizeof(*bp));
933 bp->pc = pc;
934 bp->flags = flags;
936 /* keep all GDB-injected breakpoints in front */
937 if (flags & BP_GDB) {
938 QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
939 } else {
940 QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
943 breakpoint_invalidate(cpu, pc);
945 if (breakpoint) {
946 *breakpoint = bp;
948 return 0;
951 /* Remove a specific breakpoint. */
952 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
954 CPUBreakpoint *bp;
956 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
957 if (bp->pc == pc && bp->flags == flags) {
958 cpu_breakpoint_remove_by_ref(cpu, bp);
959 return 0;
962 return -ENOENT;
965 /* Remove a specific breakpoint by reference. */
966 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
968 QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);
970 breakpoint_invalidate(cpu, breakpoint->pc);
972 g_free(breakpoint);
975 /* Remove all matching breakpoints. */
976 void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
978 CPUBreakpoint *bp, *next;
980 QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
981 if (bp->flags & mask) {
982 cpu_breakpoint_remove_by_ref(cpu, bp);
987 /* enable or disable single step mode. EXCP_DEBUG is returned by the
988 CPU loop after each instruction */
989 void cpu_single_step(CPUState *cpu, int enabled)
991 if (cpu->singlestep_enabled != enabled) {
992 cpu->singlestep_enabled = enabled;
993 if (kvm_enabled()) {
994 kvm_update_guest_debug(cpu, 0);
995 } else {
996 /* must flush all the translated code to avoid inconsistencies */
997 /* XXX: only flush what is necessary */
998 tb_flush(cpu);
1003 void QEMU_NORETURN cpu_abort(CPUState *cpu, const char *fmt, ...)
1005 va_list ap;
1006 va_list ap2;
1008 va_start(ap, fmt);
1009 va_copy(ap2, ap);
1010 fprintf(stderr, "qemu: fatal: ");
1011 vfprintf(stderr, fmt, ap);
1012 fprintf(stderr, "\n");
1013 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1014 if (qemu_log_separate()) {
1015 qemu_log_lock();
1016 qemu_log("qemu: fatal: ");
1017 qemu_log_vprintf(fmt, ap2);
1018 qemu_log("\n");
1019 log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1020 qemu_log_flush();
1021 qemu_log_unlock();
1022 qemu_log_close();
1024 va_end(ap2);
1025 va_end(ap);
1026 replay_finish();
1027 #if defined(CONFIG_USER_ONLY)
1029 struct sigaction act;
1030 sigfillset(&act.sa_mask);
1031 act.sa_handler = SIG_DFL;
1032 sigaction(SIGABRT, &act, NULL);
1034 #endif
1035 abort();
1038 #if !defined(CONFIG_USER_ONLY)
1039 /* Called from RCU critical section */
1040 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
1042 RAMBlock *block;
1044 block = atomic_rcu_read(&ram_list.mru_block);
1045 if (block && addr - block->offset < block->max_length) {
1046 return block;
1048 RAMBLOCK_FOREACH(block) {
1049 if (addr - block->offset < block->max_length) {
1050 goto found;
1054 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1055 abort();
1057 found:
1058 /* It is safe to write mru_block outside the iothread lock. This
1059 * is what happens:
1061 * mru_block = xxx
1062 * rcu_read_unlock()
1063 * xxx removed from list
1064 * rcu_read_lock()
1065 * read mru_block
1066 * mru_block = NULL;
1067 * call_rcu(reclaim_ramblock, xxx);
1068 * rcu_read_unlock()
1070 * atomic_rcu_set is not needed here. The block was already published
1071 * when it was placed into the list. Here we're just making an extra
1072 * copy of the pointer.
1074 ram_list.mru_block = block;
1075 return block;
1078 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1080 CPUState *cpu;
1081 ram_addr_t start1;
1082 RAMBlock *block;
1083 ram_addr_t end;
1085 end = TARGET_PAGE_ALIGN(start + length);
1086 start &= TARGET_PAGE_MASK;
1088 rcu_read_lock();
1089 block = qemu_get_ram_block(start);
1090 assert(block == qemu_get_ram_block(end - 1));
1091 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1092 CPU_FOREACH(cpu) {
1093 tlb_reset_dirty(cpu, start1, length);
1095 rcu_read_unlock();
1098 /* Note: start and end must be within the same ram block. */
1099 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1100 ram_addr_t length,
1101 unsigned client)
1103 DirtyMemoryBlocks *blocks;
1104 unsigned long end, page;
1105 bool dirty = false;
1107 if (length == 0) {
1108 return false;
1111 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1112 page = start >> TARGET_PAGE_BITS;
1114 rcu_read_lock();
1116 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1118 while (page < end) {
1119 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1120 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1121 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1123 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1124 offset, num);
1125 page += num;
1128 rcu_read_unlock();
1130 if (dirty && tcg_enabled()) {
1131 tlb_reset_dirty_range_all(start, length);
1134 return dirty;
1137 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1138 (ram_addr_t start, ram_addr_t length, unsigned client)
1140 DirtyMemoryBlocks *blocks;
1141 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1142 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1143 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1144 DirtyBitmapSnapshot *snap;
1145 unsigned long page, end, dest;
1147 snap = g_malloc0(sizeof(*snap) +
1148 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1149 snap->start = first;
1150 snap->end = last;
1152 page = first >> TARGET_PAGE_BITS;
1153 end = last >> TARGET_PAGE_BITS;
1154 dest = 0;
1156 rcu_read_lock();
1158 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1160 while (page < end) {
1161 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1162 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1163 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1165 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1166 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1167 offset >>= BITS_PER_LEVEL;
1169 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1170 blocks->blocks[idx] + offset,
1171 num);
1172 page += num;
1173 dest += num >> BITS_PER_LEVEL;
1176 rcu_read_unlock();
1178 if (tcg_enabled()) {
1179 tlb_reset_dirty_range_all(start, length);
1182 return snap;
1185 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1186 ram_addr_t start,
1187 ram_addr_t length)
1189 unsigned long page, end;
1191 assert(start >= snap->start);
1192 assert(start + length <= snap->end);
1194 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1195 page = (start - snap->start) >> TARGET_PAGE_BITS;
1197 while (page < end) {
1198 if (test_bit(page, snap->dirty)) {
1199 return true;
1201 page++;
1203 return false;
1206 /* Called from RCU critical section */
1207 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1208 MemoryRegionSection *section,
1209 target_ulong vaddr,
1210 hwaddr paddr, hwaddr xlat,
1211 int prot,
1212 target_ulong *address)
1214 hwaddr iotlb;
1215 CPUWatchpoint *wp;
1217 if (memory_region_is_ram(section->mr)) {
1218 /* Normal RAM. */
1219 iotlb = memory_region_get_ram_addr(section->mr) + xlat;
1220 if (!section->readonly) {
1221 iotlb |= PHYS_SECTION_NOTDIRTY;
1222 } else {
1223 iotlb |= PHYS_SECTION_ROM;
1225 } else {
1226 AddressSpaceDispatch *d;
1228 d = atomic_rcu_read(&section->address_space->dispatch);
1229 iotlb = section - d->map.sections;
1230 iotlb += xlat;
1233 /* Make accesses to pages with watchpoints go via the
1234 watchpoint trap routines. */
1235 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1236 if (cpu_watchpoint_address_matches(wp, vaddr, TARGET_PAGE_SIZE)) {
1237 /* Avoid trapping reads of pages with a write breakpoint. */
1238 if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
1239 iotlb = PHYS_SECTION_WATCH + paddr;
1240 *address |= TLB_MMIO;
1241 break;
1246 return iotlb;
1248 #endif /* defined(CONFIG_USER_ONLY) */
1250 #if !defined(CONFIG_USER_ONLY)
1252 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
1253 uint16_t section);
1254 static subpage_t *subpage_init(AddressSpace *as, hwaddr base);
1256 static void *(*phys_mem_alloc)(size_t size, uint64_t *align) =
1257 qemu_anon_ram_alloc;
1260 * Set a custom physical guest memory alloator.
1261 * Accelerators with unusual needs may need this. Hopefully, we can
1262 * get rid of it eventually.
1264 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align))
1266 phys_mem_alloc = alloc;
1269 static uint16_t phys_section_add(PhysPageMap *map,
1270 MemoryRegionSection *section)
1272 /* The physical section number is ORed with a page-aligned
1273 * pointer to produce the iotlb entries. Thus it should
1274 * never overflow into the page-aligned value.
1276 assert(map->sections_nb < TARGET_PAGE_SIZE);
1278 if (map->sections_nb == map->sections_nb_alloc) {
1279 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1280 map->sections = g_renew(MemoryRegionSection, map->sections,
1281 map->sections_nb_alloc);
1283 map->sections[map->sections_nb] = *section;
1284 memory_region_ref(section->mr);
1285 return map->sections_nb++;
1288 static void phys_section_destroy(MemoryRegion *mr)
1290 bool have_sub_page = mr->subpage;
1292 memory_region_unref(mr);
1294 if (have_sub_page) {
1295 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1296 object_unref(OBJECT(&subpage->iomem));
1297 g_free(subpage);
1301 static void phys_sections_free(PhysPageMap *map)
1303 while (map->sections_nb > 0) {
1304 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1305 phys_section_destroy(section->mr);
1307 g_free(map->sections);
1308 g_free(map->nodes);
1311 static void register_subpage(AddressSpaceDispatch *d, MemoryRegionSection *section)
1313 subpage_t *subpage;
1314 hwaddr base = section->offset_within_address_space
1315 & TARGET_PAGE_MASK;
1316 MemoryRegionSection *existing = phys_page_find(d, base);
1317 MemoryRegionSection subsection = {
1318 .offset_within_address_space = base,
1319 .size = int128_make64(TARGET_PAGE_SIZE),
1321 hwaddr start, end;
1323 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1325 if (!(existing->mr->subpage)) {
1326 subpage = subpage_init(d->as, base);
1327 subsection.address_space = d->as;
1328 subsection.mr = &subpage->iomem;
1329 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1330 phys_section_add(&d->map, &subsection));
1331 } else {
1332 subpage = container_of(existing->mr, subpage_t, iomem);
1334 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1335 end = start + int128_get64(section->size) - 1;
1336 subpage_register(subpage, start, end,
1337 phys_section_add(&d->map, section));
1341 static void register_multipage(AddressSpaceDispatch *d,
1342 MemoryRegionSection *section)
1344 hwaddr start_addr = section->offset_within_address_space;
1345 uint16_t section_index = phys_section_add(&d->map, section);
1346 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1347 TARGET_PAGE_BITS));
1349 assert(num_pages);
1350 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1353 static void mem_add(MemoryListener *listener, MemoryRegionSection *section)
1355 AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
1356 AddressSpaceDispatch *d = as->next_dispatch;
1357 MemoryRegionSection now = *section, remain = *section;
1358 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1360 if (now.offset_within_address_space & ~TARGET_PAGE_MASK) {
1361 uint64_t left = TARGET_PAGE_ALIGN(now.offset_within_address_space)
1362 - now.offset_within_address_space;
1364 now.size = int128_min(int128_make64(left), now.size);
1365 register_subpage(d, &now);
1366 } else {
1367 now.size = int128_zero();
1369 while (int128_ne(remain.size, now.size)) {
1370 remain.size = int128_sub(remain.size, now.size);
1371 remain.offset_within_address_space += int128_get64(now.size);
1372 remain.offset_within_region += int128_get64(now.size);
1373 now = remain;
1374 if (int128_lt(remain.size, page_size)) {
1375 register_subpage(d, &now);
1376 } else if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1377 now.size = page_size;
1378 register_subpage(d, &now);
1379 } else {
1380 now.size = int128_and(now.size, int128_neg(page_size));
1381 register_multipage(d, &now);
1386 void qemu_flush_coalesced_mmio_buffer(void)
1388 if (kvm_enabled())
1389 kvm_flush_coalesced_mmio_buffer();
1392 void qemu_mutex_lock_ramlist(void)
1394 qemu_mutex_lock(&ram_list.mutex);
1397 void qemu_mutex_unlock_ramlist(void)
1399 qemu_mutex_unlock(&ram_list.mutex);
1402 void ram_block_dump(Monitor *mon)
1404 RAMBlock *block;
1405 char *psize;
1407 rcu_read_lock();
1408 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1409 "Block Name", "PSize", "Offset", "Used", "Total");
1410 RAMBLOCK_FOREACH(block) {
1411 psize = size_to_str(block->page_size);
1412 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1413 " 0x%016" PRIx64 "\n", block->idstr, psize,
1414 (uint64_t)block->offset,
1415 (uint64_t)block->used_length,
1416 (uint64_t)block->max_length);
1417 g_free(psize);
1419 rcu_read_unlock();
1422 #ifdef __linux__
1424 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1425 * may or may not name the same files / on the same filesystem now as
1426 * when we actually open and map them. Iterate over the file
1427 * descriptors instead, and use qemu_fd_getpagesize().
1429 static int find_max_supported_pagesize(Object *obj, void *opaque)
1431 char *mem_path;
1432 long *hpsize_min = opaque;
1434 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1435 mem_path = object_property_get_str(obj, "mem-path", NULL);
1436 if (mem_path) {
1437 long hpsize = qemu_mempath_getpagesize(mem_path);
1438 if (hpsize < *hpsize_min) {
1439 *hpsize_min = hpsize;
1441 } else {
1442 *hpsize_min = getpagesize();
1446 return 0;
1449 long qemu_getrampagesize(void)
1451 long hpsize = LONG_MAX;
1452 long mainrampagesize;
1453 Object *memdev_root;
1455 if (mem_path) {
1456 mainrampagesize = qemu_mempath_getpagesize(mem_path);
1457 } else {
1458 mainrampagesize = getpagesize();
1461 /* it's possible we have memory-backend objects with
1462 * hugepage-backed RAM. these may get mapped into system
1463 * address space via -numa parameters or memory hotplug
1464 * hooks. we want to take these into account, but we
1465 * also want to make sure these supported hugepage
1466 * sizes are applicable across the entire range of memory
1467 * we may boot from, so we take the min across all
1468 * backends, and assume normal pages in cases where a
1469 * backend isn't backed by hugepages.
1471 memdev_root = object_resolve_path("/objects", NULL);
1472 if (memdev_root) {
1473 object_child_foreach(memdev_root, find_max_supported_pagesize, &hpsize);
1475 if (hpsize == LONG_MAX) {
1476 /* No additional memory regions found ==> Report main RAM page size */
1477 return mainrampagesize;
1480 /* If NUMA is disabled or the NUMA nodes are not backed with a
1481 * memory-backend, then there is at least one node using "normal" RAM,
1482 * so if its page size is smaller we have got to report that size instead.
1484 if (hpsize > mainrampagesize &&
1485 (nb_numa_nodes == 0 || numa_info[0].node_memdev == NULL)) {
1486 static bool warned;
1487 if (!warned) {
1488 error_report("Huge page support disabled (n/a for main memory).");
1489 warned = true;
1491 return mainrampagesize;
1494 return hpsize;
1496 #else
1497 long qemu_getrampagesize(void)
1499 return getpagesize();
1501 #endif
1503 #ifdef __linux__
1504 static int64_t get_file_size(int fd)
1506 int64_t size = lseek(fd, 0, SEEK_END);
1507 if (size < 0) {
1508 return -errno;
1510 return size;
1513 static int file_ram_open(const char *path,
1514 const char *region_name,
1515 bool *created,
1516 Error **errp)
1518 char *filename;
1519 char *sanitized_name;
1520 char *c;
1521 int fd = -1;
1523 *created = false;
1524 for (;;) {
1525 fd = open(path, O_RDWR);
1526 if (fd >= 0) {
1527 /* @path names an existing file, use it */
1528 break;
1530 if (errno == ENOENT) {
1531 /* @path names a file that doesn't exist, create it */
1532 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1533 if (fd >= 0) {
1534 *created = true;
1535 break;
1537 } else if (errno == EISDIR) {
1538 /* @path names a directory, create a file there */
1539 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1540 sanitized_name = g_strdup(region_name);
1541 for (c = sanitized_name; *c != '\0'; c++) {
1542 if (*c == '/') {
1543 *c = '_';
1547 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1548 sanitized_name);
1549 g_free(sanitized_name);
1551 fd = mkstemp(filename);
1552 if (fd >= 0) {
1553 unlink(filename);
1554 g_free(filename);
1555 break;
1557 g_free(filename);
1559 if (errno != EEXIST && errno != EINTR) {
1560 error_setg_errno(errp, errno,
1561 "can't open backing store %s for guest RAM",
1562 path);
1563 return -1;
1566 * Try again on EINTR and EEXIST. The latter happens when
1567 * something else creates the file between our two open().
1571 return fd;
1574 static void *file_ram_alloc(RAMBlock *block,
1575 ram_addr_t memory,
1576 int fd,
1577 bool truncate,
1578 Error **errp)
1580 void *area;
1582 block->page_size = qemu_fd_getpagesize(fd);
1583 block->mr->align = block->page_size;
1584 #if defined(__s390x__)
1585 if (kvm_enabled()) {
1586 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1588 #endif
1590 if (memory < block->page_size) {
1591 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1592 "or larger than page size 0x%zx",
1593 memory, block->page_size);
1594 return NULL;
1597 memory = ROUND_UP(memory, block->page_size);
1600 * ftruncate is not supported by hugetlbfs in older
1601 * hosts, so don't bother bailing out on errors.
1602 * If anything goes wrong with it under other filesystems,
1603 * mmap will fail.
1605 * Do not truncate the non-empty backend file to avoid corrupting
1606 * the existing data in the file. Disabling shrinking is not
1607 * enough. For example, the current vNVDIMM implementation stores
1608 * the guest NVDIMM labels at the end of the backend file. If the
1609 * backend file is later extended, QEMU will not be able to find
1610 * those labels. Therefore, extending the non-empty backend file
1611 * is disabled as well.
1613 if (truncate && ftruncate(fd, memory)) {
1614 perror("ftruncate");
1617 area = qemu_ram_mmap(fd, memory, block->mr->align,
1618 block->flags & RAM_SHARED);
1619 if (area == MAP_FAILED) {
1620 error_setg_errno(errp, errno,
1621 "unable to map backing store for guest RAM");
1622 return NULL;
1625 if (mem_prealloc) {
1626 os_mem_prealloc(fd, area, memory, smp_cpus, errp);
1627 if (errp && *errp) {
1628 qemu_ram_munmap(area, memory);
1629 return NULL;
1633 block->fd = fd;
1634 return area;
1636 #endif
1638 /* Called with the ramlist lock held. */
1639 static ram_addr_t find_ram_offset(ram_addr_t size)
1641 RAMBlock *block, *next_block;
1642 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1644 assert(size != 0); /* it would hand out same offset multiple times */
1646 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1647 return 0;
1650 RAMBLOCK_FOREACH(block) {
1651 ram_addr_t end, next = RAM_ADDR_MAX;
1653 end = block->offset + block->max_length;
1655 RAMBLOCK_FOREACH(next_block) {
1656 if (next_block->offset >= end) {
1657 next = MIN(next, next_block->offset);
1660 if (next - end >= size && next - end < mingap) {
1661 offset = end;
1662 mingap = next - end;
1666 if (offset == RAM_ADDR_MAX) {
1667 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1668 (uint64_t)size);
1669 abort();
1672 return offset;
1675 unsigned long last_ram_page(void)
1677 RAMBlock *block;
1678 ram_addr_t last = 0;
1680 rcu_read_lock();
1681 RAMBLOCK_FOREACH(block) {
1682 last = MAX(last, block->offset + block->max_length);
1684 rcu_read_unlock();
1685 return last >> TARGET_PAGE_BITS;
1688 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1690 int ret;
1692 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1693 if (!machine_dump_guest_core(current_machine)) {
1694 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1695 if (ret) {
1696 perror("qemu_madvise");
1697 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1698 "but dump_guest_core=off specified\n");
1703 const char *qemu_ram_get_idstr(RAMBlock *rb)
1705 return rb->idstr;
1708 bool qemu_ram_is_shared(RAMBlock *rb)
1710 return rb->flags & RAM_SHARED;
1713 /* Called with iothread lock held. */
1714 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1716 RAMBlock *block;
1718 assert(new_block);
1719 assert(!new_block->idstr[0]);
1721 if (dev) {
1722 char *id = qdev_get_dev_path(dev);
1723 if (id) {
1724 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1725 g_free(id);
1728 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1730 rcu_read_lock();
1731 RAMBLOCK_FOREACH(block) {
1732 if (block != new_block &&
1733 !strcmp(block->idstr, new_block->idstr)) {
1734 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1735 new_block->idstr);
1736 abort();
1739 rcu_read_unlock();
1742 /* Called with iothread lock held. */
1743 void qemu_ram_unset_idstr(RAMBlock *block)
1745 /* FIXME: arch_init.c assumes that this is not called throughout
1746 * migration. Ignore the problem since hot-unplug during migration
1747 * does not work anyway.
1749 if (block) {
1750 memset(block->idstr, 0, sizeof(block->idstr));
1754 size_t qemu_ram_pagesize(RAMBlock *rb)
1756 return rb->page_size;
1759 /* Returns the largest size of page in use */
1760 size_t qemu_ram_pagesize_largest(void)
1762 RAMBlock *block;
1763 size_t largest = 0;
1765 RAMBLOCK_FOREACH(block) {
1766 largest = MAX(largest, qemu_ram_pagesize(block));
1769 return largest;
1772 static int memory_try_enable_merging(void *addr, size_t len)
1774 if (!machine_mem_merge(current_machine)) {
1775 /* disabled by the user */
1776 return 0;
1779 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1782 /* Only legal before guest might have detected the memory size: e.g. on
1783 * incoming migration, or right after reset.
1785 * As memory core doesn't know how is memory accessed, it is up to
1786 * resize callback to update device state and/or add assertions to detect
1787 * misuse, if necessary.
1789 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1791 assert(block);
1793 newsize = HOST_PAGE_ALIGN(newsize);
1795 if (block->used_length == newsize) {
1796 return 0;
1799 if (!(block->flags & RAM_RESIZEABLE)) {
1800 error_setg_errno(errp, EINVAL,
1801 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1802 " in != 0x" RAM_ADDR_FMT, block->idstr,
1803 newsize, block->used_length);
1804 return -EINVAL;
1807 if (block->max_length < newsize) {
1808 error_setg_errno(errp, EINVAL,
1809 "Length too large: %s: 0x" RAM_ADDR_FMT
1810 " > 0x" RAM_ADDR_FMT, block->idstr,
1811 newsize, block->max_length);
1812 return -EINVAL;
1815 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1816 block->used_length = newsize;
1817 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1818 DIRTY_CLIENTS_ALL);
1819 memory_region_set_size(block->mr, newsize);
1820 if (block->resized) {
1821 block->resized(block->idstr, newsize, block->host);
1823 return 0;
1826 /* Called with ram_list.mutex held */
1827 static void dirty_memory_extend(ram_addr_t old_ram_size,
1828 ram_addr_t new_ram_size)
1830 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1831 DIRTY_MEMORY_BLOCK_SIZE);
1832 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1833 DIRTY_MEMORY_BLOCK_SIZE);
1834 int i;
1836 /* Only need to extend if block count increased */
1837 if (new_num_blocks <= old_num_blocks) {
1838 return;
1841 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1842 DirtyMemoryBlocks *old_blocks;
1843 DirtyMemoryBlocks *new_blocks;
1844 int j;
1846 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
1847 new_blocks = g_malloc(sizeof(*new_blocks) +
1848 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1850 if (old_num_blocks) {
1851 memcpy(new_blocks->blocks, old_blocks->blocks,
1852 old_num_blocks * sizeof(old_blocks->blocks[0]));
1855 for (j = old_num_blocks; j < new_num_blocks; j++) {
1856 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1859 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1861 if (old_blocks) {
1862 g_free_rcu(old_blocks, rcu);
1867 static void ram_block_add(RAMBlock *new_block, Error **errp)
1869 RAMBlock *block;
1870 RAMBlock *last_block = NULL;
1871 ram_addr_t old_ram_size, new_ram_size;
1872 Error *err = NULL;
1874 old_ram_size = last_ram_page();
1876 qemu_mutex_lock_ramlist();
1877 new_block->offset = find_ram_offset(new_block->max_length);
1879 if (!new_block->host) {
1880 if (xen_enabled()) {
1881 xen_ram_alloc(new_block->offset, new_block->max_length,
1882 new_block->mr, &err);
1883 if (err) {
1884 error_propagate(errp, err);
1885 qemu_mutex_unlock_ramlist();
1886 return;
1888 } else {
1889 new_block->host = phys_mem_alloc(new_block->max_length,
1890 &new_block->mr->align);
1891 if (!new_block->host) {
1892 error_setg_errno(errp, errno,
1893 "cannot set up guest memory '%s'",
1894 memory_region_name(new_block->mr));
1895 qemu_mutex_unlock_ramlist();
1896 return;
1898 memory_try_enable_merging(new_block->host, new_block->max_length);
1902 new_ram_size = MAX(old_ram_size,
1903 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1904 if (new_ram_size > old_ram_size) {
1905 dirty_memory_extend(old_ram_size, new_ram_size);
1907 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1908 * QLIST (which has an RCU-friendly variant) does not have insertion at
1909 * tail, so save the last element in last_block.
1911 RAMBLOCK_FOREACH(block) {
1912 last_block = block;
1913 if (block->max_length < new_block->max_length) {
1914 break;
1917 if (block) {
1918 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1919 } else if (last_block) {
1920 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
1921 } else { /* list is empty */
1922 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1924 ram_list.mru_block = NULL;
1926 /* Write list before version */
1927 smp_wmb();
1928 ram_list.version++;
1929 qemu_mutex_unlock_ramlist();
1931 cpu_physical_memory_set_dirty_range(new_block->offset,
1932 new_block->used_length,
1933 DIRTY_CLIENTS_ALL);
1935 if (new_block->host) {
1936 qemu_ram_setup_dump(new_block->host, new_block->max_length);
1937 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
1938 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
1939 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
1940 ram_block_notify_add(new_block->host, new_block->max_length);
1944 #ifdef __linux__
1945 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
1946 bool share, int fd,
1947 Error **errp)
1949 RAMBlock *new_block;
1950 Error *local_err = NULL;
1951 int64_t file_size;
1953 if (xen_enabled()) {
1954 error_setg(errp, "-mem-path not supported with Xen");
1955 return NULL;
1958 if (kvm_enabled() && !kvm_has_sync_mmu()) {
1959 error_setg(errp,
1960 "host lacks kvm mmu notifiers, -mem-path unsupported");
1961 return NULL;
1964 if (phys_mem_alloc != qemu_anon_ram_alloc) {
1966 * file_ram_alloc() needs to allocate just like
1967 * phys_mem_alloc, but we haven't bothered to provide
1968 * a hook there.
1970 error_setg(errp,
1971 "-mem-path not supported with this accelerator");
1972 return NULL;
1975 size = HOST_PAGE_ALIGN(size);
1976 file_size = get_file_size(fd);
1977 if (file_size > 0 && file_size < size) {
1978 error_setg(errp, "backing store %s size 0x%" PRIx64
1979 " does not match 'size' option 0x" RAM_ADDR_FMT,
1980 mem_path, file_size, size);
1981 return NULL;
1984 new_block = g_malloc0(sizeof(*new_block));
1985 new_block->mr = mr;
1986 new_block->used_length = size;
1987 new_block->max_length = size;
1988 new_block->flags = share ? RAM_SHARED : 0;
1989 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
1990 if (!new_block->host) {
1991 g_free(new_block);
1992 return NULL;
1995 ram_block_add(new_block, &local_err);
1996 if (local_err) {
1997 g_free(new_block);
1998 error_propagate(errp, local_err);
1999 return NULL;
2001 return new_block;
2006 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2007 bool share, const char *mem_path,
2008 Error **errp)
2010 int fd;
2011 bool created;
2012 RAMBlock *block;
2014 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2015 if (fd < 0) {
2016 return NULL;
2019 block = qemu_ram_alloc_from_fd(size, mr, share, fd, errp);
2020 if (!block) {
2021 if (created) {
2022 unlink(mem_path);
2024 close(fd);
2025 return NULL;
2028 return block;
2030 #endif
2032 static
2033 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2034 void (*resized)(const char*,
2035 uint64_t length,
2036 void *host),
2037 void *host, bool resizeable,
2038 MemoryRegion *mr, Error **errp)
2040 RAMBlock *new_block;
2041 Error *local_err = NULL;
2043 size = HOST_PAGE_ALIGN(size);
2044 max_size = HOST_PAGE_ALIGN(max_size);
2045 new_block = g_malloc0(sizeof(*new_block));
2046 new_block->mr = mr;
2047 new_block->resized = resized;
2048 new_block->used_length = size;
2049 new_block->max_length = max_size;
2050 assert(max_size >= size);
2051 new_block->fd = -1;
2052 new_block->page_size = getpagesize();
2053 new_block->host = host;
2054 if (host) {
2055 new_block->flags |= RAM_PREALLOC;
2057 if (resizeable) {
2058 new_block->flags |= RAM_RESIZEABLE;
2060 ram_block_add(new_block, &local_err);
2061 if (local_err) {
2062 g_free(new_block);
2063 error_propagate(errp, local_err);
2064 return NULL;
2066 return new_block;
2069 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2070 MemoryRegion *mr, Error **errp)
2072 return qemu_ram_alloc_internal(size, size, NULL, host, false, mr, errp);
2075 RAMBlock *qemu_ram_alloc(ram_addr_t size, MemoryRegion *mr, Error **errp)
2077 return qemu_ram_alloc_internal(size, size, NULL, NULL, false, mr, errp);
2080 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2081 void (*resized)(const char*,
2082 uint64_t length,
2083 void *host),
2084 MemoryRegion *mr, Error **errp)
2086 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true, mr, errp);
2089 static void reclaim_ramblock(RAMBlock *block)
2091 if (block->flags & RAM_PREALLOC) {
2093 } else if (xen_enabled()) {
2094 xen_invalidate_map_cache_entry(block->host);
2095 #ifndef _WIN32
2096 } else if (block->fd >= 0) {
2097 qemu_ram_munmap(block->host, block->max_length);
2098 close(block->fd);
2099 #endif
2100 } else {
2101 qemu_anon_ram_free(block->host, block->max_length);
2103 g_free(block);
2106 void qemu_ram_free(RAMBlock *block)
2108 if (!block) {
2109 return;
2112 if (block->host) {
2113 ram_block_notify_remove(block->host, block->max_length);
2116 qemu_mutex_lock_ramlist();
2117 QLIST_REMOVE_RCU(block, next);
2118 ram_list.mru_block = NULL;
2119 /* Write list before version */
2120 smp_wmb();
2121 ram_list.version++;
2122 call_rcu(block, reclaim_ramblock, rcu);
2123 qemu_mutex_unlock_ramlist();
2126 #ifndef _WIN32
2127 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2129 RAMBlock *block;
2130 ram_addr_t offset;
2131 int flags;
2132 void *area, *vaddr;
2134 RAMBLOCK_FOREACH(block) {
2135 offset = addr - block->offset;
2136 if (offset < block->max_length) {
2137 vaddr = ramblock_ptr(block, offset);
2138 if (block->flags & RAM_PREALLOC) {
2140 } else if (xen_enabled()) {
2141 abort();
2142 } else {
2143 flags = MAP_FIXED;
2144 if (block->fd >= 0) {
2145 flags |= (block->flags & RAM_SHARED ?
2146 MAP_SHARED : MAP_PRIVATE);
2147 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2148 flags, block->fd, offset);
2149 } else {
2151 * Remap needs to match alloc. Accelerators that
2152 * set phys_mem_alloc never remap. If they did,
2153 * we'd need a remap hook here.
2155 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2157 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2158 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2159 flags, -1, 0);
2161 if (area != vaddr) {
2162 fprintf(stderr, "Could not remap addr: "
2163 RAM_ADDR_FMT "@" RAM_ADDR_FMT "\n",
2164 length, addr);
2165 exit(1);
2167 memory_try_enable_merging(vaddr, length);
2168 qemu_ram_setup_dump(vaddr, length);
2173 #endif /* !_WIN32 */
2175 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2176 * This should not be used for general purpose DMA. Use address_space_map
2177 * or address_space_rw instead. For local memory (e.g. video ram) that the
2178 * device owns, use memory_region_get_ram_ptr.
2180 * Called within RCU critical section.
2182 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2184 RAMBlock *block = ram_block;
2186 if (block == NULL) {
2187 block = qemu_get_ram_block(addr);
2188 addr -= block->offset;
2191 if (xen_enabled() && block->host == NULL) {
2192 /* We need to check if the requested address is in the RAM
2193 * because we don't want to map the entire memory in QEMU.
2194 * In that case just map until the end of the page.
2196 if (block->offset == 0) {
2197 return xen_map_cache(addr, 0, 0, false);
2200 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2202 return ramblock_ptr(block, addr);
2205 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2206 * but takes a size argument.
2208 * Called within RCU critical section.
2210 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2211 hwaddr *size, bool lock)
2213 RAMBlock *block = ram_block;
2214 if (*size == 0) {
2215 return NULL;
2218 if (block == NULL) {
2219 block = qemu_get_ram_block(addr);
2220 addr -= block->offset;
2222 *size = MIN(*size, block->max_length - addr);
2224 if (xen_enabled() && block->host == NULL) {
2225 /* We need to check if the requested address is in the RAM
2226 * because we don't want to map the entire memory in QEMU.
2227 * In that case just map the requested area.
2229 if (block->offset == 0) {
2230 return xen_map_cache(addr, *size, lock, lock);
2233 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2236 return ramblock_ptr(block, addr);
2240 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2241 * in that RAMBlock.
2243 * ptr: Host pointer to look up
2244 * round_offset: If true round the result offset down to a page boundary
2245 * *ram_addr: set to result ram_addr
2246 * *offset: set to result offset within the RAMBlock
2248 * Returns: RAMBlock (or NULL if not found)
2250 * By the time this function returns, the returned pointer is not protected
2251 * by RCU anymore. If the caller is not within an RCU critical section and
2252 * does not hold the iothread lock, it must have other means of protecting the
2253 * pointer, such as a reference to the region that includes the incoming
2254 * ram_addr_t.
2256 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2257 ram_addr_t *offset)
2259 RAMBlock *block;
2260 uint8_t *host = ptr;
2262 if (xen_enabled()) {
2263 ram_addr_t ram_addr;
2264 rcu_read_lock();
2265 ram_addr = xen_ram_addr_from_mapcache(ptr);
2266 block = qemu_get_ram_block(ram_addr);
2267 if (block) {
2268 *offset = ram_addr - block->offset;
2270 rcu_read_unlock();
2271 return block;
2274 rcu_read_lock();
2275 block = atomic_rcu_read(&ram_list.mru_block);
2276 if (block && block->host && host - block->host < block->max_length) {
2277 goto found;
2280 RAMBLOCK_FOREACH(block) {
2281 /* This case append when the block is not mapped. */
2282 if (block->host == NULL) {
2283 continue;
2285 if (host - block->host < block->max_length) {
2286 goto found;
2290 rcu_read_unlock();
2291 return NULL;
2293 found:
2294 *offset = (host - block->host);
2295 if (round_offset) {
2296 *offset &= TARGET_PAGE_MASK;
2298 rcu_read_unlock();
2299 return block;
2303 * Finds the named RAMBlock
2305 * name: The name of RAMBlock to find
2307 * Returns: RAMBlock (or NULL if not found)
2309 RAMBlock *qemu_ram_block_by_name(const char *name)
2311 RAMBlock *block;
2313 RAMBLOCK_FOREACH(block) {
2314 if (!strcmp(name, block->idstr)) {
2315 return block;
2319 return NULL;
2322 /* Some of the softmmu routines need to translate from a host pointer
2323 (typically a TLB entry) back to a ram offset. */
2324 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2326 RAMBlock *block;
2327 ram_addr_t offset;
2329 block = qemu_ram_block_from_host(ptr, false, &offset);
2330 if (!block) {
2331 return RAM_ADDR_INVALID;
2334 return block->offset + offset;
2337 /* Called within RCU critical section. */
2338 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2339 uint64_t val, unsigned size)
2341 bool locked = false;
2343 assert(tcg_enabled());
2344 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
2345 locked = true;
2346 tb_lock();
2347 tb_invalidate_phys_page_fast(ram_addr, size);
2349 switch (size) {
2350 case 1:
2351 stb_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2352 break;
2353 case 2:
2354 stw_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2355 break;
2356 case 4:
2357 stl_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2358 break;
2359 default:
2360 abort();
2363 if (locked) {
2364 tb_unlock();
2367 /* Set both VGA and migration bits for simplicity and to remove
2368 * the notdirty callback faster.
2370 cpu_physical_memory_set_dirty_range(ram_addr, size,
2371 DIRTY_CLIENTS_NOCODE);
2372 /* we remove the notdirty callback only if the code has been
2373 flushed */
2374 if (!cpu_physical_memory_is_clean(ram_addr)) {
2375 tlb_set_dirty(current_cpu, current_cpu->mem_io_vaddr);
2379 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
2380 unsigned size, bool is_write)
2382 return is_write;
2385 static const MemoryRegionOps notdirty_mem_ops = {
2386 .write = notdirty_mem_write,
2387 .valid.accepts = notdirty_mem_accepts,
2388 .endianness = DEVICE_NATIVE_ENDIAN,
2391 /* Generate a debug exception if a watchpoint has been hit. */
2392 static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
2394 CPUState *cpu = current_cpu;
2395 CPUClass *cc = CPU_GET_CLASS(cpu);
2396 CPUArchState *env = cpu->env_ptr;
2397 target_ulong pc, cs_base;
2398 target_ulong vaddr;
2399 CPUWatchpoint *wp;
2400 uint32_t cpu_flags;
2402 assert(tcg_enabled());
2403 if (cpu->watchpoint_hit) {
2404 /* We re-entered the check after replacing the TB. Now raise
2405 * the debug interrupt so that is will trigger after the
2406 * current instruction. */
2407 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2408 return;
2410 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
2411 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
2412 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2413 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2414 && (wp->flags & flags)) {
2415 if (flags == BP_MEM_READ) {
2416 wp->flags |= BP_WATCHPOINT_HIT_READ;
2417 } else {
2418 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2420 wp->hitaddr = vaddr;
2421 wp->hitattrs = attrs;
2422 if (!cpu->watchpoint_hit) {
2423 if (wp->flags & BP_CPU &&
2424 !cc->debug_check_watchpoint(cpu, wp)) {
2425 wp->flags &= ~BP_WATCHPOINT_HIT;
2426 continue;
2428 cpu->watchpoint_hit = wp;
2430 /* Both tb_lock and iothread_mutex will be reset when
2431 * cpu_loop_exit or cpu_loop_exit_noexc longjmp
2432 * back into the cpu_exec main loop.
2434 tb_lock();
2435 tb_check_watchpoint(cpu);
2436 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2437 cpu->exception_index = EXCP_DEBUG;
2438 cpu_loop_exit(cpu);
2439 } else {
2440 cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags);
2441 tb_gen_code(cpu, pc, cs_base, cpu_flags, 1);
2442 cpu_loop_exit_noexc(cpu);
2445 } else {
2446 wp->flags &= ~BP_WATCHPOINT_HIT;
2451 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2452 so these check for a hit then pass through to the normal out-of-line
2453 phys routines. */
2454 static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2455 unsigned size, MemTxAttrs attrs)
2457 MemTxResult res;
2458 uint64_t data;
2459 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2460 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2462 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2463 switch (size) {
2464 case 1:
2465 data = address_space_ldub(as, addr, attrs, &res);
2466 break;
2467 case 2:
2468 data = address_space_lduw(as, addr, attrs, &res);
2469 break;
2470 case 4:
2471 data = address_space_ldl(as, addr, attrs, &res);
2472 break;
2473 default: abort();
2475 *pdata = data;
2476 return res;
2479 static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2480 uint64_t val, unsigned size,
2481 MemTxAttrs attrs)
2483 MemTxResult res;
2484 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2485 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2487 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2488 switch (size) {
2489 case 1:
2490 address_space_stb(as, addr, val, attrs, &res);
2491 break;
2492 case 2:
2493 address_space_stw(as, addr, val, attrs, &res);
2494 break;
2495 case 4:
2496 address_space_stl(as, addr, val, attrs, &res);
2497 break;
2498 default: abort();
2500 return res;
2503 static const MemoryRegionOps watch_mem_ops = {
2504 .read_with_attrs = watch_mem_read,
2505 .write_with_attrs = watch_mem_write,
2506 .endianness = DEVICE_NATIVE_ENDIAN,
2509 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2510 unsigned len, MemTxAttrs attrs)
2512 subpage_t *subpage = opaque;
2513 uint8_t buf[8];
2514 MemTxResult res;
2516 #if defined(DEBUG_SUBPAGE)
2517 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2518 subpage, len, addr);
2519 #endif
2520 res = address_space_read(subpage->as, addr + subpage->base,
2521 attrs, buf, len);
2522 if (res) {
2523 return res;
2525 switch (len) {
2526 case 1:
2527 *data = ldub_p(buf);
2528 return MEMTX_OK;
2529 case 2:
2530 *data = lduw_p(buf);
2531 return MEMTX_OK;
2532 case 4:
2533 *data = ldl_p(buf);
2534 return MEMTX_OK;
2535 case 8:
2536 *data = ldq_p(buf);
2537 return MEMTX_OK;
2538 default:
2539 abort();
2543 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2544 uint64_t value, unsigned len, MemTxAttrs attrs)
2546 subpage_t *subpage = opaque;
2547 uint8_t buf[8];
2549 #if defined(DEBUG_SUBPAGE)
2550 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2551 " value %"PRIx64"\n",
2552 __func__, subpage, len, addr, value);
2553 #endif
2554 switch (len) {
2555 case 1:
2556 stb_p(buf, value);
2557 break;
2558 case 2:
2559 stw_p(buf, value);
2560 break;
2561 case 4:
2562 stl_p(buf, value);
2563 break;
2564 case 8:
2565 stq_p(buf, value);
2566 break;
2567 default:
2568 abort();
2570 return address_space_write(subpage->as, addr + subpage->base,
2571 attrs, buf, len);
2574 static bool subpage_accepts(void *opaque, hwaddr addr,
2575 unsigned len, bool is_write)
2577 subpage_t *subpage = opaque;
2578 #if defined(DEBUG_SUBPAGE)
2579 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2580 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2581 #endif
2583 return address_space_access_valid(subpage->as, addr + subpage->base,
2584 len, is_write);
2587 static const MemoryRegionOps subpage_ops = {
2588 .read_with_attrs = subpage_read,
2589 .write_with_attrs = subpage_write,
2590 .impl.min_access_size = 1,
2591 .impl.max_access_size = 8,
2592 .valid.min_access_size = 1,
2593 .valid.max_access_size = 8,
2594 .valid.accepts = subpage_accepts,
2595 .endianness = DEVICE_NATIVE_ENDIAN,
2598 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
2599 uint16_t section)
2601 int idx, eidx;
2603 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2604 return -1;
2605 idx = SUBPAGE_IDX(start);
2606 eidx = SUBPAGE_IDX(end);
2607 #if defined(DEBUG_SUBPAGE)
2608 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2609 __func__, mmio, start, end, idx, eidx, section);
2610 #endif
2611 for (; idx <= eidx; idx++) {
2612 mmio->sub_section[idx] = section;
2615 return 0;
2618 static subpage_t *subpage_init(AddressSpace *as, hwaddr base)
2620 subpage_t *mmio;
2622 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2623 mmio->as = as;
2624 mmio->base = base;
2625 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2626 NULL, TARGET_PAGE_SIZE);
2627 mmio->iomem.subpage = true;
2628 #if defined(DEBUG_SUBPAGE)
2629 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2630 mmio, base, TARGET_PAGE_SIZE);
2631 #endif
2632 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
2634 return mmio;
2637 static uint16_t dummy_section(PhysPageMap *map, AddressSpace *as,
2638 MemoryRegion *mr)
2640 assert(as);
2641 MemoryRegionSection section = {
2642 .address_space = as,
2643 .mr = mr,
2644 .offset_within_address_space = 0,
2645 .offset_within_region = 0,
2646 .size = int128_2_64(),
2649 return phys_section_add(map, &section);
2652 MemoryRegion *iotlb_to_region(CPUState *cpu, hwaddr index, MemTxAttrs attrs)
2654 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2655 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2656 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
2657 MemoryRegionSection *sections = d->map.sections;
2659 return sections[index & ~TARGET_PAGE_MASK].mr;
2662 static void io_mem_init(void)
2664 memory_region_init_io(&io_mem_rom, NULL, &unassigned_mem_ops, NULL, NULL, UINT64_MAX);
2665 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2666 NULL, UINT64_MAX);
2668 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
2669 * which can be called without the iothread mutex.
2671 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
2672 NULL, UINT64_MAX);
2673 memory_region_clear_global_locking(&io_mem_notdirty);
2675 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
2676 NULL, UINT64_MAX);
2679 static void mem_begin(MemoryListener *listener)
2681 AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
2682 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2683 uint16_t n;
2685 n = dummy_section(&d->map, as, &io_mem_unassigned);
2686 assert(n == PHYS_SECTION_UNASSIGNED);
2687 n = dummy_section(&d->map, as, &io_mem_notdirty);
2688 assert(n == PHYS_SECTION_NOTDIRTY);
2689 n = dummy_section(&d->map, as, &io_mem_rom);
2690 assert(n == PHYS_SECTION_ROM);
2691 n = dummy_section(&d->map, as, &io_mem_watch);
2692 assert(n == PHYS_SECTION_WATCH);
2694 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2695 d->as = as;
2696 as->next_dispatch = d;
2699 static void address_space_dispatch_free(AddressSpaceDispatch *d)
2701 phys_sections_free(&d->map);
2702 g_free(d);
2705 static void mem_commit(MemoryListener *listener)
2707 AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
2708 AddressSpaceDispatch *cur = as->dispatch;
2709 AddressSpaceDispatch *next = as->next_dispatch;
2711 phys_page_compact_all(next, next->map.nodes_nb);
2713 atomic_rcu_set(&as->dispatch, next);
2714 if (cur) {
2715 call_rcu(cur, address_space_dispatch_free, rcu);
2719 static void tcg_commit(MemoryListener *listener)
2721 CPUAddressSpace *cpuas;
2722 AddressSpaceDispatch *d;
2724 /* since each CPU stores ram addresses in its TLB cache, we must
2725 reset the modified entries */
2726 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2727 cpu_reloading_memory_map();
2728 /* The CPU and TLB are protected by the iothread lock.
2729 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2730 * may have split the RCU critical section.
2732 d = atomic_rcu_read(&cpuas->as->dispatch);
2733 atomic_rcu_set(&cpuas->memory_dispatch, d);
2734 tlb_flush(cpuas->cpu);
2737 void address_space_init_dispatch(AddressSpace *as)
2739 as->dispatch = NULL;
2740 as->dispatch_listener = (MemoryListener) {
2741 .begin = mem_begin,
2742 .commit = mem_commit,
2743 .region_add = mem_add,
2744 .region_nop = mem_add,
2745 .priority = 0,
2747 memory_listener_register(&as->dispatch_listener, as);
2750 void address_space_unregister(AddressSpace *as)
2752 memory_listener_unregister(&as->dispatch_listener);
2755 void address_space_destroy_dispatch(AddressSpace *as)
2757 AddressSpaceDispatch *d = as->dispatch;
2759 atomic_rcu_set(&as->dispatch, NULL);
2760 if (d) {
2761 call_rcu(d, address_space_dispatch_free, rcu);
2765 static void memory_map_init(void)
2767 system_memory = g_malloc(sizeof(*system_memory));
2769 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2770 address_space_init(&address_space_memory, system_memory, "memory");
2772 system_io = g_malloc(sizeof(*system_io));
2773 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2774 65536);
2775 address_space_init(&address_space_io, system_io, "I/O");
2778 MemoryRegion *get_system_memory(void)
2780 return system_memory;
2783 MemoryRegion *get_system_io(void)
2785 return system_io;
2788 #endif /* !defined(CONFIG_USER_ONLY) */
2790 /* physical memory access (slow version, mainly for debug) */
2791 #if defined(CONFIG_USER_ONLY)
2792 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
2793 uint8_t *buf, int len, int is_write)
2795 int l, flags;
2796 target_ulong page;
2797 void * p;
2799 while (len > 0) {
2800 page = addr & TARGET_PAGE_MASK;
2801 l = (page + TARGET_PAGE_SIZE) - addr;
2802 if (l > len)
2803 l = len;
2804 flags = page_get_flags(page);
2805 if (!(flags & PAGE_VALID))
2806 return -1;
2807 if (is_write) {
2808 if (!(flags & PAGE_WRITE))
2809 return -1;
2810 /* XXX: this code should not depend on lock_user */
2811 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
2812 return -1;
2813 memcpy(p, buf, l);
2814 unlock_user(p, addr, l);
2815 } else {
2816 if (!(flags & PAGE_READ))
2817 return -1;
2818 /* XXX: this code should not depend on lock_user */
2819 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
2820 return -1;
2821 memcpy(buf, p, l);
2822 unlock_user(p, addr, 0);
2824 len -= l;
2825 buf += l;
2826 addr += l;
2828 return 0;
2831 #else
2833 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2834 hwaddr length)
2836 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2837 addr += memory_region_get_ram_addr(mr);
2839 /* No early return if dirty_log_mask is or becomes 0, because
2840 * cpu_physical_memory_set_dirty_range will still call
2841 * xen_modified_memory.
2843 if (dirty_log_mask) {
2844 dirty_log_mask =
2845 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2847 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2848 assert(tcg_enabled());
2849 tb_lock();
2850 tb_invalidate_phys_range(addr, addr + length);
2851 tb_unlock();
2852 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2854 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2857 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2859 unsigned access_size_max = mr->ops->valid.max_access_size;
2861 /* Regions are assumed to support 1-4 byte accesses unless
2862 otherwise specified. */
2863 if (access_size_max == 0) {
2864 access_size_max = 4;
2867 /* Bound the maximum access by the alignment of the address. */
2868 if (!mr->ops->impl.unaligned) {
2869 unsigned align_size_max = addr & -addr;
2870 if (align_size_max != 0 && align_size_max < access_size_max) {
2871 access_size_max = align_size_max;
2875 /* Don't attempt accesses larger than the maximum. */
2876 if (l > access_size_max) {
2877 l = access_size_max;
2879 l = pow2floor(l);
2881 return l;
2884 static bool prepare_mmio_access(MemoryRegion *mr)
2886 bool unlocked = !qemu_mutex_iothread_locked();
2887 bool release_lock = false;
2889 if (unlocked && mr->global_locking) {
2890 qemu_mutex_lock_iothread();
2891 unlocked = false;
2892 release_lock = true;
2894 if (mr->flush_coalesced_mmio) {
2895 if (unlocked) {
2896 qemu_mutex_lock_iothread();
2898 qemu_flush_coalesced_mmio_buffer();
2899 if (unlocked) {
2900 qemu_mutex_unlock_iothread();
2904 return release_lock;
2907 /* Called within RCU critical section. */
2908 static MemTxResult address_space_write_continue(AddressSpace *as, hwaddr addr,
2909 MemTxAttrs attrs,
2910 const uint8_t *buf,
2911 int len, hwaddr addr1,
2912 hwaddr l, MemoryRegion *mr)
2914 uint8_t *ptr;
2915 uint64_t val;
2916 MemTxResult result = MEMTX_OK;
2917 bool release_lock = false;
2919 for (;;) {
2920 if (!memory_access_is_direct(mr, true)) {
2921 release_lock |= prepare_mmio_access(mr);
2922 l = memory_access_size(mr, l, addr1);
2923 /* XXX: could force current_cpu to NULL to avoid
2924 potential bugs */
2925 switch (l) {
2926 case 8:
2927 /* 64 bit write access */
2928 val = ldq_p(buf);
2929 result |= memory_region_dispatch_write(mr, addr1, val, 8,
2930 attrs);
2931 break;
2932 case 4:
2933 /* 32 bit write access */
2934 val = (uint32_t)ldl_p(buf);
2935 result |= memory_region_dispatch_write(mr, addr1, val, 4,
2936 attrs);
2937 break;
2938 case 2:
2939 /* 16 bit write access */
2940 val = lduw_p(buf);
2941 result |= memory_region_dispatch_write(mr, addr1, val, 2,
2942 attrs);
2943 break;
2944 case 1:
2945 /* 8 bit write access */
2946 val = ldub_p(buf);
2947 result |= memory_region_dispatch_write(mr, addr1, val, 1,
2948 attrs);
2949 break;
2950 default:
2951 abort();
2953 } else {
2954 /* RAM case */
2955 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2956 memcpy(ptr, buf, l);
2957 invalidate_and_set_dirty(mr, addr1, l);
2960 if (release_lock) {
2961 qemu_mutex_unlock_iothread();
2962 release_lock = false;
2965 len -= l;
2966 buf += l;
2967 addr += l;
2969 if (!len) {
2970 break;
2973 l = len;
2974 mr = address_space_translate(as, addr, &addr1, &l, true);
2977 return result;
2980 MemTxResult address_space_write(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2981 const uint8_t *buf, int len)
2983 hwaddr l;
2984 hwaddr addr1;
2985 MemoryRegion *mr;
2986 MemTxResult result = MEMTX_OK;
2988 if (len > 0) {
2989 rcu_read_lock();
2990 l = len;
2991 mr = address_space_translate(as, addr, &addr1, &l, true);
2992 result = address_space_write_continue(as, addr, attrs, buf, len,
2993 addr1, l, mr);
2994 rcu_read_unlock();
2997 return result;
3000 /* Called within RCU critical section. */
3001 MemTxResult address_space_read_continue(AddressSpace *as, hwaddr addr,
3002 MemTxAttrs attrs, uint8_t *buf,
3003 int len, hwaddr addr1, hwaddr l,
3004 MemoryRegion *mr)
3006 uint8_t *ptr;
3007 uint64_t val;
3008 MemTxResult result = MEMTX_OK;
3009 bool release_lock = false;
3011 for (;;) {
3012 if (!memory_access_is_direct(mr, false)) {
3013 /* I/O case */
3014 release_lock |= prepare_mmio_access(mr);
3015 l = memory_access_size(mr, l, addr1);
3016 switch (l) {
3017 case 8:
3018 /* 64 bit read access */
3019 result |= memory_region_dispatch_read(mr, addr1, &val, 8,
3020 attrs);
3021 stq_p(buf, val);
3022 break;
3023 case 4:
3024 /* 32 bit read access */
3025 result |= memory_region_dispatch_read(mr, addr1, &val, 4,
3026 attrs);
3027 stl_p(buf, val);
3028 break;
3029 case 2:
3030 /* 16 bit read access */
3031 result |= memory_region_dispatch_read(mr, addr1, &val, 2,
3032 attrs);
3033 stw_p(buf, val);
3034 break;
3035 case 1:
3036 /* 8 bit read access */
3037 result |= memory_region_dispatch_read(mr, addr1, &val, 1,
3038 attrs);
3039 stb_p(buf, val);
3040 break;
3041 default:
3042 abort();
3044 } else {
3045 /* RAM case */
3046 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3047 memcpy(buf, ptr, l);
3050 if (release_lock) {
3051 qemu_mutex_unlock_iothread();
3052 release_lock = false;
3055 len -= l;
3056 buf += l;
3057 addr += l;
3059 if (!len) {
3060 break;
3063 l = len;
3064 mr = address_space_translate(as, addr, &addr1, &l, false);
3067 return result;
3070 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3071 MemTxAttrs attrs, uint8_t *buf, int len)
3073 hwaddr l;
3074 hwaddr addr1;
3075 MemoryRegion *mr;
3076 MemTxResult result = MEMTX_OK;
3078 if (len > 0) {
3079 rcu_read_lock();
3080 l = len;
3081 mr = address_space_translate(as, addr, &addr1, &l, false);
3082 result = address_space_read_continue(as, addr, attrs, buf, len,
3083 addr1, l, mr);
3084 rcu_read_unlock();
3087 return result;
3090 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3091 uint8_t *buf, int len, bool is_write)
3093 if (is_write) {
3094 return address_space_write(as, addr, attrs, (uint8_t *)buf, len);
3095 } else {
3096 return address_space_read(as, addr, attrs, (uint8_t *)buf, len);
3100 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
3101 int len, int is_write)
3103 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3104 buf, len, is_write);
3107 enum write_rom_type {
3108 WRITE_DATA,
3109 FLUSH_CACHE,
3112 static inline void cpu_physical_memory_write_rom_internal(AddressSpace *as,
3113 hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
3115 hwaddr l;
3116 uint8_t *ptr;
3117 hwaddr addr1;
3118 MemoryRegion *mr;
3120 rcu_read_lock();
3121 while (len > 0) {
3122 l = len;
3123 mr = address_space_translate(as, addr, &addr1, &l, true);
3125 if (!(memory_region_is_ram(mr) ||
3126 memory_region_is_romd(mr))) {
3127 l = memory_access_size(mr, l, addr1);
3128 } else {
3129 /* ROM/RAM case */
3130 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3131 switch (type) {
3132 case WRITE_DATA:
3133 memcpy(ptr, buf, l);
3134 invalidate_and_set_dirty(mr, addr1, l);
3135 break;
3136 case FLUSH_CACHE:
3137 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
3138 break;
3141 len -= l;
3142 buf += l;
3143 addr += l;
3145 rcu_read_unlock();
3148 /* used for ROM loading : can write in RAM and ROM */
3149 void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
3150 const uint8_t *buf, int len)
3152 cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
3155 void cpu_flush_icache_range(hwaddr start, int len)
3158 * This function should do the same thing as an icache flush that was
3159 * triggered from within the guest. For TCG we are always cache coherent,
3160 * so there is no need to flush anything. For KVM / Xen we need to flush
3161 * the host's instruction cache at least.
3163 if (tcg_enabled()) {
3164 return;
3167 cpu_physical_memory_write_rom_internal(&address_space_memory,
3168 start, NULL, len, FLUSH_CACHE);
3171 typedef struct {
3172 MemoryRegion *mr;
3173 void *buffer;
3174 hwaddr addr;
3175 hwaddr len;
3176 bool in_use;
3177 } BounceBuffer;
3179 static BounceBuffer bounce;
3181 typedef struct MapClient {
3182 QEMUBH *bh;
3183 QLIST_ENTRY(MapClient) link;
3184 } MapClient;
3186 QemuMutex map_client_list_lock;
3187 static QLIST_HEAD(map_client_list, MapClient) map_client_list
3188 = QLIST_HEAD_INITIALIZER(map_client_list);
3190 static void cpu_unregister_map_client_do(MapClient *client)
3192 QLIST_REMOVE(client, link);
3193 g_free(client);
3196 static void cpu_notify_map_clients_locked(void)
3198 MapClient *client;
3200 while (!QLIST_EMPTY(&map_client_list)) {
3201 client = QLIST_FIRST(&map_client_list);
3202 qemu_bh_schedule(client->bh);
3203 cpu_unregister_map_client_do(client);
3207 void cpu_register_map_client(QEMUBH *bh)
3209 MapClient *client = g_malloc(sizeof(*client));
3211 qemu_mutex_lock(&map_client_list_lock);
3212 client->bh = bh;
3213 QLIST_INSERT_HEAD(&map_client_list, client, link);
3214 if (!atomic_read(&bounce.in_use)) {
3215 cpu_notify_map_clients_locked();
3217 qemu_mutex_unlock(&map_client_list_lock);
3220 void cpu_exec_init_all(void)
3222 qemu_mutex_init(&ram_list.mutex);
3223 /* The data structures we set up here depend on knowing the page size,
3224 * so no more changes can be made after this point.
3225 * In an ideal world, nothing we did before we had finished the
3226 * machine setup would care about the target page size, and we could
3227 * do this much later, rather than requiring board models to state
3228 * up front what their requirements are.
3230 finalize_target_page_bits();
3231 io_mem_init();
3232 memory_map_init();
3233 qemu_mutex_init(&map_client_list_lock);
3236 void cpu_unregister_map_client(QEMUBH *bh)
3238 MapClient *client;
3240 qemu_mutex_lock(&map_client_list_lock);
3241 QLIST_FOREACH(client, &map_client_list, link) {
3242 if (client->bh == bh) {
3243 cpu_unregister_map_client_do(client);
3244 break;
3247 qemu_mutex_unlock(&map_client_list_lock);
3250 static void cpu_notify_map_clients(void)
3252 qemu_mutex_lock(&map_client_list_lock);
3253 cpu_notify_map_clients_locked();
3254 qemu_mutex_unlock(&map_client_list_lock);
3257 bool address_space_access_valid(AddressSpace *as, hwaddr addr, int len, bool is_write)
3259 MemoryRegion *mr;
3260 hwaddr l, xlat;
3262 rcu_read_lock();
3263 while (len > 0) {
3264 l = len;
3265 mr = address_space_translate(as, addr, &xlat, &l, is_write);
3266 if (!memory_access_is_direct(mr, is_write)) {
3267 l = memory_access_size(mr, l, addr);
3268 if (!memory_region_access_valid(mr, xlat, l, is_write)) {
3269 rcu_read_unlock();
3270 return false;
3274 len -= l;
3275 addr += l;
3277 rcu_read_unlock();
3278 return true;
3281 static hwaddr
3282 address_space_extend_translation(AddressSpace *as, hwaddr addr, hwaddr target_len,
3283 MemoryRegion *mr, hwaddr base, hwaddr len,
3284 bool is_write)
3286 hwaddr done = 0;
3287 hwaddr xlat;
3288 MemoryRegion *this_mr;
3290 for (;;) {
3291 target_len -= len;
3292 addr += len;
3293 done += len;
3294 if (target_len == 0) {
3295 return done;
3298 len = target_len;
3299 this_mr = address_space_translate(as, addr, &xlat, &len, is_write);
3300 if (this_mr != mr || xlat != base + done) {
3301 return done;
3306 /* Map a physical memory region into a host virtual address.
3307 * May map a subset of the requested range, given by and returned in *plen.
3308 * May return NULL if resources needed to perform the mapping are exhausted.
3309 * Use only for reads OR writes - not for read-modify-write operations.
3310 * Use cpu_register_map_client() to know when retrying the map operation is
3311 * likely to succeed.
3313 void *address_space_map(AddressSpace *as,
3314 hwaddr addr,
3315 hwaddr *plen,
3316 bool is_write)
3318 hwaddr len = *plen;
3319 hwaddr l, xlat;
3320 MemoryRegion *mr;
3321 void *ptr;
3323 if (len == 0) {
3324 return NULL;
3327 l = len;
3328 rcu_read_lock();
3329 mr = address_space_translate(as, addr, &xlat, &l, is_write);
3331 if (!memory_access_is_direct(mr, is_write)) {
3332 if (atomic_xchg(&bounce.in_use, true)) {
3333 rcu_read_unlock();
3334 return NULL;
3336 /* Avoid unbounded allocations */
3337 l = MIN(l, TARGET_PAGE_SIZE);
3338 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3339 bounce.addr = addr;
3340 bounce.len = l;
3342 memory_region_ref(mr);
3343 bounce.mr = mr;
3344 if (!is_write) {
3345 address_space_read(as, addr, MEMTXATTRS_UNSPECIFIED,
3346 bounce.buffer, l);
3349 rcu_read_unlock();
3350 *plen = l;
3351 return bounce.buffer;
3355 memory_region_ref(mr);
3356 *plen = address_space_extend_translation(as, addr, len, mr, xlat, l, is_write);
3357 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3358 rcu_read_unlock();
3360 return ptr;
3363 /* Unmaps a memory region previously mapped by address_space_map().
3364 * Will also mark the memory as dirty if is_write == 1. access_len gives
3365 * the amount of memory that was actually read or written by the caller.
3367 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3368 int is_write, hwaddr access_len)
3370 if (buffer != bounce.buffer) {
3371 MemoryRegion *mr;
3372 ram_addr_t addr1;
3374 mr = memory_region_from_host(buffer, &addr1);
3375 assert(mr != NULL);
3376 if (is_write) {
3377 invalidate_and_set_dirty(mr, addr1, access_len);
3379 if (xen_enabled()) {
3380 xen_invalidate_map_cache_entry(buffer);
3382 memory_region_unref(mr);
3383 return;
3385 if (is_write) {
3386 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3387 bounce.buffer, access_len);
3389 qemu_vfree(bounce.buffer);
3390 bounce.buffer = NULL;
3391 memory_region_unref(bounce.mr);
3392 atomic_mb_set(&bounce.in_use, false);
3393 cpu_notify_map_clients();
3396 void *cpu_physical_memory_map(hwaddr addr,
3397 hwaddr *plen,
3398 int is_write)
3400 return address_space_map(&address_space_memory, addr, plen, is_write);
3403 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3404 int is_write, hwaddr access_len)
3406 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3409 #define ARG1_DECL AddressSpace *as
3410 #define ARG1 as
3411 #define SUFFIX
3412 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3413 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3414 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3415 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3416 #define RCU_READ_LOCK(...) rcu_read_lock()
3417 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3418 #include "memory_ldst.inc.c"
3420 int64_t address_space_cache_init(MemoryRegionCache *cache,
3421 AddressSpace *as,
3422 hwaddr addr,
3423 hwaddr len,
3424 bool is_write)
3426 cache->len = len;
3427 cache->as = as;
3428 cache->xlat = addr;
3429 return len;
3432 void address_space_cache_invalidate(MemoryRegionCache *cache,
3433 hwaddr addr,
3434 hwaddr access_len)
3438 void address_space_cache_destroy(MemoryRegionCache *cache)
3440 cache->as = NULL;
3443 #define ARG1_DECL MemoryRegionCache *cache
3444 #define ARG1 cache
3445 #define SUFFIX _cached
3446 #define TRANSLATE(addr, ...) \
3447 address_space_translate(cache->as, cache->xlat + (addr), __VA_ARGS__)
3448 #define IS_DIRECT(mr, is_write) true
3449 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3450 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3451 #define RCU_READ_LOCK() rcu_read_lock()
3452 #define RCU_READ_UNLOCK() rcu_read_unlock()
3453 #include "memory_ldst.inc.c"
3455 /* virtual memory access for debug (includes writing to ROM) */
3456 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3457 uint8_t *buf, int len, int is_write)
3459 int l;
3460 hwaddr phys_addr;
3461 target_ulong page;
3463 cpu_synchronize_state(cpu);
3464 while (len > 0) {
3465 int asidx;
3466 MemTxAttrs attrs;
3468 page = addr & TARGET_PAGE_MASK;
3469 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3470 asidx = cpu_asidx_from_attrs(cpu, attrs);
3471 /* if no physical page mapped, return an error */
3472 if (phys_addr == -1)
3473 return -1;
3474 l = (page + TARGET_PAGE_SIZE) - addr;
3475 if (l > len)
3476 l = len;
3477 phys_addr += (addr & ~TARGET_PAGE_MASK);
3478 if (is_write) {
3479 cpu_physical_memory_write_rom(cpu->cpu_ases[asidx].as,
3480 phys_addr, buf, l);
3481 } else {
3482 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3483 MEMTXATTRS_UNSPECIFIED,
3484 buf, l, 0);
3486 len -= l;
3487 buf += l;
3488 addr += l;
3490 return 0;
3494 * Allows code that needs to deal with migration bitmaps etc to still be built
3495 * target independent.
3497 size_t qemu_target_page_size(void)
3499 return TARGET_PAGE_SIZE;
3502 int qemu_target_page_bits(void)
3504 return TARGET_PAGE_BITS;
3507 int qemu_target_page_bits_min(void)
3509 return TARGET_PAGE_BITS_MIN;
3511 #endif
3514 * A helper function for the _utterly broken_ virtio device model to find out if
3515 * it's running on a big endian machine. Don't do this at home kids!
3517 bool target_words_bigendian(void);
3518 bool target_words_bigendian(void)
3520 #if defined(TARGET_WORDS_BIGENDIAN)
3521 return true;
3522 #else
3523 return false;
3524 #endif
3527 #ifndef CONFIG_USER_ONLY
3528 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3530 MemoryRegion*mr;
3531 hwaddr l = 1;
3532 bool res;
3534 rcu_read_lock();
3535 mr = address_space_translate(&address_space_memory,
3536 phys_addr, &phys_addr, &l, false);
3538 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3539 rcu_read_unlock();
3540 return res;
3543 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3545 RAMBlock *block;
3546 int ret = 0;
3548 rcu_read_lock();
3549 RAMBLOCK_FOREACH(block) {
3550 ret = func(block->idstr, block->host, block->offset,
3551 block->used_length, opaque);
3552 if (ret) {
3553 break;
3556 rcu_read_unlock();
3557 return ret;
3561 * Unmap pages of memory from start to start+length such that
3562 * they a) read as 0, b) Trigger whatever fault mechanism
3563 * the OS provides for postcopy.
3564 * The pages must be unmapped by the end of the function.
3565 * Returns: 0 on success, none-0 on failure
3568 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3570 int ret = -1;
3572 uint8_t *host_startaddr = rb->host + start;
3574 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
3575 error_report("ram_block_discard_range: Unaligned start address: %p",
3576 host_startaddr);
3577 goto err;
3580 if ((start + length) <= rb->used_length) {
3581 uint8_t *host_endaddr = host_startaddr + length;
3582 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
3583 error_report("ram_block_discard_range: Unaligned end address: %p",
3584 host_endaddr);
3585 goto err;
3588 errno = ENOTSUP; /* If we are missing MADVISE etc */
3590 if (rb->page_size == qemu_host_page_size) {
3591 #if defined(CONFIG_MADVISE)
3592 /* Note: We need the madvise MADV_DONTNEED behaviour of definitely
3593 * freeing the page.
3595 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3596 #endif
3597 } else {
3598 /* Huge page case - unfortunately it can't do DONTNEED, but
3599 * it can do the equivalent by FALLOC_FL_PUNCH_HOLE in the
3600 * huge page file.
3602 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3603 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3604 start, length);
3605 #endif
3607 if (ret) {
3608 ret = -errno;
3609 error_report("ram_block_discard_range: Failed to discard range "
3610 "%s:%" PRIx64 " +%zx (%d)",
3611 rb->idstr, start, length, ret);
3613 } else {
3614 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3615 "/%zx/" RAM_ADDR_FMT")",
3616 rb->idstr, start, length, rb->used_length);
3619 err:
3620 return ret;
3623 #endif
3625 void page_size_init(void)
3627 /* NOTE: we can always suppose that qemu_host_page_size >=
3628 TARGET_PAGE_SIZE */
3629 qemu_real_host_page_size = getpagesize();
3630 qemu_real_host_page_mask = -(intptr_t)qemu_real_host_page_size;
3631 if (qemu_host_page_size == 0) {
3632 qemu_host_page_size = qemu_real_host_page_size;
3634 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
3635 qemu_host_page_size = TARGET_PAGE_SIZE;
3637 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;