Merge tag 'v2.9.0-rc3'
[qemu/ar7.git] / exec.c
blobd032c26190e65295f6bf241dc0c43af074aa3f79
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 "tcg.h"
28 #include "hw/qdev-core.h"
29 #if !defined(CONFIG_USER_ONLY)
30 #include "hw/boards.h"
31 #include "hw/xen/xen.h"
32 #endif
33 #include "sysemu/kvm.h"
34 #include "sysemu/sysemu.h"
35 #include "qemu/timer.h"
36 #include "qemu/config-file.h"
37 #include "qemu/error-report.h"
38 #if defined(CONFIG_USER_ONLY)
39 #include "qemu.h"
40 #else /* !CONFIG_USER_ONLY */
41 #include "hw/hw.h"
42 #include "exec/memory.h"
43 #include "exec/ioport.h"
44 #include "sysemu/dma.h"
45 #include "sysemu/numa.h"
46 #include "sysemu/hw_accel.h"
47 #include "exec/address-spaces.h"
48 #include "sysemu/xen-mapcache.h"
49 #include "trace-root.h"
51 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
52 #include <fcntl.h>
53 #include <linux/falloc.h>
54 #endif
56 #endif
57 #include "exec/cpu-all.h"
58 #include "qemu/rcu_queue.h"
59 #include "qemu/main-loop.h"
60 #include "translate-all.h"
61 #include "sysemu/replay.h"
63 #include "exec/memory-internal.h"
64 #include "exec/ram_addr.h"
65 #include "exec/log.h"
67 #include "migration/vmstate.h"
69 #include "qemu/range.h"
70 #ifndef _WIN32
71 #include "qemu/mmap-alloc.h"
72 #endif
74 //#define DEBUG_SUBPAGE
76 #if !defined(CONFIG_USER_ONLY)
77 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
78 * are protected by the ramlist lock.
80 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
82 static MemoryRegion *system_memory;
83 static MemoryRegion *system_io;
85 AddressSpace address_space_io;
86 AddressSpace address_space_memory;
88 MemoryRegion io_mem_rom, io_mem_notdirty;
89 static MemoryRegion io_mem_unassigned;
91 /* RAM is pre-allocated and passed into qemu_ram_alloc_from_ptr */
92 #define RAM_PREALLOC (1 << 0)
94 /* RAM is mmap-ed with MAP_SHARED */
95 #define RAM_SHARED (1 << 1)
97 /* Only a portion of RAM (used_length) is actually used, and migrated.
98 * This used_length size can change across reboots.
100 #define RAM_RESIZEABLE (1 << 2)
102 #endif
104 #ifdef TARGET_PAGE_BITS_VARY
105 int target_page_bits;
106 bool target_page_bits_decided;
107 #endif
109 struct CPUTailQ cpus = QTAILQ_HEAD_INITIALIZER(cpus);
110 /* current CPU in the current thread. It is only valid inside
111 cpu_exec() */
112 __thread CPUState *current_cpu;
113 /* 0 = Do not count executed instructions.
114 1 = Precise instruction counting.
115 2 = Adaptive rate instruction counting. */
116 int use_icount;
118 bool set_preferred_target_page_bits(int bits)
120 /* The target page size is the lowest common denominator for all
121 * the CPUs in the system, so we can only make it smaller, never
122 * larger. And we can't make it smaller once we've committed to
123 * a particular size.
125 #ifdef TARGET_PAGE_BITS_VARY
126 assert(bits >= TARGET_PAGE_BITS_MIN);
127 if (target_page_bits == 0 || target_page_bits > bits) {
128 if (target_page_bits_decided) {
129 return false;
131 target_page_bits = bits;
133 #endif
134 return true;
137 #if !defined(CONFIG_USER_ONLY)
139 static void finalize_target_page_bits(void)
141 #ifdef TARGET_PAGE_BITS_VARY
142 if (target_page_bits == 0) {
143 target_page_bits = TARGET_PAGE_BITS_MIN;
145 target_page_bits_decided = true;
146 #endif
149 typedef struct PhysPageEntry PhysPageEntry;
151 struct PhysPageEntry {
152 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
153 uint32_t skip : 6;
154 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
155 uint32_t ptr : 26;
158 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
160 /* Size of the L2 (and L3, etc) page tables. */
161 #define ADDR_SPACE_BITS 64
163 #define P_L2_BITS 9
164 #define P_L2_SIZE (1 << P_L2_BITS)
166 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
168 typedef PhysPageEntry Node[P_L2_SIZE];
170 typedef struct PhysPageMap {
171 struct rcu_head rcu;
173 unsigned sections_nb;
174 unsigned sections_nb_alloc;
175 unsigned nodes_nb;
176 unsigned nodes_nb_alloc;
177 Node *nodes;
178 MemoryRegionSection *sections;
179 } PhysPageMap;
181 struct AddressSpaceDispatch {
182 struct rcu_head rcu;
184 MemoryRegionSection *mru_section;
185 /* This is a multi-level map on the physical address space.
186 * The bottom level has pointers to MemoryRegionSections.
188 PhysPageEntry phys_map;
189 PhysPageMap map;
190 AddressSpace *as;
193 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
194 typedef struct subpage_t {
195 MemoryRegion iomem;
196 AddressSpace *as;
197 hwaddr base;
198 uint16_t sub_section[];
199 } subpage_t;
201 #define PHYS_SECTION_UNASSIGNED 0
202 #define PHYS_SECTION_NOTDIRTY 1
203 #define PHYS_SECTION_ROM 2
204 #define PHYS_SECTION_WATCH 3
206 static void io_mem_init(void);
207 static void memory_map_init(void);
208 static void tcg_commit(MemoryListener *listener);
210 static MemoryRegion io_mem_watch;
213 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
214 * @cpu: the CPU whose AddressSpace this is
215 * @as: the AddressSpace itself
216 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
217 * @tcg_as_listener: listener for tracking changes to the AddressSpace
219 struct CPUAddressSpace {
220 CPUState *cpu;
221 AddressSpace *as;
222 struct AddressSpaceDispatch *memory_dispatch;
223 MemoryListener tcg_as_listener;
226 #endif
228 #if !defined(CONFIG_USER_ONLY)
230 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
232 static unsigned alloc_hint = 16;
233 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
234 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, alloc_hint);
235 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, map->nodes_nb + nodes);
236 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
237 alloc_hint = map->nodes_nb_alloc;
241 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
243 unsigned i;
244 uint32_t ret;
245 PhysPageEntry e;
246 PhysPageEntry *p;
248 ret = map->nodes_nb++;
249 p = map->nodes[ret];
250 assert(ret != PHYS_MAP_NODE_NIL);
251 assert(ret != map->nodes_nb_alloc);
253 e.skip = leaf ? 0 : 1;
254 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
255 for (i = 0; i < P_L2_SIZE; ++i) {
256 memcpy(&p[i], &e, sizeof(e));
258 return ret;
261 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
262 hwaddr *index, hwaddr *nb, uint16_t leaf,
263 int level)
265 PhysPageEntry *p;
266 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
268 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
269 lp->ptr = phys_map_node_alloc(map, level == 0);
271 p = map->nodes[lp->ptr];
272 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
274 while (*nb && lp < &p[P_L2_SIZE]) {
275 if ((*index & (step - 1)) == 0 && *nb >= step) {
276 lp->skip = 0;
277 lp->ptr = leaf;
278 *index += step;
279 *nb -= step;
280 } else {
281 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
283 ++lp;
287 static void phys_page_set(AddressSpaceDispatch *d,
288 hwaddr index, hwaddr nb,
289 uint16_t leaf)
291 /* Wildly overreserve - it doesn't matter much. */
292 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
294 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
297 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
298 * and update our entry so we can skip it and go directly to the destination.
300 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
302 unsigned valid_ptr = P_L2_SIZE;
303 int valid = 0;
304 PhysPageEntry *p;
305 int i;
307 if (lp->ptr == PHYS_MAP_NODE_NIL) {
308 return;
311 p = nodes[lp->ptr];
312 for (i = 0; i < P_L2_SIZE; i++) {
313 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
314 continue;
317 valid_ptr = i;
318 valid++;
319 if (p[i].skip) {
320 phys_page_compact(&p[i], nodes);
324 /* We can only compress if there's only one child. */
325 if (valid != 1) {
326 return;
329 assert(valid_ptr < P_L2_SIZE);
331 /* Don't compress if it won't fit in the # of bits we have. */
332 if (lp->skip + p[valid_ptr].skip >= (1 << 3)) {
333 return;
336 lp->ptr = p[valid_ptr].ptr;
337 if (!p[valid_ptr].skip) {
338 /* If our only child is a leaf, make this a leaf. */
339 /* By design, we should have made this node a leaf to begin with so we
340 * should never reach here.
341 * But since it's so simple to handle this, let's do it just in case we
342 * change this rule.
344 lp->skip = 0;
345 } else {
346 lp->skip += p[valid_ptr].skip;
350 static void phys_page_compact_all(AddressSpaceDispatch *d, int nodes_nb)
352 if (d->phys_map.skip) {
353 phys_page_compact(&d->phys_map, d->map.nodes);
357 static inline bool section_covers_addr(const MemoryRegionSection *section,
358 hwaddr addr)
360 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
361 * the section must cover the entire address space.
363 return int128_gethi(section->size) ||
364 range_covers_byte(section->offset_within_address_space,
365 int128_getlo(section->size), addr);
368 static MemoryRegionSection *phys_page_find(PhysPageEntry lp, hwaddr addr,
369 Node *nodes, MemoryRegionSection *sections)
371 PhysPageEntry *p;
372 hwaddr index = addr >> TARGET_PAGE_BITS;
373 int i;
375 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
376 if (lp.ptr == PHYS_MAP_NODE_NIL) {
377 return &sections[PHYS_SECTION_UNASSIGNED];
379 p = nodes[lp.ptr];
380 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
383 if (section_covers_addr(&sections[lp.ptr], addr)) {
384 return &sections[lp.ptr];
385 } else {
386 return &sections[PHYS_SECTION_UNASSIGNED];
390 bool memory_region_is_unassigned(MemoryRegion *mr)
392 return mr != &io_mem_rom && mr != &io_mem_notdirty && !mr->rom_device
393 && mr != &io_mem_watch;
396 /* Called from RCU critical section */
397 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
398 hwaddr addr,
399 bool resolve_subpage)
401 MemoryRegionSection *section = atomic_read(&d->mru_section);
402 subpage_t *subpage;
403 bool update;
405 if (section && section != &d->map.sections[PHYS_SECTION_UNASSIGNED] &&
406 section_covers_addr(section, addr)) {
407 update = false;
408 } else {
409 section = phys_page_find(d->phys_map, addr, d->map.nodes,
410 d->map.sections);
411 update = true;
413 if (resolve_subpage && section->mr->subpage) {
414 subpage = container_of(section->mr, subpage_t, iomem);
415 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
417 if (update) {
418 atomic_set(&d->mru_section, section);
420 return section;
423 /* Called from RCU critical section */
424 static MemoryRegionSection *
425 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
426 hwaddr *plen, bool resolve_subpage)
428 MemoryRegionSection *section;
429 MemoryRegion *mr;
430 Int128 diff;
432 section = address_space_lookup_region(d, addr, resolve_subpage);
433 /* Compute offset within MemoryRegionSection */
434 addr -= section->offset_within_address_space;
436 /* Compute offset within MemoryRegion */
437 *xlat = addr + section->offset_within_region;
439 mr = section->mr;
441 /* MMIO registers can be expected to perform full-width accesses based only
442 * on their address, without considering adjacent registers that could
443 * decode to completely different MemoryRegions. When such registers
444 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
445 * regions overlap wildly. For this reason we cannot clamp the accesses
446 * here.
448 * If the length is small (as is the case for address_space_ldl/stl),
449 * everything works fine. If the incoming length is large, however,
450 * the caller really has to do the clamping through memory_access_size.
452 if (memory_region_is_ram(mr)) {
453 diff = int128_sub(section->size, int128_make64(addr));
454 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
456 return section;
459 /* Called from RCU critical section */
460 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
461 bool is_write)
463 IOMMUTLBEntry iotlb = {0};
464 MemoryRegionSection *section;
465 MemoryRegion *mr;
467 for (;;) {
468 AddressSpaceDispatch *d = atomic_rcu_read(&as->dispatch);
469 section = address_space_lookup_region(d, addr, false);
470 addr = addr - section->offset_within_address_space
471 + section->offset_within_region;
472 mr = section->mr;
474 if (!mr->iommu_ops) {
475 break;
478 iotlb = mr->iommu_ops->translate(mr, addr, is_write);
479 if (!(iotlb.perm & (1 << is_write))) {
480 iotlb.target_as = NULL;
481 break;
484 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
485 | (addr & iotlb.addr_mask));
486 as = iotlb.target_as;
489 return iotlb;
492 /* Called from RCU critical section */
493 MemoryRegion *address_space_translate(AddressSpace *as, hwaddr addr,
494 hwaddr *xlat, hwaddr *plen,
495 bool is_write)
497 IOMMUTLBEntry iotlb;
498 MemoryRegionSection *section;
499 MemoryRegion *mr;
501 for (;;) {
502 AddressSpaceDispatch *d = atomic_rcu_read(&as->dispatch);
503 section = address_space_translate_internal(d, addr, &addr, plen, true);
504 mr = section->mr;
506 if (!mr->iommu_ops) {
507 break;
510 iotlb = mr->iommu_ops->translate(mr, addr, is_write);
511 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
512 | (addr & iotlb.addr_mask));
513 *plen = MIN(*plen, (addr | iotlb.addr_mask) - addr + 1);
514 if (!(iotlb.perm & (1 << is_write))) {
515 mr = &io_mem_unassigned;
516 break;
519 as = iotlb.target_as;
522 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
523 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
524 *plen = MIN(page, *plen);
527 *xlat = addr;
528 return mr;
531 /* Called from RCU critical section */
532 MemoryRegionSection *
533 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
534 hwaddr *xlat, hwaddr *plen)
536 MemoryRegionSection *section;
537 AddressSpaceDispatch *d = atomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
539 section = address_space_translate_internal(d, addr, xlat, plen, false);
541 assert(!section->mr->iommu_ops);
542 return section;
544 #endif
546 #if !defined(CONFIG_USER_ONLY)
548 static int cpu_common_post_load(void *opaque, int version_id)
550 CPUState *cpu = opaque;
552 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
553 version_id is increased. */
554 cpu->interrupt_request &= ~0x01;
555 tlb_flush(cpu);
557 return 0;
560 static int cpu_common_pre_load(void *opaque)
562 CPUState *cpu = opaque;
564 cpu->exception_index = -1;
566 return 0;
569 static bool cpu_common_exception_index_needed(void *opaque)
571 CPUState *cpu = opaque;
573 return tcg_enabled() && cpu->exception_index != -1;
576 static const VMStateDescription vmstate_cpu_common_exception_index = {
577 .name = "cpu_common/exception_index",
578 .version_id = 1,
579 .minimum_version_id = 1,
580 .needed = cpu_common_exception_index_needed,
581 .fields = (VMStateField[]) {
582 VMSTATE_INT32(exception_index, CPUState),
583 VMSTATE_END_OF_LIST()
587 static bool cpu_common_crash_occurred_needed(void *opaque)
589 CPUState *cpu = opaque;
591 return cpu->crash_occurred;
594 static const VMStateDescription vmstate_cpu_common_crash_occurred = {
595 .name = "cpu_common/crash_occurred",
596 .version_id = 1,
597 .minimum_version_id = 1,
598 .needed = cpu_common_crash_occurred_needed,
599 .fields = (VMStateField[]) {
600 VMSTATE_BOOL(crash_occurred, CPUState),
601 VMSTATE_END_OF_LIST()
605 const VMStateDescription vmstate_cpu_common = {
606 .name = "cpu_common",
607 .version_id = 1,
608 .minimum_version_id = 1,
609 .pre_load = cpu_common_pre_load,
610 .post_load = cpu_common_post_load,
611 .fields = (VMStateField[]) {
612 VMSTATE_UINT32(halted, CPUState),
613 VMSTATE_UINT32(interrupt_request, CPUState),
614 VMSTATE_END_OF_LIST()
616 .subsections = (const VMStateDescription*[]) {
617 &vmstate_cpu_common_exception_index,
618 &vmstate_cpu_common_crash_occurred,
619 NULL
623 #endif
625 CPUState *qemu_get_cpu(int index)
627 CPUState *cpu;
629 CPU_FOREACH(cpu) {
630 if (cpu->cpu_index == index) {
631 return cpu;
635 return NULL;
638 #if !defined(CONFIG_USER_ONLY)
639 void cpu_address_space_init(CPUState *cpu, AddressSpace *as, int asidx)
641 CPUAddressSpace *newas;
643 /* Target code should have set num_ases before calling us */
644 assert(asidx < cpu->num_ases);
646 if (asidx == 0) {
647 /* address space 0 gets the convenience alias */
648 cpu->as = as;
651 /* KVM cannot currently support multiple address spaces. */
652 assert(asidx == 0 || !kvm_enabled());
654 if (!cpu->cpu_ases) {
655 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
658 newas = &cpu->cpu_ases[asidx];
659 newas->cpu = cpu;
660 newas->as = as;
661 if (tcg_enabled()) {
662 newas->tcg_as_listener.commit = tcg_commit;
663 memory_listener_register(&newas->tcg_as_listener, as);
667 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
669 /* Return the AddressSpace corresponding to the specified index */
670 return cpu->cpu_ases[asidx].as;
672 #endif
674 void cpu_exec_unrealizefn(CPUState *cpu)
676 CPUClass *cc = CPU_GET_CLASS(cpu);
678 cpu_list_remove(cpu);
680 if (cc->vmsd != NULL) {
681 vmstate_unregister(NULL, cc->vmsd, cpu);
683 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
684 vmstate_unregister(NULL, &vmstate_cpu_common, cpu);
688 void cpu_exec_initfn(CPUState *cpu)
690 #ifdef TARGET_WORDS_BIGENDIAN
691 cpu->bigendian = true;
692 #else
693 cpu->bigendian = false;
694 #endif
695 cpu->as = NULL;
696 cpu->num_ases = 0;
698 #ifndef CONFIG_USER_ONLY
699 cpu->thread_id = qemu_get_thread_id();
701 /* This is a softmmu CPU object, so create a property for it
702 * so users can wire up its memory. (This can't go in qom/cpu.c
703 * because that file is compiled only once for both user-mode
704 * and system builds.) The default if no link is set up is to use
705 * the system address space.
707 object_property_add_link(OBJECT(cpu), "memory", TYPE_MEMORY_REGION,
708 (Object **)&cpu->memory,
709 qdev_prop_allow_set_link_before_realize,
710 OBJ_PROP_LINK_UNREF_ON_RELEASE,
711 &error_abort);
712 cpu->memory = system_memory;
713 object_ref(OBJECT(cpu->memory));
714 #endif
717 void cpu_exec_realizefn(CPUState *cpu, Error **errp)
719 CPUClass *cc ATTRIBUTE_UNUSED = CPU_GET_CLASS(cpu);
721 cpu_list_add(cpu);
723 #ifndef CONFIG_USER_ONLY
724 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
725 vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
727 if (cc->vmsd != NULL) {
728 vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);
730 #endif
733 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
735 /* Flush the whole TB as this will not have race conditions
736 * even if we don't have proper locking yet.
737 * Ideally we would just invalidate the TBs for the
738 * specified PC.
740 tb_flush(cpu);
743 #if defined(CONFIG_USER_ONLY)
744 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
749 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
750 int flags)
752 return -ENOSYS;
755 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
759 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
760 int flags, CPUWatchpoint **watchpoint)
762 return -ENOSYS;
764 #else
765 /* Add a watchpoint. */
766 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
767 int flags, CPUWatchpoint **watchpoint)
769 CPUWatchpoint *wp;
771 /* forbid ranges which are empty or run off the end of the address space */
772 if (len == 0 || (addr + len - 1) < addr) {
773 error_report("tried to set invalid watchpoint at %"
774 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
775 return -EINVAL;
777 wp = g_malloc(sizeof(*wp));
779 wp->vaddr = addr;
780 wp->len = len;
781 wp->flags = flags;
783 /* keep all GDB-injected watchpoints in front */
784 if (flags & BP_GDB) {
785 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
786 } else {
787 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
790 tlb_flush_page(cpu, addr);
792 if (watchpoint)
793 *watchpoint = wp;
794 return 0;
797 /* Remove a specific watchpoint. */
798 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
799 int flags)
801 CPUWatchpoint *wp;
803 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
804 if (addr == wp->vaddr && len == wp->len
805 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
806 cpu_watchpoint_remove_by_ref(cpu, wp);
807 return 0;
810 return -ENOENT;
813 /* Remove a specific watchpoint by reference. */
814 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
816 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
818 tlb_flush_page(cpu, watchpoint->vaddr);
820 g_free(watchpoint);
823 /* Remove all matching watchpoints. */
824 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
826 CPUWatchpoint *wp, *next;
828 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
829 if (wp->flags & mask) {
830 cpu_watchpoint_remove_by_ref(cpu, wp);
835 /* Return true if this watchpoint address matches the specified
836 * access (ie the address range covered by the watchpoint overlaps
837 * partially or completely with the address range covered by the
838 * access).
840 static inline bool cpu_watchpoint_address_matches(CPUWatchpoint *wp,
841 vaddr addr,
842 vaddr len)
844 /* We know the lengths are non-zero, but a little caution is
845 * required to avoid errors in the case where the range ends
846 * exactly at the top of the address space and so addr + len
847 * wraps round to zero.
849 vaddr wpend = wp->vaddr + wp->len - 1;
850 vaddr addrend = addr + len - 1;
852 return !(addr > wpend || wp->vaddr > addrend);
855 #endif
857 /* Add a breakpoint. */
858 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
859 CPUBreakpoint **breakpoint)
861 CPUBreakpoint *bp;
863 bp = g_malloc(sizeof(*bp));
865 bp->pc = pc;
866 bp->flags = flags;
868 /* keep all GDB-injected breakpoints in front */
869 if (flags & BP_GDB) {
870 QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
871 } else {
872 QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
875 breakpoint_invalidate(cpu, pc);
877 if (breakpoint) {
878 *breakpoint = bp;
880 return 0;
883 /* Remove a specific breakpoint. */
884 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
886 CPUBreakpoint *bp;
888 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
889 if (bp->pc == pc && bp->flags == flags) {
890 cpu_breakpoint_remove_by_ref(cpu, bp);
891 return 0;
894 return -ENOENT;
897 /* Remove a specific breakpoint by reference. */
898 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
900 QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);
902 breakpoint_invalidate(cpu, breakpoint->pc);
904 g_free(breakpoint);
907 /* Remove all matching breakpoints. */
908 void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
910 CPUBreakpoint *bp, *next;
912 QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
913 if (bp->flags & mask) {
914 cpu_breakpoint_remove_by_ref(cpu, bp);
919 /* enable or disable single step mode. EXCP_DEBUG is returned by the
920 CPU loop after each instruction */
921 void cpu_single_step(CPUState *cpu, int enabled)
923 if (cpu->singlestep_enabled != enabled) {
924 cpu->singlestep_enabled = enabled;
925 if (kvm_enabled()) {
926 kvm_update_guest_debug(cpu, 0);
927 } else {
928 /* must flush all the translated code to avoid inconsistencies */
929 /* XXX: only flush what is necessary */
930 tb_flush(cpu);
935 void QEMU_NORETURN cpu_abort(CPUState *cpu, const char *fmt, ...)
937 va_list ap;
938 va_list ap2;
940 va_start(ap, fmt);
941 va_copy(ap2, ap);
942 fprintf(stderr, "qemu: fatal: ");
943 vfprintf(stderr, fmt, ap);
944 fprintf(stderr, "\n");
945 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU | CPU_DUMP_CCOP);
946 if (qemu_log_separate()) {
947 qemu_log_lock();
948 qemu_log("qemu: fatal: ");
949 qemu_log_vprintf(fmt, ap2);
950 qemu_log("\n");
951 log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
952 qemu_log_flush();
953 qemu_log_unlock();
954 qemu_log_close();
956 va_end(ap2);
957 va_end(ap);
958 replay_finish();
959 #if defined(CONFIG_USER_ONLY)
961 struct sigaction act;
962 sigfillset(&act.sa_mask);
963 act.sa_handler = SIG_DFL;
964 sigaction(SIGABRT, &act, NULL);
966 #endif
967 abort();
970 #if !defined(CONFIG_USER_ONLY)
971 /* Called from RCU critical section */
972 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
974 RAMBlock *block;
976 block = atomic_rcu_read(&ram_list.mru_block);
977 if (block && addr - block->offset < block->max_length) {
978 return block;
980 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
981 if (addr - block->offset < block->max_length) {
982 goto found;
986 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
987 abort();
989 found:
990 /* It is safe to write mru_block outside the iothread lock. This
991 * is what happens:
993 * mru_block = xxx
994 * rcu_read_unlock()
995 * xxx removed from list
996 * rcu_read_lock()
997 * read mru_block
998 * mru_block = NULL;
999 * call_rcu(reclaim_ramblock, xxx);
1000 * rcu_read_unlock()
1002 * atomic_rcu_set is not needed here. The block was already published
1003 * when it was placed into the list. Here we're just making an extra
1004 * copy of the pointer.
1006 ram_list.mru_block = block;
1007 return block;
1010 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1012 CPUState *cpu;
1013 ram_addr_t start1;
1014 RAMBlock *block;
1015 ram_addr_t end;
1017 end = TARGET_PAGE_ALIGN(start + length);
1018 start &= TARGET_PAGE_MASK;
1020 rcu_read_lock();
1021 block = qemu_get_ram_block(start);
1022 assert(block == qemu_get_ram_block(end - 1));
1023 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1024 CPU_FOREACH(cpu) {
1025 tlb_reset_dirty(cpu, start1, length);
1027 rcu_read_unlock();
1030 /* Note: start and end must be within the same ram block. */
1031 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1032 ram_addr_t length,
1033 unsigned client)
1035 DirtyMemoryBlocks *blocks;
1036 unsigned long end, page;
1037 bool dirty = false;
1039 if (length == 0) {
1040 return false;
1043 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1044 page = start >> TARGET_PAGE_BITS;
1046 rcu_read_lock();
1048 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1050 while (page < end) {
1051 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1052 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1053 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1055 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1056 offset, num);
1057 page += num;
1060 rcu_read_unlock();
1062 if (dirty && tcg_enabled()) {
1063 tlb_reset_dirty_range_all(start, length);
1066 return dirty;
1069 /* Called from RCU critical section */
1070 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1071 MemoryRegionSection *section,
1072 target_ulong vaddr,
1073 hwaddr paddr, hwaddr xlat,
1074 int prot,
1075 target_ulong *address)
1077 hwaddr iotlb;
1078 CPUWatchpoint *wp;
1080 if (memory_region_is_ram(section->mr)) {
1081 /* Normal RAM. */
1082 iotlb = memory_region_get_ram_addr(section->mr) + xlat;
1083 if (!section->readonly) {
1084 iotlb |= PHYS_SECTION_NOTDIRTY;
1085 } else {
1086 iotlb |= PHYS_SECTION_ROM;
1088 } else {
1089 AddressSpaceDispatch *d;
1091 d = atomic_rcu_read(&section->address_space->dispatch);
1092 iotlb = section - d->map.sections;
1093 iotlb += xlat;
1096 /* Make accesses to pages with watchpoints go via the
1097 watchpoint trap routines. */
1098 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1099 if (cpu_watchpoint_address_matches(wp, vaddr, TARGET_PAGE_SIZE)) {
1100 /* Avoid trapping reads of pages with a write breakpoint. */
1101 if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
1102 iotlb = PHYS_SECTION_WATCH + paddr;
1103 *address |= TLB_MMIO;
1104 break;
1109 return iotlb;
1111 #endif /* defined(CONFIG_USER_ONLY) */
1113 #if !defined(CONFIG_USER_ONLY)
1115 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
1116 uint16_t section);
1117 static subpage_t *subpage_init(AddressSpace *as, hwaddr base);
1119 static void *(*phys_mem_alloc)(size_t size, uint64_t *align) =
1120 qemu_anon_ram_alloc;
1123 * Set a custom physical guest memory alloator.
1124 * Accelerators with unusual needs may need this. Hopefully, we can
1125 * get rid of it eventually.
1127 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align))
1129 phys_mem_alloc = alloc;
1132 static uint16_t phys_section_add(PhysPageMap *map,
1133 MemoryRegionSection *section)
1135 /* The physical section number is ORed with a page-aligned
1136 * pointer to produce the iotlb entries. Thus it should
1137 * never overflow into the page-aligned value.
1139 assert(map->sections_nb < TARGET_PAGE_SIZE);
1141 if (map->sections_nb == map->sections_nb_alloc) {
1142 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1143 map->sections = g_renew(MemoryRegionSection, map->sections,
1144 map->sections_nb_alloc);
1146 map->sections[map->sections_nb] = *section;
1147 memory_region_ref(section->mr);
1148 return map->sections_nb++;
1151 static void phys_section_destroy(MemoryRegion *mr)
1153 bool have_sub_page = mr->subpage;
1155 memory_region_unref(mr);
1157 if (have_sub_page) {
1158 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1159 object_unref(OBJECT(&subpage->iomem));
1160 g_free(subpage);
1164 static void phys_sections_free(PhysPageMap *map)
1166 while (map->sections_nb > 0) {
1167 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1168 phys_section_destroy(section->mr);
1170 g_free(map->sections);
1171 g_free(map->nodes);
1174 static void register_subpage(AddressSpaceDispatch *d, MemoryRegionSection *section)
1176 subpage_t *subpage;
1177 hwaddr base = section->offset_within_address_space
1178 & TARGET_PAGE_MASK;
1179 MemoryRegionSection *existing = phys_page_find(d->phys_map, base,
1180 d->map.nodes, d->map.sections);
1181 MemoryRegionSection subsection = {
1182 .offset_within_address_space = base,
1183 .size = int128_make64(TARGET_PAGE_SIZE),
1185 hwaddr start, end;
1187 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1189 if (!(existing->mr->subpage)) {
1190 subpage = subpage_init(d->as, base);
1191 subsection.address_space = d->as;
1192 subsection.mr = &subpage->iomem;
1193 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1194 phys_section_add(&d->map, &subsection));
1195 } else {
1196 subpage = container_of(existing->mr, subpage_t, iomem);
1198 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1199 end = start + int128_get64(section->size) - 1;
1200 subpage_register(subpage, start, end,
1201 phys_section_add(&d->map, section));
1205 static void register_multipage(AddressSpaceDispatch *d,
1206 MemoryRegionSection *section)
1208 hwaddr start_addr = section->offset_within_address_space;
1209 uint16_t section_index = phys_section_add(&d->map, section);
1210 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1211 TARGET_PAGE_BITS));
1213 assert(num_pages);
1214 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1217 static void mem_add(MemoryListener *listener, MemoryRegionSection *section)
1219 AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
1220 AddressSpaceDispatch *d = as->next_dispatch;
1221 MemoryRegionSection now = *section, remain = *section;
1222 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1224 if (now.offset_within_address_space & ~TARGET_PAGE_MASK) {
1225 uint64_t left = TARGET_PAGE_ALIGN(now.offset_within_address_space)
1226 - now.offset_within_address_space;
1228 now.size = int128_min(int128_make64(left), now.size);
1229 register_subpage(d, &now);
1230 } else {
1231 now.size = int128_zero();
1233 while (int128_ne(remain.size, now.size)) {
1234 remain.size = int128_sub(remain.size, now.size);
1235 remain.offset_within_address_space += int128_get64(now.size);
1236 remain.offset_within_region += int128_get64(now.size);
1237 now = remain;
1238 if (int128_lt(remain.size, page_size)) {
1239 register_subpage(d, &now);
1240 } else if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1241 now.size = page_size;
1242 register_subpage(d, &now);
1243 } else {
1244 now.size = int128_and(now.size, int128_neg(page_size));
1245 register_multipage(d, &now);
1250 void qemu_flush_coalesced_mmio_buffer(void)
1252 if (kvm_enabled())
1253 kvm_flush_coalesced_mmio_buffer();
1256 void qemu_mutex_lock_ramlist(void)
1258 qemu_mutex_lock(&ram_list.mutex);
1261 void qemu_mutex_unlock_ramlist(void)
1263 qemu_mutex_unlock(&ram_list.mutex);
1266 #ifdef __linux__
1268 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1269 * may or may not name the same files / on the same filesystem now as
1270 * when we actually open and map them. Iterate over the file
1271 * descriptors instead, and use qemu_fd_getpagesize().
1273 static int find_max_supported_pagesize(Object *obj, void *opaque)
1275 char *mem_path;
1276 long *hpsize_min = opaque;
1278 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1279 mem_path = object_property_get_str(obj, "mem-path", NULL);
1280 if (mem_path) {
1281 long hpsize = qemu_mempath_getpagesize(mem_path);
1282 if (hpsize < *hpsize_min) {
1283 *hpsize_min = hpsize;
1285 } else {
1286 *hpsize_min = getpagesize();
1290 return 0;
1293 long qemu_getrampagesize(void)
1295 long hpsize = LONG_MAX;
1296 long mainrampagesize;
1297 Object *memdev_root;
1299 if (mem_path) {
1300 mainrampagesize = qemu_mempath_getpagesize(mem_path);
1301 } else {
1302 mainrampagesize = getpagesize();
1305 /* it's possible we have memory-backend objects with
1306 * hugepage-backed RAM. these may get mapped into system
1307 * address space via -numa parameters or memory hotplug
1308 * hooks. we want to take these into account, but we
1309 * also want to make sure these supported hugepage
1310 * sizes are applicable across the entire range of memory
1311 * we may boot from, so we take the min across all
1312 * backends, and assume normal pages in cases where a
1313 * backend isn't backed by hugepages.
1315 memdev_root = object_resolve_path("/objects", NULL);
1316 if (memdev_root) {
1317 object_child_foreach(memdev_root, find_max_supported_pagesize, &hpsize);
1319 if (hpsize == LONG_MAX) {
1320 /* No additional memory regions found ==> Report main RAM page size */
1321 return mainrampagesize;
1324 /* If NUMA is disabled or the NUMA nodes are not backed with a
1325 * memory-backend, then there is at least one node using "normal" RAM,
1326 * so if its page size is smaller we have got to report that size instead.
1328 if (hpsize > mainrampagesize &&
1329 (nb_numa_nodes == 0 || numa_info[0].node_memdev == NULL)) {
1330 static bool warned;
1331 if (!warned) {
1332 error_report("Huge page support disabled (n/a for main memory).");
1333 warned = true;
1335 return mainrampagesize;
1338 return hpsize;
1340 #else
1341 long qemu_getrampagesize(void)
1343 return getpagesize();
1345 #endif
1347 #ifdef __linux__
1348 static int64_t get_file_size(int fd)
1350 int64_t size = lseek(fd, 0, SEEK_END);
1351 if (size < 0) {
1352 return -errno;
1354 return size;
1357 static void *file_ram_alloc(RAMBlock *block,
1358 ram_addr_t memory,
1359 const char *path,
1360 Error **errp)
1362 bool unlink_on_error = false;
1363 char *filename;
1364 char *sanitized_name;
1365 char *c;
1366 void * volatile area = MAP_FAILED;
1367 int fd = -1;
1368 int64_t file_size;
1370 if (kvm_enabled() && !kvm_has_sync_mmu()) {
1371 error_setg(errp,
1372 "host lacks kvm mmu notifiers, -mem-path unsupported");
1373 return NULL;
1376 for (;;) {
1377 fd = open(path, O_RDWR);
1378 if (fd >= 0) {
1379 /* @path names an existing file, use it */
1380 break;
1382 if (errno == ENOENT) {
1383 /* @path names a file that doesn't exist, create it */
1384 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1385 if (fd >= 0) {
1386 unlink_on_error = true;
1387 break;
1389 } else if (errno == EISDIR) {
1390 /* @path names a directory, create a file there */
1391 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1392 sanitized_name = g_strdup(memory_region_name(block->mr));
1393 for (c = sanitized_name; *c != '\0'; c++) {
1394 if (*c == '/') {
1395 *c = '_';
1399 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1400 sanitized_name);
1401 g_free(sanitized_name);
1403 fd = mkstemp(filename);
1404 if (fd >= 0) {
1405 unlink(filename);
1406 g_free(filename);
1407 break;
1409 g_free(filename);
1411 if (errno != EEXIST && errno != EINTR) {
1412 error_setg_errno(errp, errno,
1413 "can't open backing store %s for guest RAM",
1414 path);
1415 goto error;
1418 * Try again on EINTR and EEXIST. The latter happens when
1419 * something else creates the file between our two open().
1423 block->page_size = qemu_fd_getpagesize(fd);
1424 block->mr->align = block->page_size;
1425 #if defined(__s390x__)
1426 if (kvm_enabled()) {
1427 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1429 #endif
1431 file_size = get_file_size(fd);
1433 if (memory < block->page_size) {
1434 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1435 "or larger than page size 0x%zx",
1436 memory, block->page_size);
1437 goto error;
1440 if (file_size > 0 && file_size < memory) {
1441 error_setg(errp, "backing store %s size 0x%" PRIx64
1442 " does not match 'size' option 0x" RAM_ADDR_FMT,
1443 path, file_size, memory);
1444 goto error;
1447 memory = ROUND_UP(memory, block->page_size);
1450 * ftruncate is not supported by hugetlbfs in older
1451 * hosts, so don't bother bailing out on errors.
1452 * If anything goes wrong with it under other filesystems,
1453 * mmap will fail.
1455 * Do not truncate the non-empty backend file to avoid corrupting
1456 * the existing data in the file. Disabling shrinking is not
1457 * enough. For example, the current vNVDIMM implementation stores
1458 * the guest NVDIMM labels at the end of the backend file. If the
1459 * backend file is later extended, QEMU will not be able to find
1460 * those labels. Therefore, extending the non-empty backend file
1461 * is disabled as well.
1463 if (!file_size && ftruncate(fd, memory)) {
1464 perror("ftruncate");
1467 area = qemu_ram_mmap(fd, memory, block->mr->align,
1468 block->flags & RAM_SHARED);
1469 if (area == MAP_FAILED) {
1470 error_setg_errno(errp, errno,
1471 "unable to map backing store for guest RAM");
1472 goto error;
1475 if (mem_prealloc) {
1476 os_mem_prealloc(fd, area, memory, smp_cpus, errp);
1477 if (errp && *errp) {
1478 goto error;
1482 block->fd = fd;
1483 return area;
1485 error:
1486 if (area != MAP_FAILED) {
1487 qemu_ram_munmap(area, memory);
1489 if (unlink_on_error) {
1490 unlink(path);
1492 if (fd != -1) {
1493 close(fd);
1495 return NULL;
1497 #endif
1499 /* Called with the ramlist lock held. */
1500 static ram_addr_t find_ram_offset(ram_addr_t size)
1502 RAMBlock *block, *next_block;
1503 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1505 assert(size != 0); /* it would hand out same offset multiple times */
1507 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1508 return 0;
1511 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1512 ram_addr_t end, next = RAM_ADDR_MAX;
1514 end = block->offset + block->max_length;
1516 QLIST_FOREACH_RCU(next_block, &ram_list.blocks, next) {
1517 if (next_block->offset >= end) {
1518 next = MIN(next, next_block->offset);
1521 if (next - end >= size && next - end < mingap) {
1522 offset = end;
1523 mingap = next - end;
1527 if (offset == RAM_ADDR_MAX) {
1528 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1529 (uint64_t)size);
1530 abort();
1533 return offset;
1536 ram_addr_t last_ram_offset(void)
1538 RAMBlock *block;
1539 ram_addr_t last = 0;
1541 rcu_read_lock();
1542 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1543 last = MAX(last, block->offset + block->max_length);
1545 rcu_read_unlock();
1546 return last;
1549 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1551 int ret;
1553 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1554 if (!machine_dump_guest_core(current_machine)) {
1555 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1556 if (ret) {
1557 perror("qemu_madvise");
1558 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1559 "but dump_guest_core=off specified\n");
1564 const char *qemu_ram_get_idstr(RAMBlock *rb)
1566 return rb->idstr;
1569 bool qemu_ram_is_shared(RAMBlock *rb)
1571 return rb->flags & RAM_SHARED;
1574 /* Called with iothread lock held. */
1575 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1577 RAMBlock *block;
1579 assert(new_block);
1580 assert(!new_block->idstr[0]);
1582 if (dev) {
1583 char *id = qdev_get_dev_path(dev);
1584 if (id) {
1585 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1586 g_free(id);
1589 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1591 rcu_read_lock();
1592 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1593 if (block != new_block &&
1594 !strcmp(block->idstr, new_block->idstr)) {
1595 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1596 new_block->idstr);
1597 abort();
1600 rcu_read_unlock();
1603 /* Called with iothread lock held. */
1604 void qemu_ram_unset_idstr(RAMBlock *block)
1606 /* FIXME: arch_init.c assumes that this is not called throughout
1607 * migration. Ignore the problem since hot-unplug during migration
1608 * does not work anyway.
1610 if (block) {
1611 memset(block->idstr, 0, sizeof(block->idstr));
1615 size_t qemu_ram_pagesize(RAMBlock *rb)
1617 return rb->page_size;
1620 /* Returns the largest size of page in use */
1621 size_t qemu_ram_pagesize_largest(void)
1623 RAMBlock *block;
1624 size_t largest = 0;
1626 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1627 largest = MAX(largest, qemu_ram_pagesize(block));
1630 return largest;
1633 static int memory_try_enable_merging(void *addr, size_t len)
1635 if (!machine_mem_merge(current_machine)) {
1636 /* disabled by the user */
1637 return 0;
1640 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1643 /* Only legal before guest might have detected the memory size: e.g. on
1644 * incoming migration, or right after reset.
1646 * As memory core doesn't know how is memory accessed, it is up to
1647 * resize callback to update device state and/or add assertions to detect
1648 * misuse, if necessary.
1650 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1652 assert(block);
1654 newsize = HOST_PAGE_ALIGN(newsize);
1656 if (block->used_length == newsize) {
1657 return 0;
1660 if (!(block->flags & RAM_RESIZEABLE)) {
1661 error_setg_errno(errp, EINVAL,
1662 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1663 " in != 0x" RAM_ADDR_FMT, block->idstr,
1664 newsize, block->used_length);
1665 return -EINVAL;
1668 if (block->max_length < newsize) {
1669 error_setg_errno(errp, EINVAL,
1670 "Length too large: %s: 0x" RAM_ADDR_FMT
1671 " > 0x" RAM_ADDR_FMT, block->idstr,
1672 newsize, block->max_length);
1673 return -EINVAL;
1676 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1677 block->used_length = newsize;
1678 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1679 DIRTY_CLIENTS_ALL);
1680 memory_region_set_size(block->mr, newsize);
1681 if (block->resized) {
1682 block->resized(block->idstr, newsize, block->host);
1684 return 0;
1687 /* Called with ram_list.mutex held */
1688 static void dirty_memory_extend(ram_addr_t old_ram_size,
1689 ram_addr_t new_ram_size)
1691 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1692 DIRTY_MEMORY_BLOCK_SIZE);
1693 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1694 DIRTY_MEMORY_BLOCK_SIZE);
1695 int i;
1697 /* Only need to extend if block count increased */
1698 if (new_num_blocks <= old_num_blocks) {
1699 return;
1702 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1703 DirtyMemoryBlocks *old_blocks;
1704 DirtyMemoryBlocks *new_blocks;
1705 int j;
1707 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
1708 new_blocks = g_malloc(sizeof(*new_blocks) +
1709 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1711 if (old_num_blocks) {
1712 memcpy(new_blocks->blocks, old_blocks->blocks,
1713 old_num_blocks * sizeof(old_blocks->blocks[0]));
1716 for (j = old_num_blocks; j < new_num_blocks; j++) {
1717 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1720 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1722 if (old_blocks) {
1723 g_free_rcu(old_blocks, rcu);
1728 static void ram_block_add(RAMBlock *new_block, Error **errp)
1730 RAMBlock *block;
1731 RAMBlock *last_block = NULL;
1732 ram_addr_t old_ram_size, new_ram_size;
1733 Error *err = NULL;
1735 old_ram_size = last_ram_offset() >> TARGET_PAGE_BITS;
1737 qemu_mutex_lock_ramlist();
1738 new_block->offset = find_ram_offset(new_block->max_length);
1740 if (!new_block->host) {
1741 if (xen_enabled()) {
1742 xen_ram_alloc(new_block->offset, new_block->max_length,
1743 new_block->mr, &err);
1744 if (err) {
1745 error_propagate(errp, err);
1746 qemu_mutex_unlock_ramlist();
1747 return;
1749 } else {
1750 new_block->host = phys_mem_alloc(new_block->max_length,
1751 &new_block->mr->align);
1752 if (!new_block->host) {
1753 error_setg_errno(errp, errno,
1754 "cannot set up guest memory '%s'",
1755 memory_region_name(new_block->mr));
1756 qemu_mutex_unlock_ramlist();
1757 return;
1759 memory_try_enable_merging(new_block->host, new_block->max_length);
1763 new_ram_size = MAX(old_ram_size,
1764 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1765 if (new_ram_size > old_ram_size) {
1766 migration_bitmap_extend(old_ram_size, new_ram_size);
1767 dirty_memory_extend(old_ram_size, new_ram_size);
1769 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1770 * QLIST (which has an RCU-friendly variant) does not have insertion at
1771 * tail, so save the last element in last_block.
1773 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1774 last_block = block;
1775 if (block->max_length < new_block->max_length) {
1776 break;
1779 if (block) {
1780 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1781 } else if (last_block) {
1782 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
1783 } else { /* list is empty */
1784 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1786 ram_list.mru_block = NULL;
1788 /* Write list before version */
1789 smp_wmb();
1790 ram_list.version++;
1791 qemu_mutex_unlock_ramlist();
1793 cpu_physical_memory_set_dirty_range(new_block->offset,
1794 new_block->used_length,
1795 DIRTY_CLIENTS_ALL);
1797 if (new_block->host) {
1798 qemu_ram_setup_dump(new_block->host, new_block->max_length);
1799 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
1800 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
1801 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
1802 ram_block_notify_add(new_block->host, new_block->max_length);
1806 #ifdef __linux__
1807 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
1808 bool share, const char *mem_path,
1809 Error **errp)
1811 RAMBlock *new_block;
1812 Error *local_err = NULL;
1814 if (xen_enabled()) {
1815 error_setg(errp, "-mem-path not supported with Xen");
1816 return NULL;
1819 if (phys_mem_alloc != qemu_anon_ram_alloc) {
1821 * file_ram_alloc() needs to allocate just like
1822 * phys_mem_alloc, but we haven't bothered to provide
1823 * a hook there.
1825 error_setg(errp,
1826 "-mem-path not supported with this accelerator");
1827 return NULL;
1830 size = HOST_PAGE_ALIGN(size);
1831 new_block = g_malloc0(sizeof(*new_block));
1832 new_block->mr = mr;
1833 new_block->used_length = size;
1834 new_block->max_length = size;
1835 new_block->flags = share ? RAM_SHARED : 0;
1836 new_block->host = file_ram_alloc(new_block, size,
1837 mem_path, errp);
1838 if (!new_block->host) {
1839 g_free(new_block);
1840 return NULL;
1843 ram_block_add(new_block, &local_err);
1844 if (local_err) {
1845 g_free(new_block);
1846 error_propagate(errp, local_err);
1847 return NULL;
1849 return new_block;
1851 #endif
1853 static
1854 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
1855 void (*resized)(const char*,
1856 uint64_t length,
1857 void *host),
1858 void *host, bool resizeable,
1859 MemoryRegion *mr, Error **errp)
1861 RAMBlock *new_block;
1862 Error *local_err = NULL;
1864 size = HOST_PAGE_ALIGN(size);
1865 max_size = HOST_PAGE_ALIGN(max_size);
1866 new_block = g_malloc0(sizeof(*new_block));
1867 new_block->mr = mr;
1868 new_block->resized = resized;
1869 new_block->used_length = size;
1870 new_block->max_length = max_size;
1871 assert(max_size >= size);
1872 new_block->fd = -1;
1873 new_block->page_size = getpagesize();
1874 new_block->host = host;
1875 if (host) {
1876 new_block->flags |= RAM_PREALLOC;
1878 if (resizeable) {
1879 new_block->flags |= RAM_RESIZEABLE;
1881 ram_block_add(new_block, &local_err);
1882 if (local_err) {
1883 g_free(new_block);
1884 error_propagate(errp, local_err);
1885 return NULL;
1887 return new_block;
1890 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
1891 MemoryRegion *mr, Error **errp)
1893 return qemu_ram_alloc_internal(size, size, NULL, host, false, mr, errp);
1896 RAMBlock *qemu_ram_alloc(ram_addr_t size, MemoryRegion *mr, Error **errp)
1898 return qemu_ram_alloc_internal(size, size, NULL, NULL, false, mr, errp);
1901 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
1902 void (*resized)(const char*,
1903 uint64_t length,
1904 void *host),
1905 MemoryRegion *mr, Error **errp)
1907 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true, mr, errp);
1910 static void reclaim_ramblock(RAMBlock *block)
1912 if (block->flags & RAM_PREALLOC) {
1914 } else if (xen_enabled()) {
1915 xen_invalidate_map_cache_entry(block->host);
1916 #ifndef _WIN32
1917 } else if (block->fd >= 0) {
1918 qemu_ram_munmap(block->host, block->max_length);
1919 close(block->fd);
1920 #endif
1921 } else {
1922 qemu_anon_ram_free(block->host, block->max_length);
1924 g_free(block);
1927 void qemu_ram_free(RAMBlock *block)
1929 if (!block) {
1930 return;
1933 if (block->host) {
1934 ram_block_notify_remove(block->host, block->max_length);
1937 qemu_mutex_lock_ramlist();
1938 QLIST_REMOVE_RCU(block, next);
1939 ram_list.mru_block = NULL;
1940 /* Write list before version */
1941 smp_wmb();
1942 ram_list.version++;
1943 call_rcu(block, reclaim_ramblock, rcu);
1944 qemu_mutex_unlock_ramlist();
1947 #ifndef _WIN32
1948 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
1950 RAMBlock *block;
1951 ram_addr_t offset;
1952 int flags;
1953 void *area, *vaddr;
1955 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1956 offset = addr - block->offset;
1957 if (offset < block->max_length) {
1958 vaddr = ramblock_ptr(block, offset);
1959 if (block->flags & RAM_PREALLOC) {
1961 } else if (xen_enabled()) {
1962 abort();
1963 } else {
1964 flags = MAP_FIXED;
1965 if (block->fd >= 0) {
1966 flags |= (block->flags & RAM_SHARED ?
1967 MAP_SHARED : MAP_PRIVATE);
1968 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
1969 flags, block->fd, offset);
1970 } else {
1972 * Remap needs to match alloc. Accelerators that
1973 * set phys_mem_alloc never remap. If they did,
1974 * we'd need a remap hook here.
1976 assert(phys_mem_alloc == qemu_anon_ram_alloc);
1978 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
1979 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
1980 flags, -1, 0);
1982 if (area != vaddr) {
1983 fprintf(stderr, "Could not remap addr: "
1984 RAM_ADDR_FMT "@" RAM_ADDR_FMT "\n",
1985 length, addr);
1986 exit(1);
1988 memory_try_enable_merging(vaddr, length);
1989 qemu_ram_setup_dump(vaddr, length);
1994 #endif /* !_WIN32 */
1996 /* Return a host pointer to ram allocated with qemu_ram_alloc.
1997 * This should not be used for general purpose DMA. Use address_space_map
1998 * or address_space_rw instead. For local memory (e.g. video ram) that the
1999 * device owns, use memory_region_get_ram_ptr.
2001 * Called within RCU critical section.
2003 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2005 RAMBlock *block = ram_block;
2007 if (block == NULL) {
2008 block = qemu_get_ram_block(addr);
2009 addr -= block->offset;
2012 if (xen_enabled() && block->host == NULL) {
2013 /* We need to check if the requested address is in the RAM
2014 * because we don't want to map the entire memory in QEMU.
2015 * In that case just map until the end of the page.
2017 if (block->offset == 0) {
2018 return xen_map_cache(addr, 0, 0);
2021 block->host = xen_map_cache(block->offset, block->max_length, 1);
2023 return ramblock_ptr(block, addr);
2026 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2027 * but takes a size argument.
2029 * Called within RCU critical section.
2031 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2032 hwaddr *size)
2034 RAMBlock *block = ram_block;
2035 if (*size == 0) {
2036 return NULL;
2039 if (block == NULL) {
2040 block = qemu_get_ram_block(addr);
2041 addr -= block->offset;
2043 *size = MIN(*size, block->max_length - addr);
2045 if (xen_enabled() && block->host == NULL) {
2046 /* We need to check if the requested address is in the RAM
2047 * because we don't want to map the entire memory in QEMU.
2048 * In that case just map the requested area.
2050 if (block->offset == 0) {
2051 return xen_map_cache(addr, *size, 1);
2054 block->host = xen_map_cache(block->offset, block->max_length, 1);
2057 return ramblock_ptr(block, addr);
2061 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2062 * in that RAMBlock.
2064 * ptr: Host pointer to look up
2065 * round_offset: If true round the result offset down to a page boundary
2066 * *ram_addr: set to result ram_addr
2067 * *offset: set to result offset within the RAMBlock
2069 * Returns: RAMBlock (or NULL if not found)
2071 * By the time this function returns, the returned pointer is not protected
2072 * by RCU anymore. If the caller is not within an RCU critical section and
2073 * does not hold the iothread lock, it must have other means of protecting the
2074 * pointer, such as a reference to the region that includes the incoming
2075 * ram_addr_t.
2077 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2078 ram_addr_t *offset)
2080 RAMBlock *block;
2081 uint8_t *host = ptr;
2083 if (xen_enabled()) {
2084 ram_addr_t ram_addr;
2085 rcu_read_lock();
2086 ram_addr = xen_ram_addr_from_mapcache(ptr);
2087 block = qemu_get_ram_block(ram_addr);
2088 if (block) {
2089 *offset = ram_addr - block->offset;
2091 rcu_read_unlock();
2092 return block;
2095 rcu_read_lock();
2096 block = atomic_rcu_read(&ram_list.mru_block);
2097 if (block && block->host && host - block->host < block->max_length) {
2098 goto found;
2101 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
2102 /* This case append when the block is not mapped. */
2103 if (block->host == NULL) {
2104 continue;
2106 if (host - block->host < block->max_length) {
2107 goto found;
2111 rcu_read_unlock();
2112 return NULL;
2114 found:
2115 *offset = (host - block->host);
2116 if (round_offset) {
2117 *offset &= TARGET_PAGE_MASK;
2119 rcu_read_unlock();
2120 return block;
2124 * Finds the named RAMBlock
2126 * name: The name of RAMBlock to find
2128 * Returns: RAMBlock (or NULL if not found)
2130 RAMBlock *qemu_ram_block_by_name(const char *name)
2132 RAMBlock *block;
2134 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
2135 if (!strcmp(name, block->idstr)) {
2136 return block;
2140 return NULL;
2143 /* Some of the softmmu routines need to translate from a host pointer
2144 (typically a TLB entry) back to a ram offset. */
2145 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2147 RAMBlock *block;
2148 ram_addr_t offset;
2150 block = qemu_ram_block_from_host(ptr, false, &offset);
2151 if (!block) {
2152 return RAM_ADDR_INVALID;
2155 return block->offset + offset;
2158 /* Called within RCU critical section. */
2159 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2160 uint64_t val, unsigned size)
2162 bool locked = false;
2164 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
2165 locked = true;
2166 tb_lock();
2167 tb_invalidate_phys_page_fast(ram_addr, size);
2169 switch (size) {
2170 case 1:
2171 stb_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2172 break;
2173 case 2:
2174 stw_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2175 break;
2176 case 4:
2177 stl_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2178 break;
2179 default:
2180 abort();
2183 if (locked) {
2184 tb_unlock();
2187 /* Set both VGA and migration bits for simplicity and to remove
2188 * the notdirty callback faster.
2190 cpu_physical_memory_set_dirty_range(ram_addr, size,
2191 DIRTY_CLIENTS_NOCODE);
2192 /* we remove the notdirty callback only if the code has been
2193 flushed */
2194 if (!cpu_physical_memory_is_clean(ram_addr)) {
2195 tlb_set_dirty(current_cpu, current_cpu->mem_io_vaddr);
2199 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
2200 unsigned size, bool is_write)
2202 return is_write;
2205 static const MemoryRegionOps notdirty_mem_ops = {
2206 .write = notdirty_mem_write,
2207 .valid.accepts = notdirty_mem_accepts,
2208 .endianness = DEVICE_NATIVE_ENDIAN,
2211 /* Generate a debug exception if a watchpoint has been hit. */
2212 static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
2214 CPUState *cpu = current_cpu;
2215 CPUClass *cc = CPU_GET_CLASS(cpu);
2216 CPUArchState *env = cpu->env_ptr;
2217 target_ulong pc, cs_base;
2218 target_ulong vaddr;
2219 CPUWatchpoint *wp;
2220 uint32_t cpu_flags;
2222 if (cpu->watchpoint_hit) {
2223 /* We re-entered the check after replacing the TB. Now raise
2224 * the debug interrupt so that is will trigger after the
2225 * current instruction. */
2226 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2227 return;
2229 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
2230 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
2231 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2232 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2233 && (wp->flags & flags)) {
2234 if (flags == BP_MEM_READ) {
2235 wp->flags |= BP_WATCHPOINT_HIT_READ;
2236 } else {
2237 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2239 wp->hitaddr = vaddr;
2240 wp->hitattrs = attrs;
2241 if (!cpu->watchpoint_hit) {
2242 if (wp->flags & BP_CPU &&
2243 !cc->debug_check_watchpoint(cpu, wp)) {
2244 wp->flags &= ~BP_WATCHPOINT_HIT;
2245 continue;
2247 cpu->watchpoint_hit = wp;
2249 /* Both tb_lock and iothread_mutex will be reset when
2250 * cpu_loop_exit or cpu_loop_exit_noexc longjmp
2251 * back into the cpu_exec main loop.
2253 tb_lock();
2254 tb_check_watchpoint(cpu);
2255 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2256 cpu->exception_index = EXCP_DEBUG;
2257 cpu_loop_exit(cpu);
2258 } else {
2259 cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags);
2260 tb_gen_code(cpu, pc, cs_base, cpu_flags, 1);
2261 cpu_loop_exit_noexc(cpu);
2264 } else {
2265 wp->flags &= ~BP_WATCHPOINT_HIT;
2270 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2271 so these check for a hit then pass through to the normal out-of-line
2272 phys routines. */
2273 static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2274 unsigned size, MemTxAttrs attrs)
2276 MemTxResult res;
2277 uint64_t data;
2278 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2279 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2281 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2282 switch (size) {
2283 case 1:
2284 data = address_space_ldub(as, addr, attrs, &res);
2285 break;
2286 case 2:
2287 data = address_space_lduw(as, addr, attrs, &res);
2288 break;
2289 case 4:
2290 data = address_space_ldl(as, addr, attrs, &res);
2291 break;
2292 default: abort();
2294 *pdata = data;
2295 return res;
2298 static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2299 uint64_t val, unsigned size,
2300 MemTxAttrs attrs)
2302 MemTxResult res;
2303 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2304 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2306 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2307 switch (size) {
2308 case 1:
2309 address_space_stb(as, addr, val, attrs, &res);
2310 break;
2311 case 2:
2312 address_space_stw(as, addr, val, attrs, &res);
2313 break;
2314 case 4:
2315 address_space_stl(as, addr, val, attrs, &res);
2316 break;
2317 default: abort();
2319 return res;
2322 static const MemoryRegionOps watch_mem_ops = {
2323 .read_with_attrs = watch_mem_read,
2324 .write_with_attrs = watch_mem_write,
2325 .endianness = DEVICE_NATIVE_ENDIAN,
2328 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2329 unsigned len, MemTxAttrs attrs)
2331 subpage_t *subpage = opaque;
2332 uint8_t buf[8];
2333 MemTxResult res;
2335 #if defined(DEBUG_SUBPAGE)
2336 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2337 subpage, len, addr);
2338 #endif
2339 res = address_space_read(subpage->as, addr + subpage->base,
2340 attrs, buf, len);
2341 if (res) {
2342 return res;
2344 switch (len) {
2345 case 1:
2346 *data = ldub_p(buf);
2347 return MEMTX_OK;
2348 case 2:
2349 *data = lduw_p(buf);
2350 return MEMTX_OK;
2351 case 4:
2352 *data = ldl_p(buf);
2353 return MEMTX_OK;
2354 case 8:
2355 *data = ldq_p(buf);
2356 return MEMTX_OK;
2357 default:
2358 abort();
2362 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2363 uint64_t value, unsigned len, MemTxAttrs attrs)
2365 subpage_t *subpage = opaque;
2366 uint8_t buf[8];
2368 #if defined(DEBUG_SUBPAGE)
2369 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2370 " value %"PRIx64"\n",
2371 __func__, subpage, len, addr, value);
2372 #endif
2373 switch (len) {
2374 case 1:
2375 stb_p(buf, value);
2376 break;
2377 case 2:
2378 stw_p(buf, value);
2379 break;
2380 case 4:
2381 stl_p(buf, value);
2382 break;
2383 case 8:
2384 stq_p(buf, value);
2385 break;
2386 default:
2387 abort();
2389 return address_space_write(subpage->as, addr + subpage->base,
2390 attrs, buf, len);
2393 static bool subpage_accepts(void *opaque, hwaddr addr,
2394 unsigned len, bool is_write)
2396 subpage_t *subpage = opaque;
2397 #if defined(DEBUG_SUBPAGE)
2398 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2399 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2400 #endif
2402 return address_space_access_valid(subpage->as, addr + subpage->base,
2403 len, is_write);
2406 static const MemoryRegionOps subpage_ops = {
2407 .read_with_attrs = subpage_read,
2408 .write_with_attrs = subpage_write,
2409 .impl.min_access_size = 1,
2410 .impl.max_access_size = 8,
2411 .valid.min_access_size = 1,
2412 .valid.max_access_size = 8,
2413 .valid.accepts = subpage_accepts,
2414 .endianness = DEVICE_NATIVE_ENDIAN,
2417 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
2418 uint16_t section)
2420 int idx, eidx;
2422 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2423 return -1;
2424 idx = SUBPAGE_IDX(start);
2425 eidx = SUBPAGE_IDX(end);
2426 #if defined(DEBUG_SUBPAGE)
2427 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2428 __func__, mmio, start, end, idx, eidx, section);
2429 #endif
2430 for (; idx <= eidx; idx++) {
2431 mmio->sub_section[idx] = section;
2434 return 0;
2437 static subpage_t *subpage_init(AddressSpace *as, hwaddr base)
2439 subpage_t *mmio;
2441 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2442 mmio->as = as;
2443 mmio->base = base;
2444 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2445 NULL, TARGET_PAGE_SIZE);
2446 mmio->iomem.subpage = true;
2447 #if defined(DEBUG_SUBPAGE)
2448 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2449 mmio, base, TARGET_PAGE_SIZE);
2450 #endif
2451 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
2453 return mmio;
2456 static uint16_t dummy_section(PhysPageMap *map, AddressSpace *as,
2457 MemoryRegion *mr)
2459 assert(as);
2460 MemoryRegionSection section = {
2461 .address_space = as,
2462 .mr = mr,
2463 .offset_within_address_space = 0,
2464 .offset_within_region = 0,
2465 .size = int128_2_64(),
2468 return phys_section_add(map, &section);
2471 MemoryRegion *iotlb_to_region(CPUState *cpu, hwaddr index, MemTxAttrs attrs)
2473 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2474 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2475 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
2476 MemoryRegionSection *sections = d->map.sections;
2478 return sections[index & ~TARGET_PAGE_MASK].mr;
2481 static void io_mem_init(void)
2483 memory_region_init_io(&io_mem_rom, NULL, &unassigned_mem_ops, NULL, NULL, UINT64_MAX);
2484 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2485 NULL, UINT64_MAX);
2487 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
2488 * which can be called without the iothread mutex.
2490 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
2491 NULL, UINT64_MAX);
2492 memory_region_clear_global_locking(&io_mem_notdirty);
2494 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
2495 NULL, UINT64_MAX);
2498 static void mem_begin(MemoryListener *listener)
2500 AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
2501 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2502 uint16_t n;
2504 n = dummy_section(&d->map, as, &io_mem_unassigned);
2505 assert(n == PHYS_SECTION_UNASSIGNED);
2506 n = dummy_section(&d->map, as, &io_mem_notdirty);
2507 assert(n == PHYS_SECTION_NOTDIRTY);
2508 n = dummy_section(&d->map, as, &io_mem_rom);
2509 assert(n == PHYS_SECTION_ROM);
2510 n = dummy_section(&d->map, as, &io_mem_watch);
2511 assert(n == PHYS_SECTION_WATCH);
2513 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2514 d->as = as;
2515 as->next_dispatch = d;
2518 static void address_space_dispatch_free(AddressSpaceDispatch *d)
2520 phys_sections_free(&d->map);
2521 g_free(d);
2524 static void mem_commit(MemoryListener *listener)
2526 AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
2527 AddressSpaceDispatch *cur = as->dispatch;
2528 AddressSpaceDispatch *next = as->next_dispatch;
2530 phys_page_compact_all(next, next->map.nodes_nb);
2532 atomic_rcu_set(&as->dispatch, next);
2533 if (cur) {
2534 call_rcu(cur, address_space_dispatch_free, rcu);
2538 static void tcg_commit(MemoryListener *listener)
2540 CPUAddressSpace *cpuas;
2541 AddressSpaceDispatch *d;
2543 /* since each CPU stores ram addresses in its TLB cache, we must
2544 reset the modified entries */
2545 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2546 cpu_reloading_memory_map();
2547 /* The CPU and TLB are protected by the iothread lock.
2548 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2549 * may have split the RCU critical section.
2551 d = atomic_rcu_read(&cpuas->as->dispatch);
2552 atomic_rcu_set(&cpuas->memory_dispatch, d);
2553 tlb_flush(cpuas->cpu);
2556 void address_space_init_dispatch(AddressSpace *as)
2558 as->dispatch = NULL;
2559 as->dispatch_listener = (MemoryListener) {
2560 .begin = mem_begin,
2561 .commit = mem_commit,
2562 .region_add = mem_add,
2563 .region_nop = mem_add,
2564 .priority = 0,
2566 memory_listener_register(&as->dispatch_listener, as);
2569 void address_space_unregister(AddressSpace *as)
2571 memory_listener_unregister(&as->dispatch_listener);
2574 void address_space_destroy_dispatch(AddressSpace *as)
2576 AddressSpaceDispatch *d = as->dispatch;
2578 atomic_rcu_set(&as->dispatch, NULL);
2579 if (d) {
2580 call_rcu(d, address_space_dispatch_free, rcu);
2584 static void memory_map_init(void)
2586 system_memory = g_malloc(sizeof(*system_memory));
2588 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2589 address_space_init(&address_space_memory, system_memory, "memory");
2591 system_io = g_malloc(sizeof(*system_io));
2592 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2593 65536);
2594 address_space_init(&address_space_io, system_io, "I/O");
2597 MemoryRegion *get_system_memory(void)
2599 return system_memory;
2602 MemoryRegion *get_system_io(void)
2604 return system_io;
2607 #endif /* !defined(CONFIG_USER_ONLY) */
2609 /* physical memory access (slow version, mainly for debug) */
2610 #if defined(CONFIG_USER_ONLY)
2611 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
2612 uint8_t *buf, int len, int is_write)
2614 int l, flags;
2615 target_ulong page;
2616 void * p;
2618 while (len > 0) {
2619 page = addr & TARGET_PAGE_MASK;
2620 l = (page + TARGET_PAGE_SIZE) - addr;
2621 if (l > len)
2622 l = len;
2623 flags = page_get_flags(page);
2624 if (!(flags & PAGE_VALID))
2625 return -1;
2626 if (is_write) {
2627 if (!(flags & PAGE_WRITE))
2628 return -1;
2629 /* XXX: this code should not depend on lock_user */
2630 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
2631 return -1;
2632 memcpy(p, buf, l);
2633 unlock_user(p, addr, l);
2634 } else {
2635 if (!(flags & PAGE_READ))
2636 return -1;
2637 /* XXX: this code should not depend on lock_user */
2638 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
2639 return -1;
2640 memcpy(buf, p, l);
2641 unlock_user(p, addr, 0);
2643 len -= l;
2644 buf += l;
2645 addr += l;
2647 return 0;
2650 #else
2652 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2653 hwaddr length)
2655 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2656 addr += memory_region_get_ram_addr(mr);
2658 /* No early return if dirty_log_mask is or becomes 0, because
2659 * cpu_physical_memory_set_dirty_range will still call
2660 * xen_modified_memory.
2662 if (dirty_log_mask) {
2663 dirty_log_mask =
2664 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2666 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2667 tb_lock();
2668 tb_invalidate_phys_range(addr, addr + length);
2669 tb_unlock();
2670 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2672 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2675 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2677 unsigned access_size_max = mr->ops->valid.max_access_size;
2679 /* Regions are assumed to support 1-4 byte accesses unless
2680 otherwise specified. */
2681 if (access_size_max == 0) {
2682 access_size_max = 4;
2685 /* Bound the maximum access by the alignment of the address. */
2686 if (!mr->ops->impl.unaligned) {
2687 unsigned align_size_max = addr & -addr;
2688 if (align_size_max != 0 && align_size_max < access_size_max) {
2689 access_size_max = align_size_max;
2693 /* Don't attempt accesses larger than the maximum. */
2694 if (l > access_size_max) {
2695 l = access_size_max;
2697 l = pow2floor(l);
2699 return l;
2702 static bool prepare_mmio_access(MemoryRegion *mr)
2704 bool unlocked = !qemu_mutex_iothread_locked();
2705 bool release_lock = false;
2707 if (unlocked && mr->global_locking) {
2708 qemu_mutex_lock_iothread();
2709 unlocked = false;
2710 release_lock = true;
2712 if (mr->flush_coalesced_mmio) {
2713 if (unlocked) {
2714 qemu_mutex_lock_iothread();
2716 qemu_flush_coalesced_mmio_buffer();
2717 if (unlocked) {
2718 qemu_mutex_unlock_iothread();
2722 return release_lock;
2725 /* Called within RCU critical section. */
2726 static MemTxResult address_space_write_continue(AddressSpace *as, hwaddr addr,
2727 MemTxAttrs attrs,
2728 const uint8_t *buf,
2729 int len, hwaddr addr1,
2730 hwaddr l, MemoryRegion *mr)
2732 uint8_t *ptr;
2733 uint64_t val;
2734 MemTxResult result = MEMTX_OK;
2735 bool release_lock = false;
2737 for (;;) {
2738 if (!memory_access_is_direct(mr, true)) {
2739 release_lock |= prepare_mmio_access(mr);
2740 l = memory_access_size(mr, l, addr1);
2741 /* XXX: could force current_cpu to NULL to avoid
2742 potential bugs */
2743 switch (l) {
2744 case 8:
2745 /* 64 bit write access */
2746 val = ldq_p(buf);
2747 result |= memory_region_dispatch_write(mr, addr1, val, 8,
2748 attrs);
2749 break;
2750 case 4:
2751 /* 32 bit write access */
2752 val = (uint32_t)ldl_p(buf);
2753 result |= memory_region_dispatch_write(mr, addr1, val, 4,
2754 attrs);
2755 break;
2756 case 2:
2757 /* 16 bit write access */
2758 val = lduw_p(buf);
2759 result |= memory_region_dispatch_write(mr, addr1, val, 2,
2760 attrs);
2761 break;
2762 case 1:
2763 /* 8 bit write access */
2764 val = ldub_p(buf);
2765 result |= memory_region_dispatch_write(mr, addr1, val, 1,
2766 attrs);
2767 break;
2768 default:
2769 abort();
2771 } else {
2772 /* RAM case */
2773 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2774 memcpy(ptr, buf, l);
2775 invalidate_and_set_dirty(mr, addr1, l);
2778 if (release_lock) {
2779 qemu_mutex_unlock_iothread();
2780 release_lock = false;
2783 len -= l;
2784 buf += l;
2785 addr += l;
2787 if (!len) {
2788 break;
2791 l = len;
2792 mr = address_space_translate(as, addr, &addr1, &l, true);
2795 return result;
2798 MemTxResult address_space_write(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2799 const uint8_t *buf, int len)
2801 hwaddr l;
2802 hwaddr addr1;
2803 MemoryRegion *mr;
2804 MemTxResult result = MEMTX_OK;
2806 if (len > 0) {
2807 rcu_read_lock();
2808 l = len;
2809 mr = address_space_translate(as, addr, &addr1, &l, true);
2810 result = address_space_write_continue(as, addr, attrs, buf, len,
2811 addr1, l, mr);
2812 rcu_read_unlock();
2815 return result;
2818 /* Called within RCU critical section. */
2819 MemTxResult address_space_read_continue(AddressSpace *as, hwaddr addr,
2820 MemTxAttrs attrs, uint8_t *buf,
2821 int len, hwaddr addr1, hwaddr l,
2822 MemoryRegion *mr)
2824 uint8_t *ptr;
2825 uint64_t val;
2826 MemTxResult result = MEMTX_OK;
2827 bool release_lock = false;
2829 for (;;) {
2830 if (!memory_access_is_direct(mr, false)) {
2831 /* I/O case */
2832 release_lock |= prepare_mmio_access(mr);
2833 l = memory_access_size(mr, l, addr1);
2834 switch (l) {
2835 case 8:
2836 /* 64 bit read access */
2837 result |= memory_region_dispatch_read(mr, addr1, &val, 8,
2838 attrs);
2839 stq_p(buf, val);
2840 break;
2841 case 4:
2842 /* 32 bit read access */
2843 result |= memory_region_dispatch_read(mr, addr1, &val, 4,
2844 attrs);
2845 stl_p(buf, val);
2846 break;
2847 case 2:
2848 /* 16 bit read access */
2849 result |= memory_region_dispatch_read(mr, addr1, &val, 2,
2850 attrs);
2851 stw_p(buf, val);
2852 break;
2853 case 1:
2854 /* 8 bit read access */
2855 result |= memory_region_dispatch_read(mr, addr1, &val, 1,
2856 attrs);
2857 stb_p(buf, val);
2858 break;
2859 default:
2860 abort();
2862 } else {
2863 /* RAM case */
2864 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2865 memcpy(buf, ptr, l);
2868 if (release_lock) {
2869 qemu_mutex_unlock_iothread();
2870 release_lock = false;
2873 len -= l;
2874 buf += l;
2875 addr += l;
2877 if (!len) {
2878 break;
2881 l = len;
2882 mr = address_space_translate(as, addr, &addr1, &l, false);
2885 return result;
2888 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2889 MemTxAttrs attrs, uint8_t *buf, int len)
2891 hwaddr l;
2892 hwaddr addr1;
2893 MemoryRegion *mr;
2894 MemTxResult result = MEMTX_OK;
2896 if (len > 0) {
2897 rcu_read_lock();
2898 l = len;
2899 mr = address_space_translate(as, addr, &addr1, &l, false);
2900 result = address_space_read_continue(as, addr, attrs, buf, len,
2901 addr1, l, mr);
2902 rcu_read_unlock();
2905 return result;
2908 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2909 uint8_t *buf, int len, bool is_write)
2911 if (is_write) {
2912 return address_space_write(as, addr, attrs, (uint8_t *)buf, len);
2913 } else {
2914 return address_space_read(as, addr, attrs, (uint8_t *)buf, len);
2918 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
2919 int len, int is_write)
2921 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
2922 buf, len, is_write);
2925 enum write_rom_type {
2926 WRITE_DATA,
2927 FLUSH_CACHE,
2930 static inline void cpu_physical_memory_write_rom_internal(AddressSpace *as,
2931 hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
2933 hwaddr l;
2934 uint8_t *ptr;
2935 hwaddr addr1;
2936 MemoryRegion *mr;
2938 rcu_read_lock();
2939 while (len > 0) {
2940 l = len;
2941 mr = address_space_translate(as, addr, &addr1, &l, true);
2943 if (!(memory_region_is_ram(mr) ||
2944 memory_region_is_romd(mr))) {
2945 l = memory_access_size(mr, l, addr1);
2946 } else {
2947 /* ROM/RAM case */
2948 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2949 switch (type) {
2950 case WRITE_DATA:
2951 memcpy(ptr, buf, l);
2952 invalidate_and_set_dirty(mr, addr1, l);
2953 break;
2954 case FLUSH_CACHE:
2955 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
2956 break;
2959 len -= l;
2960 buf += l;
2961 addr += l;
2963 rcu_read_unlock();
2966 /* used for ROM loading : can write in RAM and ROM */
2967 void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
2968 const uint8_t *buf, int len)
2970 cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
2973 void cpu_flush_icache_range(hwaddr start, int len)
2976 * This function should do the same thing as an icache flush that was
2977 * triggered from within the guest. For TCG we are always cache coherent,
2978 * so there is no need to flush anything. For KVM / Xen we need to flush
2979 * the host's instruction cache at least.
2981 if (tcg_enabled()) {
2982 return;
2985 cpu_physical_memory_write_rom_internal(&address_space_memory,
2986 start, NULL, len, FLUSH_CACHE);
2989 typedef struct {
2990 MemoryRegion *mr;
2991 void *buffer;
2992 hwaddr addr;
2993 hwaddr len;
2994 bool in_use;
2995 } BounceBuffer;
2997 static BounceBuffer bounce;
2999 typedef struct MapClient {
3000 QEMUBH *bh;
3001 QLIST_ENTRY(MapClient) link;
3002 } MapClient;
3004 QemuMutex map_client_list_lock;
3005 static QLIST_HEAD(map_client_list, MapClient) map_client_list
3006 = QLIST_HEAD_INITIALIZER(map_client_list);
3008 static void cpu_unregister_map_client_do(MapClient *client)
3010 QLIST_REMOVE(client, link);
3011 g_free(client);
3014 static void cpu_notify_map_clients_locked(void)
3016 MapClient *client;
3018 while (!QLIST_EMPTY(&map_client_list)) {
3019 client = QLIST_FIRST(&map_client_list);
3020 qemu_bh_schedule(client->bh);
3021 cpu_unregister_map_client_do(client);
3025 void cpu_register_map_client(QEMUBH *bh)
3027 MapClient *client = g_malloc(sizeof(*client));
3029 qemu_mutex_lock(&map_client_list_lock);
3030 client->bh = bh;
3031 QLIST_INSERT_HEAD(&map_client_list, client, link);
3032 if (!atomic_read(&bounce.in_use)) {
3033 cpu_notify_map_clients_locked();
3035 qemu_mutex_unlock(&map_client_list_lock);
3038 void cpu_exec_init_all(void)
3040 qemu_mutex_init(&ram_list.mutex);
3041 /* The data structures we set up here depend on knowing the page size,
3042 * so no more changes can be made after this point.
3043 * In an ideal world, nothing we did before we had finished the
3044 * machine setup would care about the target page size, and we could
3045 * do this much later, rather than requiring board models to state
3046 * up front what their requirements are.
3048 finalize_target_page_bits();
3049 io_mem_init();
3050 memory_map_init();
3051 qemu_mutex_init(&map_client_list_lock);
3054 void cpu_unregister_map_client(QEMUBH *bh)
3056 MapClient *client;
3058 qemu_mutex_lock(&map_client_list_lock);
3059 QLIST_FOREACH(client, &map_client_list, link) {
3060 if (client->bh == bh) {
3061 cpu_unregister_map_client_do(client);
3062 break;
3065 qemu_mutex_unlock(&map_client_list_lock);
3068 static void cpu_notify_map_clients(void)
3070 qemu_mutex_lock(&map_client_list_lock);
3071 cpu_notify_map_clients_locked();
3072 qemu_mutex_unlock(&map_client_list_lock);
3075 bool address_space_access_valid(AddressSpace *as, hwaddr addr, int len, bool is_write)
3077 MemoryRegion *mr;
3078 hwaddr l, xlat;
3080 rcu_read_lock();
3081 while (len > 0) {
3082 l = len;
3083 mr = address_space_translate(as, addr, &xlat, &l, is_write);
3084 if (!memory_access_is_direct(mr, is_write)) {
3085 l = memory_access_size(mr, l, addr);
3086 if (!memory_region_access_valid(mr, xlat, l, is_write)) {
3087 rcu_read_unlock();
3088 return false;
3092 len -= l;
3093 addr += l;
3095 rcu_read_unlock();
3096 return true;
3099 static hwaddr
3100 address_space_extend_translation(AddressSpace *as, hwaddr addr, hwaddr target_len,
3101 MemoryRegion *mr, hwaddr base, hwaddr len,
3102 bool is_write)
3104 hwaddr done = 0;
3105 hwaddr xlat;
3106 MemoryRegion *this_mr;
3108 for (;;) {
3109 target_len -= len;
3110 addr += len;
3111 done += len;
3112 if (target_len == 0) {
3113 return done;
3116 len = target_len;
3117 this_mr = address_space_translate(as, addr, &xlat, &len, is_write);
3118 if (this_mr != mr || xlat != base + done) {
3119 return done;
3124 /* Map a physical memory region into a host virtual address.
3125 * May map a subset of the requested range, given by and returned in *plen.
3126 * May return NULL if resources needed to perform the mapping are exhausted.
3127 * Use only for reads OR writes - not for read-modify-write operations.
3128 * Use cpu_register_map_client() to know when retrying the map operation is
3129 * likely to succeed.
3131 void *address_space_map(AddressSpace *as,
3132 hwaddr addr,
3133 hwaddr *plen,
3134 bool is_write)
3136 hwaddr len = *plen;
3137 hwaddr l, xlat;
3138 MemoryRegion *mr;
3139 void *ptr;
3141 if (len == 0) {
3142 return NULL;
3145 l = len;
3146 rcu_read_lock();
3147 mr = address_space_translate(as, addr, &xlat, &l, is_write);
3149 if (!memory_access_is_direct(mr, is_write)) {
3150 if (atomic_xchg(&bounce.in_use, true)) {
3151 rcu_read_unlock();
3152 return NULL;
3154 /* Avoid unbounded allocations */
3155 l = MIN(l, TARGET_PAGE_SIZE);
3156 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3157 bounce.addr = addr;
3158 bounce.len = l;
3160 memory_region_ref(mr);
3161 bounce.mr = mr;
3162 if (!is_write) {
3163 address_space_read(as, addr, MEMTXATTRS_UNSPECIFIED,
3164 bounce.buffer, l);
3167 rcu_read_unlock();
3168 *plen = l;
3169 return bounce.buffer;
3173 memory_region_ref(mr);
3174 *plen = address_space_extend_translation(as, addr, len, mr, xlat, l, is_write);
3175 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen);
3176 rcu_read_unlock();
3178 return ptr;
3181 /* Unmaps a memory region previously mapped by address_space_map().
3182 * Will also mark the memory as dirty if is_write == 1. access_len gives
3183 * the amount of memory that was actually read or written by the caller.
3185 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3186 int is_write, hwaddr access_len)
3188 if (buffer != bounce.buffer) {
3189 MemoryRegion *mr;
3190 ram_addr_t addr1;
3192 mr = memory_region_from_host(buffer, &addr1);
3193 assert(mr != NULL);
3194 if (is_write) {
3195 invalidate_and_set_dirty(mr, addr1, access_len);
3197 if (xen_enabled()) {
3198 xen_invalidate_map_cache_entry(buffer);
3200 memory_region_unref(mr);
3201 return;
3203 if (is_write) {
3204 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3205 bounce.buffer, access_len);
3207 qemu_vfree(bounce.buffer);
3208 bounce.buffer = NULL;
3209 memory_region_unref(bounce.mr);
3210 atomic_mb_set(&bounce.in_use, false);
3211 cpu_notify_map_clients();
3214 void *cpu_physical_memory_map(hwaddr addr,
3215 hwaddr *plen,
3216 int is_write)
3218 return address_space_map(&address_space_memory, addr, plen, is_write);
3221 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3222 int is_write, hwaddr access_len)
3224 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3227 #define ARG1_DECL AddressSpace *as
3228 #define ARG1 as
3229 #define SUFFIX
3230 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3231 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3232 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3233 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3234 #define RCU_READ_LOCK(...) rcu_read_lock()
3235 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3236 #include "memory_ldst.inc.c"
3238 int64_t address_space_cache_init(MemoryRegionCache *cache,
3239 AddressSpace *as,
3240 hwaddr addr,
3241 hwaddr len,
3242 bool is_write)
3244 cache->len = len;
3245 cache->as = as;
3246 cache->xlat = addr;
3247 return len;
3250 void address_space_cache_invalidate(MemoryRegionCache *cache,
3251 hwaddr addr,
3252 hwaddr access_len)
3256 void address_space_cache_destroy(MemoryRegionCache *cache)
3258 cache->as = NULL;
3261 #define ARG1_DECL MemoryRegionCache *cache
3262 #define ARG1 cache
3263 #define SUFFIX _cached
3264 #define TRANSLATE(addr, ...) \
3265 address_space_translate(cache->as, cache->xlat + (addr), __VA_ARGS__)
3266 #define IS_DIRECT(mr, is_write) true
3267 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3268 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3269 #define RCU_READ_LOCK() rcu_read_lock()
3270 #define RCU_READ_UNLOCK() rcu_read_unlock()
3271 #include "memory_ldst.inc.c"
3273 /* virtual memory access for debug (includes writing to ROM) */
3274 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3275 uint8_t *buf, int len, int is_write)
3277 int l;
3278 hwaddr phys_addr;
3279 target_ulong page;
3281 cpu_synchronize_state(cpu);
3282 while (len > 0) {
3283 int asidx;
3284 MemTxAttrs attrs;
3286 page = addr & TARGET_PAGE_MASK;
3287 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3288 asidx = cpu_asidx_from_attrs(cpu, attrs);
3289 /* if no physical page mapped, return an error */
3290 if (phys_addr == -1)
3291 return -1;
3292 l = (page + TARGET_PAGE_SIZE) - addr;
3293 if (l > len)
3294 l = len;
3295 phys_addr += (addr & ~TARGET_PAGE_MASK);
3296 if (is_write) {
3297 cpu_physical_memory_write_rom(cpu->cpu_ases[asidx].as,
3298 phys_addr, buf, l);
3299 } else {
3300 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3301 MEMTXATTRS_UNSPECIFIED,
3302 buf, l, 0);
3304 len -= l;
3305 buf += l;
3306 addr += l;
3308 return 0;
3312 * Allows code that needs to deal with migration bitmaps etc to still be built
3313 * target independent.
3315 size_t qemu_target_page_bits(void)
3317 return TARGET_PAGE_BITS;
3320 #endif
3323 * A helper function for the _utterly broken_ virtio device model to find out if
3324 * it's running on a big endian machine. Don't do this at home kids!
3326 bool target_words_bigendian(void);
3327 bool target_words_bigendian(void)
3329 #if defined(TARGET_WORDS_BIGENDIAN)
3330 return true;
3331 #else
3332 return false;
3333 #endif
3336 #ifndef CONFIG_USER_ONLY
3337 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3339 MemoryRegion*mr;
3340 hwaddr l = 1;
3341 bool res;
3343 rcu_read_lock();
3344 mr = address_space_translate(&address_space_memory,
3345 phys_addr, &phys_addr, &l, false);
3347 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3348 rcu_read_unlock();
3349 return res;
3352 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3354 RAMBlock *block;
3355 int ret = 0;
3357 rcu_read_lock();
3358 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
3359 ret = func(block->idstr, block->host, block->offset,
3360 block->used_length, opaque);
3361 if (ret) {
3362 break;
3365 rcu_read_unlock();
3366 return ret;
3370 * Unmap pages of memory from start to start+length such that
3371 * they a) read as 0, b) Trigger whatever fault mechanism
3372 * the OS provides for postcopy.
3373 * The pages must be unmapped by the end of the function.
3374 * Returns: 0 on success, none-0 on failure
3377 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3379 int ret = -1;
3381 uint8_t *host_startaddr = rb->host + start;
3383 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
3384 error_report("ram_block_discard_range: Unaligned start address: %p",
3385 host_startaddr);
3386 goto err;
3389 if ((start + length) <= rb->used_length) {
3390 uint8_t *host_endaddr = host_startaddr + length;
3391 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
3392 error_report("ram_block_discard_range: Unaligned end address: %p",
3393 host_endaddr);
3394 goto err;
3397 errno = ENOTSUP; /* If we are missing MADVISE etc */
3399 if (rb->page_size == qemu_host_page_size) {
3400 #if defined(CONFIG_MADVISE)
3401 /* Note: We need the madvise MADV_DONTNEED behaviour of definitely
3402 * freeing the page.
3404 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3405 #endif
3406 } else {
3407 /* Huge page case - unfortunately it can't do DONTNEED, but
3408 * it can do the equivalent by FALLOC_FL_PUNCH_HOLE in the
3409 * huge page file.
3411 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3412 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3413 start, length);
3414 #endif
3416 if (ret) {
3417 ret = -errno;
3418 error_report("ram_block_discard_range: Failed to discard range "
3419 "%s:%" PRIx64 " +%zx (%d)",
3420 rb->idstr, start, length, ret);
3422 } else {
3423 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3424 "/%zx/" RAM_ADDR_FMT")",
3425 rb->idstr, start, length, rb->used_length);
3428 err:
3429 return ret;
3432 #endif