exec: abstract address_space_do_translate()
[qemu/ar7.git] / exec.c
blobf942eb2bd1b704e3c637e374d546ca09f4dbbf4e
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 struct DirtyBitmapSnapshot {
227 ram_addr_t start;
228 ram_addr_t end;
229 unsigned long dirty[];
232 #endif
234 #if !defined(CONFIG_USER_ONLY)
236 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
238 static unsigned alloc_hint = 16;
239 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
240 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, alloc_hint);
241 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, map->nodes_nb + nodes);
242 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
243 alloc_hint = map->nodes_nb_alloc;
247 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
249 unsigned i;
250 uint32_t ret;
251 PhysPageEntry e;
252 PhysPageEntry *p;
254 ret = map->nodes_nb++;
255 p = map->nodes[ret];
256 assert(ret != PHYS_MAP_NODE_NIL);
257 assert(ret != map->nodes_nb_alloc);
259 e.skip = leaf ? 0 : 1;
260 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
261 for (i = 0; i < P_L2_SIZE; ++i) {
262 memcpy(&p[i], &e, sizeof(e));
264 return ret;
267 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
268 hwaddr *index, hwaddr *nb, uint16_t leaf,
269 int level)
271 PhysPageEntry *p;
272 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
274 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
275 lp->ptr = phys_map_node_alloc(map, level == 0);
277 p = map->nodes[lp->ptr];
278 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
280 while (*nb && lp < &p[P_L2_SIZE]) {
281 if ((*index & (step - 1)) == 0 && *nb >= step) {
282 lp->skip = 0;
283 lp->ptr = leaf;
284 *index += step;
285 *nb -= step;
286 } else {
287 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
289 ++lp;
293 static void phys_page_set(AddressSpaceDispatch *d,
294 hwaddr index, hwaddr nb,
295 uint16_t leaf)
297 /* Wildly overreserve - it doesn't matter much. */
298 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
300 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
303 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
304 * and update our entry so we can skip it and go directly to the destination.
306 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
308 unsigned valid_ptr = P_L2_SIZE;
309 int valid = 0;
310 PhysPageEntry *p;
311 int i;
313 if (lp->ptr == PHYS_MAP_NODE_NIL) {
314 return;
317 p = nodes[lp->ptr];
318 for (i = 0; i < P_L2_SIZE; i++) {
319 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
320 continue;
323 valid_ptr = i;
324 valid++;
325 if (p[i].skip) {
326 phys_page_compact(&p[i], nodes);
330 /* We can only compress if there's only one child. */
331 if (valid != 1) {
332 return;
335 assert(valid_ptr < P_L2_SIZE);
337 /* Don't compress if it won't fit in the # of bits we have. */
338 if (lp->skip + p[valid_ptr].skip >= (1 << 3)) {
339 return;
342 lp->ptr = p[valid_ptr].ptr;
343 if (!p[valid_ptr].skip) {
344 /* If our only child is a leaf, make this a leaf. */
345 /* By design, we should have made this node a leaf to begin with so we
346 * should never reach here.
347 * But since it's so simple to handle this, let's do it just in case we
348 * change this rule.
350 lp->skip = 0;
351 } else {
352 lp->skip += p[valid_ptr].skip;
356 static void phys_page_compact_all(AddressSpaceDispatch *d, int nodes_nb)
358 if (d->phys_map.skip) {
359 phys_page_compact(&d->phys_map, d->map.nodes);
363 static inline bool section_covers_addr(const MemoryRegionSection *section,
364 hwaddr addr)
366 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
367 * the section must cover the entire address space.
369 return int128_gethi(section->size) ||
370 range_covers_byte(section->offset_within_address_space,
371 int128_getlo(section->size), addr);
374 static MemoryRegionSection *phys_page_find(PhysPageEntry lp, hwaddr addr,
375 Node *nodes, MemoryRegionSection *sections)
377 PhysPageEntry *p;
378 hwaddr index = addr >> TARGET_PAGE_BITS;
379 int i;
381 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
382 if (lp.ptr == PHYS_MAP_NODE_NIL) {
383 return &sections[PHYS_SECTION_UNASSIGNED];
385 p = nodes[lp.ptr];
386 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
389 if (section_covers_addr(&sections[lp.ptr], addr)) {
390 return &sections[lp.ptr];
391 } else {
392 return &sections[PHYS_SECTION_UNASSIGNED];
396 bool memory_region_is_unassigned(MemoryRegion *mr)
398 return mr != &io_mem_rom && mr != &io_mem_notdirty && !mr->rom_device
399 && mr != &io_mem_watch;
402 /* Called from RCU critical section */
403 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
404 hwaddr addr,
405 bool resolve_subpage)
407 MemoryRegionSection *section = atomic_read(&d->mru_section);
408 subpage_t *subpage;
409 bool update;
411 if (section && section != &d->map.sections[PHYS_SECTION_UNASSIGNED] &&
412 section_covers_addr(section, addr)) {
413 update = false;
414 } else {
415 section = phys_page_find(d->phys_map, addr, d->map.nodes,
416 d->map.sections);
417 update = true;
419 if (resolve_subpage && section->mr->subpage) {
420 subpage = container_of(section->mr, subpage_t, iomem);
421 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
423 if (update) {
424 atomic_set(&d->mru_section, section);
426 return section;
429 /* Called from RCU critical section */
430 static MemoryRegionSection *
431 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
432 hwaddr *plen, bool resolve_subpage)
434 MemoryRegionSection *section;
435 MemoryRegion *mr;
436 Int128 diff;
438 section = address_space_lookup_region(d, addr, resolve_subpage);
439 /* Compute offset within MemoryRegionSection */
440 addr -= section->offset_within_address_space;
442 /* Compute offset within MemoryRegion */
443 *xlat = addr + section->offset_within_region;
445 mr = section->mr;
447 /* MMIO registers can be expected to perform full-width accesses based only
448 * on their address, without considering adjacent registers that could
449 * decode to completely different MemoryRegions. When such registers
450 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
451 * regions overlap wildly. For this reason we cannot clamp the accesses
452 * here.
454 * If the length is small (as is the case for address_space_ldl/stl),
455 * everything works fine. If the incoming length is large, however,
456 * the caller really has to do the clamping through memory_access_size.
458 if (memory_region_is_ram(mr)) {
459 diff = int128_sub(section->size, int128_make64(addr));
460 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
462 return section;
465 /* Called from RCU critical section */
466 static MemoryRegionSection address_space_do_translate(AddressSpace *as,
467 hwaddr addr,
468 hwaddr *xlat,
469 hwaddr *plen,
470 bool is_write,
471 bool is_mmio)
473 IOMMUTLBEntry iotlb;
474 MemoryRegionSection *section;
475 MemoryRegion *mr;
477 for (;;) {
478 AddressSpaceDispatch *d = atomic_rcu_read(&as->dispatch);
479 section = address_space_translate_internal(d, addr, &addr, plen, is_mmio);
480 mr = section->mr;
482 if (!mr->iommu_ops) {
483 break;
486 iotlb = mr->iommu_ops->translate(mr, addr, is_write);
487 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
488 | (addr & iotlb.addr_mask));
489 *plen = MIN(*plen, (addr | iotlb.addr_mask) - addr + 1);
490 if (!(iotlb.perm & (1 << is_write))) {
491 goto translate_fail;
494 as = iotlb.target_as;
497 *xlat = addr;
499 return *section;
501 translate_fail:
502 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
505 /* Called from RCU critical section */
506 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
507 bool is_write)
509 MemoryRegionSection section;
510 hwaddr xlat, plen;
512 /* Try to get maximum page mask during translation. */
513 plen = (hwaddr)-1;
515 /* This can never be MMIO. */
516 section = address_space_do_translate(as, addr, &xlat, &plen,
517 is_write, false);
519 /* Illegal translation */
520 if (section.mr == &io_mem_unassigned) {
521 goto iotlb_fail;
524 /* Convert memory region offset into address space offset */
525 xlat += section.offset_within_address_space -
526 section.offset_within_region;
528 if (plen == (hwaddr)-1) {
530 * We use default page size here. Logically it only happens
531 * for identity mappings.
533 plen = TARGET_PAGE_SIZE;
536 /* Convert to address mask */
537 plen -= 1;
539 return (IOMMUTLBEntry) {
540 .target_as = section.address_space,
541 .iova = addr & ~plen,
542 .translated_addr = xlat & ~plen,
543 .addr_mask = plen,
544 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
545 .perm = IOMMU_RW,
548 iotlb_fail:
549 return (IOMMUTLBEntry) {0};
552 /* Called from RCU critical section */
553 MemoryRegion *address_space_translate(AddressSpace *as, hwaddr addr,
554 hwaddr *xlat, hwaddr *plen,
555 bool is_write)
557 MemoryRegion *mr;
558 MemoryRegionSection section;
560 /* This can be MMIO, so setup MMIO bit. */
561 section = address_space_do_translate(as, addr, xlat, plen, is_write, true);
562 mr = section.mr;
564 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
565 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
566 *plen = MIN(page, *plen);
569 return mr;
572 /* Called from RCU critical section */
573 MemoryRegionSection *
574 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
575 hwaddr *xlat, hwaddr *plen)
577 MemoryRegionSection *section;
578 AddressSpaceDispatch *d = atomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
580 section = address_space_translate_internal(d, addr, xlat, plen, false);
582 assert(!section->mr->iommu_ops);
583 return section;
585 #endif
587 #if !defined(CONFIG_USER_ONLY)
589 static int cpu_common_post_load(void *opaque, int version_id)
591 CPUState *cpu = opaque;
593 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
594 version_id is increased. */
595 cpu->interrupt_request &= ~0x01;
596 tlb_flush(cpu);
598 return 0;
601 static int cpu_common_pre_load(void *opaque)
603 CPUState *cpu = opaque;
605 cpu->exception_index = -1;
607 return 0;
610 static bool cpu_common_exception_index_needed(void *opaque)
612 CPUState *cpu = opaque;
614 return tcg_enabled() && cpu->exception_index != -1;
617 static const VMStateDescription vmstate_cpu_common_exception_index = {
618 .name = "cpu_common/exception_index",
619 .version_id = 1,
620 .minimum_version_id = 1,
621 .needed = cpu_common_exception_index_needed,
622 .fields = (VMStateField[]) {
623 VMSTATE_INT32(exception_index, CPUState),
624 VMSTATE_END_OF_LIST()
628 static bool cpu_common_crash_occurred_needed(void *opaque)
630 CPUState *cpu = opaque;
632 return cpu->crash_occurred;
635 static const VMStateDescription vmstate_cpu_common_crash_occurred = {
636 .name = "cpu_common/crash_occurred",
637 .version_id = 1,
638 .minimum_version_id = 1,
639 .needed = cpu_common_crash_occurred_needed,
640 .fields = (VMStateField[]) {
641 VMSTATE_BOOL(crash_occurred, CPUState),
642 VMSTATE_END_OF_LIST()
646 const VMStateDescription vmstate_cpu_common = {
647 .name = "cpu_common",
648 .version_id = 1,
649 .minimum_version_id = 1,
650 .pre_load = cpu_common_pre_load,
651 .post_load = cpu_common_post_load,
652 .fields = (VMStateField[]) {
653 VMSTATE_UINT32(halted, CPUState),
654 VMSTATE_UINT32(interrupt_request, CPUState),
655 VMSTATE_END_OF_LIST()
657 .subsections = (const VMStateDescription*[]) {
658 &vmstate_cpu_common_exception_index,
659 &vmstate_cpu_common_crash_occurred,
660 NULL
664 #endif
666 CPUState *qemu_get_cpu(int index)
668 CPUState *cpu;
670 CPU_FOREACH(cpu) {
671 if (cpu->cpu_index == index) {
672 return cpu;
676 return NULL;
679 #if !defined(CONFIG_USER_ONLY)
680 void cpu_address_space_init(CPUState *cpu, AddressSpace *as, int asidx)
682 CPUAddressSpace *newas;
684 /* Target code should have set num_ases before calling us */
685 assert(asidx < cpu->num_ases);
687 if (asidx == 0) {
688 /* address space 0 gets the convenience alias */
689 cpu->as = as;
692 /* KVM cannot currently support multiple address spaces. */
693 assert(asidx == 0 || !kvm_enabled());
695 if (!cpu->cpu_ases) {
696 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
699 newas = &cpu->cpu_ases[asidx];
700 newas->cpu = cpu;
701 newas->as = as;
702 if (tcg_enabled()) {
703 newas->tcg_as_listener.commit = tcg_commit;
704 memory_listener_register(&newas->tcg_as_listener, as);
708 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
710 /* Return the AddressSpace corresponding to the specified index */
711 return cpu->cpu_ases[asidx].as;
713 #endif
715 void cpu_exec_unrealizefn(CPUState *cpu)
717 CPUClass *cc = CPU_GET_CLASS(cpu);
719 cpu_list_remove(cpu);
721 if (cc->vmsd != NULL) {
722 vmstate_unregister(NULL, cc->vmsd, cpu);
724 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
725 vmstate_unregister(NULL, &vmstate_cpu_common, cpu);
729 void cpu_exec_initfn(CPUState *cpu)
731 cpu->as = NULL;
732 cpu->num_ases = 0;
734 #ifndef CONFIG_USER_ONLY
735 cpu->thread_id = qemu_get_thread_id();
737 /* This is a softmmu CPU object, so create a property for it
738 * so users can wire up its memory. (This can't go in qom/cpu.c
739 * because that file is compiled only once for both user-mode
740 * and system builds.) The default if no link is set up is to use
741 * the system address space.
743 object_property_add_link(OBJECT(cpu), "memory", TYPE_MEMORY_REGION,
744 (Object **)&cpu->memory,
745 qdev_prop_allow_set_link_before_realize,
746 OBJ_PROP_LINK_UNREF_ON_RELEASE,
747 &error_abort);
748 cpu->memory = system_memory;
749 object_ref(OBJECT(cpu->memory));
750 #endif
753 void cpu_exec_realizefn(CPUState *cpu, Error **errp)
755 CPUClass *cc ATTRIBUTE_UNUSED = CPU_GET_CLASS(cpu);
757 cpu_list_add(cpu);
759 #ifndef CONFIG_USER_ONLY
760 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
761 vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
763 if (cc->vmsd != NULL) {
764 vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);
766 #endif
769 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
771 /* Flush the whole TB as this will not have race conditions
772 * even if we don't have proper locking yet.
773 * Ideally we would just invalidate the TBs for the
774 * specified PC.
776 tb_flush(cpu);
779 #if defined(CONFIG_USER_ONLY)
780 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
785 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
786 int flags)
788 return -ENOSYS;
791 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
795 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
796 int flags, CPUWatchpoint **watchpoint)
798 return -ENOSYS;
800 #else
801 /* Add a watchpoint. */
802 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
803 int flags, CPUWatchpoint **watchpoint)
805 CPUWatchpoint *wp;
807 /* forbid ranges which are empty or run off the end of the address space */
808 if (len == 0 || (addr + len - 1) < addr) {
809 error_report("tried to set invalid watchpoint at %"
810 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
811 return -EINVAL;
813 wp = g_malloc(sizeof(*wp));
815 wp->vaddr = addr;
816 wp->len = len;
817 wp->flags = flags;
819 /* keep all GDB-injected watchpoints in front */
820 if (flags & BP_GDB) {
821 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
822 } else {
823 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
826 tlb_flush_page(cpu, addr);
828 if (watchpoint)
829 *watchpoint = wp;
830 return 0;
833 /* Remove a specific watchpoint. */
834 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
835 int flags)
837 CPUWatchpoint *wp;
839 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
840 if (addr == wp->vaddr && len == wp->len
841 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
842 cpu_watchpoint_remove_by_ref(cpu, wp);
843 return 0;
846 return -ENOENT;
849 /* Remove a specific watchpoint by reference. */
850 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
852 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
854 tlb_flush_page(cpu, watchpoint->vaddr);
856 g_free(watchpoint);
859 /* Remove all matching watchpoints. */
860 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
862 CPUWatchpoint *wp, *next;
864 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
865 if (wp->flags & mask) {
866 cpu_watchpoint_remove_by_ref(cpu, wp);
871 /* Return true if this watchpoint address matches the specified
872 * access (ie the address range covered by the watchpoint overlaps
873 * partially or completely with the address range covered by the
874 * access).
876 static inline bool cpu_watchpoint_address_matches(CPUWatchpoint *wp,
877 vaddr addr,
878 vaddr len)
880 /* We know the lengths are non-zero, but a little caution is
881 * required to avoid errors in the case where the range ends
882 * exactly at the top of the address space and so addr + len
883 * wraps round to zero.
885 vaddr wpend = wp->vaddr + wp->len - 1;
886 vaddr addrend = addr + len - 1;
888 return !(addr > wpend || wp->vaddr > addrend);
891 #endif
893 /* Add a breakpoint. */
894 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
895 CPUBreakpoint **breakpoint)
897 CPUBreakpoint *bp;
899 bp = g_malloc(sizeof(*bp));
901 bp->pc = pc;
902 bp->flags = flags;
904 /* keep all GDB-injected breakpoints in front */
905 if (flags & BP_GDB) {
906 QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
907 } else {
908 QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
911 breakpoint_invalidate(cpu, pc);
913 if (breakpoint) {
914 *breakpoint = bp;
916 return 0;
919 /* Remove a specific breakpoint. */
920 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
922 CPUBreakpoint *bp;
924 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
925 if (bp->pc == pc && bp->flags == flags) {
926 cpu_breakpoint_remove_by_ref(cpu, bp);
927 return 0;
930 return -ENOENT;
933 /* Remove a specific breakpoint by reference. */
934 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
936 QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);
938 breakpoint_invalidate(cpu, breakpoint->pc);
940 g_free(breakpoint);
943 /* Remove all matching breakpoints. */
944 void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
946 CPUBreakpoint *bp, *next;
948 QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
949 if (bp->flags & mask) {
950 cpu_breakpoint_remove_by_ref(cpu, bp);
955 /* enable or disable single step mode. EXCP_DEBUG is returned by the
956 CPU loop after each instruction */
957 void cpu_single_step(CPUState *cpu, int enabled)
959 if (cpu->singlestep_enabled != enabled) {
960 cpu->singlestep_enabled = enabled;
961 if (kvm_enabled()) {
962 kvm_update_guest_debug(cpu, 0);
963 } else {
964 /* must flush all the translated code to avoid inconsistencies */
965 /* XXX: only flush what is necessary */
966 tb_flush(cpu);
971 void cpu_abort(CPUState *cpu, const char *fmt, ...)
973 va_list ap;
974 va_list ap2;
976 va_start(ap, fmt);
977 va_copy(ap2, ap);
978 fprintf(stderr, "qemu: fatal: ");
979 vfprintf(stderr, fmt, ap);
980 fprintf(stderr, "\n");
981 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU | CPU_DUMP_CCOP);
982 if (qemu_log_separate()) {
983 qemu_log_lock();
984 qemu_log("qemu: fatal: ");
985 qemu_log_vprintf(fmt, ap2);
986 qemu_log("\n");
987 log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
988 qemu_log_flush();
989 qemu_log_unlock();
990 qemu_log_close();
992 va_end(ap2);
993 va_end(ap);
994 replay_finish();
995 #if defined(CONFIG_USER_ONLY)
997 struct sigaction act;
998 sigfillset(&act.sa_mask);
999 act.sa_handler = SIG_DFL;
1000 sigaction(SIGABRT, &act, NULL);
1002 #endif
1003 abort();
1006 #if !defined(CONFIG_USER_ONLY)
1007 /* Called from RCU critical section */
1008 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
1010 RAMBlock *block;
1012 block = atomic_rcu_read(&ram_list.mru_block);
1013 if (block && addr - block->offset < block->max_length) {
1014 return block;
1016 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1017 if (addr - block->offset < block->max_length) {
1018 goto found;
1022 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1023 abort();
1025 found:
1026 /* It is safe to write mru_block outside the iothread lock. This
1027 * is what happens:
1029 * mru_block = xxx
1030 * rcu_read_unlock()
1031 * xxx removed from list
1032 * rcu_read_lock()
1033 * read mru_block
1034 * mru_block = NULL;
1035 * call_rcu(reclaim_ramblock, xxx);
1036 * rcu_read_unlock()
1038 * atomic_rcu_set is not needed here. The block was already published
1039 * when it was placed into the list. Here we're just making an extra
1040 * copy of the pointer.
1042 ram_list.mru_block = block;
1043 return block;
1046 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1048 CPUState *cpu;
1049 ram_addr_t start1;
1050 RAMBlock *block;
1051 ram_addr_t end;
1053 end = TARGET_PAGE_ALIGN(start + length);
1054 start &= TARGET_PAGE_MASK;
1056 rcu_read_lock();
1057 block = qemu_get_ram_block(start);
1058 assert(block == qemu_get_ram_block(end - 1));
1059 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1060 CPU_FOREACH(cpu) {
1061 tlb_reset_dirty(cpu, start1, length);
1063 rcu_read_unlock();
1066 /* Note: start and end must be within the same ram block. */
1067 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1068 ram_addr_t length,
1069 unsigned client)
1071 DirtyMemoryBlocks *blocks;
1072 unsigned long end, page;
1073 bool dirty = false;
1075 if (length == 0) {
1076 return false;
1079 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1080 page = start >> TARGET_PAGE_BITS;
1082 rcu_read_lock();
1084 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1086 while (page < end) {
1087 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1088 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1089 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1091 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1092 offset, num);
1093 page += num;
1096 rcu_read_unlock();
1098 if (dirty && tcg_enabled()) {
1099 tlb_reset_dirty_range_all(start, length);
1102 return dirty;
1105 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1106 (ram_addr_t start, ram_addr_t length, unsigned client)
1108 DirtyMemoryBlocks *blocks;
1109 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1110 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1111 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1112 DirtyBitmapSnapshot *snap;
1113 unsigned long page, end, dest;
1115 snap = g_malloc0(sizeof(*snap) +
1116 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1117 snap->start = first;
1118 snap->end = last;
1120 page = first >> TARGET_PAGE_BITS;
1121 end = last >> TARGET_PAGE_BITS;
1122 dest = 0;
1124 rcu_read_lock();
1126 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1128 while (page < end) {
1129 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1130 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1131 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1133 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1134 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1135 offset >>= BITS_PER_LEVEL;
1137 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1138 blocks->blocks[idx] + offset,
1139 num);
1140 page += num;
1141 dest += num >> BITS_PER_LEVEL;
1144 rcu_read_unlock();
1146 if (tcg_enabled()) {
1147 tlb_reset_dirty_range_all(start, length);
1150 return snap;
1153 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1154 ram_addr_t start,
1155 ram_addr_t length)
1157 unsigned long page, end;
1159 assert(start >= snap->start);
1160 assert(start + length <= snap->end);
1162 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1163 page = (start - snap->start) >> TARGET_PAGE_BITS;
1165 while (page < end) {
1166 if (test_bit(page, snap->dirty)) {
1167 return true;
1169 page++;
1171 return false;
1174 /* Called from RCU critical section */
1175 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1176 MemoryRegionSection *section,
1177 target_ulong vaddr,
1178 hwaddr paddr, hwaddr xlat,
1179 int prot,
1180 target_ulong *address)
1182 hwaddr iotlb;
1183 CPUWatchpoint *wp;
1185 if (memory_region_is_ram(section->mr)) {
1186 /* Normal RAM. */
1187 iotlb = memory_region_get_ram_addr(section->mr) + xlat;
1188 if (!section->readonly) {
1189 iotlb |= PHYS_SECTION_NOTDIRTY;
1190 } else {
1191 iotlb |= PHYS_SECTION_ROM;
1193 } else {
1194 AddressSpaceDispatch *d;
1196 d = atomic_rcu_read(&section->address_space->dispatch);
1197 iotlb = section - d->map.sections;
1198 iotlb += xlat;
1201 /* Make accesses to pages with watchpoints go via the
1202 watchpoint trap routines. */
1203 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1204 if (cpu_watchpoint_address_matches(wp, vaddr, TARGET_PAGE_SIZE)) {
1205 /* Avoid trapping reads of pages with a write breakpoint. */
1206 if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
1207 iotlb = PHYS_SECTION_WATCH + paddr;
1208 *address |= TLB_MMIO;
1209 break;
1214 return iotlb;
1216 #endif /* defined(CONFIG_USER_ONLY) */
1218 #if !defined(CONFIG_USER_ONLY)
1220 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
1221 uint16_t section);
1222 static subpage_t *subpage_init(AddressSpace *as, hwaddr base);
1224 static void *(*phys_mem_alloc)(size_t size, uint64_t *align) =
1225 qemu_anon_ram_alloc;
1228 * Set a custom physical guest memory alloator.
1229 * Accelerators with unusual needs may need this. Hopefully, we can
1230 * get rid of it eventually.
1232 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align))
1234 phys_mem_alloc = alloc;
1237 static uint16_t phys_section_add(PhysPageMap *map,
1238 MemoryRegionSection *section)
1240 /* The physical section number is ORed with a page-aligned
1241 * pointer to produce the iotlb entries. Thus it should
1242 * never overflow into the page-aligned value.
1244 assert(map->sections_nb < TARGET_PAGE_SIZE);
1246 if (map->sections_nb == map->sections_nb_alloc) {
1247 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1248 map->sections = g_renew(MemoryRegionSection, map->sections,
1249 map->sections_nb_alloc);
1251 map->sections[map->sections_nb] = *section;
1252 memory_region_ref(section->mr);
1253 return map->sections_nb++;
1256 static void phys_section_destroy(MemoryRegion *mr)
1258 bool have_sub_page = mr->subpage;
1260 memory_region_unref(mr);
1262 if (have_sub_page) {
1263 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1264 object_unref(OBJECT(&subpage->iomem));
1265 g_free(subpage);
1269 static void phys_sections_free(PhysPageMap *map)
1271 while (map->sections_nb > 0) {
1272 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1273 phys_section_destroy(section->mr);
1275 g_free(map->sections);
1276 g_free(map->nodes);
1279 static void register_subpage(AddressSpaceDispatch *d, MemoryRegionSection *section)
1281 subpage_t *subpage;
1282 hwaddr base = section->offset_within_address_space
1283 & TARGET_PAGE_MASK;
1284 MemoryRegionSection *existing = phys_page_find(d->phys_map, base,
1285 d->map.nodes, d->map.sections);
1286 MemoryRegionSection subsection = {
1287 .offset_within_address_space = base,
1288 .size = int128_make64(TARGET_PAGE_SIZE),
1290 hwaddr start, end;
1292 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1294 if (!(existing->mr->subpage)) {
1295 subpage = subpage_init(d->as, base);
1296 subsection.address_space = d->as;
1297 subsection.mr = &subpage->iomem;
1298 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1299 phys_section_add(&d->map, &subsection));
1300 } else {
1301 subpage = container_of(existing->mr, subpage_t, iomem);
1303 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1304 end = start + int128_get64(section->size) - 1;
1305 subpage_register(subpage, start, end,
1306 phys_section_add(&d->map, section));
1310 static void register_multipage(AddressSpaceDispatch *d,
1311 MemoryRegionSection *section)
1313 hwaddr start_addr = section->offset_within_address_space;
1314 uint16_t section_index = phys_section_add(&d->map, section);
1315 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1316 TARGET_PAGE_BITS));
1318 assert(num_pages);
1319 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1322 static void mem_add(MemoryListener *listener, MemoryRegionSection *section)
1324 AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
1325 AddressSpaceDispatch *d = as->next_dispatch;
1326 MemoryRegionSection now = *section, remain = *section;
1327 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1329 if (now.offset_within_address_space & ~TARGET_PAGE_MASK) {
1330 uint64_t left = TARGET_PAGE_ALIGN(now.offset_within_address_space)
1331 - now.offset_within_address_space;
1333 now.size = int128_min(int128_make64(left), now.size);
1334 register_subpage(d, &now);
1335 } else {
1336 now.size = int128_zero();
1338 while (int128_ne(remain.size, now.size)) {
1339 remain.size = int128_sub(remain.size, now.size);
1340 remain.offset_within_address_space += int128_get64(now.size);
1341 remain.offset_within_region += int128_get64(now.size);
1342 now = remain;
1343 if (int128_lt(remain.size, page_size)) {
1344 register_subpage(d, &now);
1345 } else if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1346 now.size = page_size;
1347 register_subpage(d, &now);
1348 } else {
1349 now.size = int128_and(now.size, int128_neg(page_size));
1350 register_multipage(d, &now);
1355 void qemu_flush_coalesced_mmio_buffer(void)
1357 if (kvm_enabled())
1358 kvm_flush_coalesced_mmio_buffer();
1361 void qemu_mutex_lock_ramlist(void)
1363 qemu_mutex_lock(&ram_list.mutex);
1366 void qemu_mutex_unlock_ramlist(void)
1368 qemu_mutex_unlock(&ram_list.mutex);
1371 #ifdef __linux__
1373 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1374 * may or may not name the same files / on the same filesystem now as
1375 * when we actually open and map them. Iterate over the file
1376 * descriptors instead, and use qemu_fd_getpagesize().
1378 static int find_max_supported_pagesize(Object *obj, void *opaque)
1380 char *mem_path;
1381 long *hpsize_min = opaque;
1383 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1384 mem_path = object_property_get_str(obj, "mem-path", NULL);
1385 if (mem_path) {
1386 long hpsize = qemu_mempath_getpagesize(mem_path);
1387 if (hpsize < *hpsize_min) {
1388 *hpsize_min = hpsize;
1390 } else {
1391 *hpsize_min = getpagesize();
1395 return 0;
1398 long qemu_getrampagesize(void)
1400 long hpsize = LONG_MAX;
1401 long mainrampagesize;
1402 Object *memdev_root;
1404 if (mem_path) {
1405 mainrampagesize = qemu_mempath_getpagesize(mem_path);
1406 } else {
1407 mainrampagesize = getpagesize();
1410 /* it's possible we have memory-backend objects with
1411 * hugepage-backed RAM. these may get mapped into system
1412 * address space via -numa parameters or memory hotplug
1413 * hooks. we want to take these into account, but we
1414 * also want to make sure these supported hugepage
1415 * sizes are applicable across the entire range of memory
1416 * we may boot from, so we take the min across all
1417 * backends, and assume normal pages in cases where a
1418 * backend isn't backed by hugepages.
1420 memdev_root = object_resolve_path("/objects", NULL);
1421 if (memdev_root) {
1422 object_child_foreach(memdev_root, find_max_supported_pagesize, &hpsize);
1424 if (hpsize == LONG_MAX) {
1425 /* No additional memory regions found ==> Report main RAM page size */
1426 return mainrampagesize;
1429 /* If NUMA is disabled or the NUMA nodes are not backed with a
1430 * memory-backend, then there is at least one node using "normal" RAM,
1431 * so if its page size is smaller we have got to report that size instead.
1433 if (hpsize > mainrampagesize &&
1434 (nb_numa_nodes == 0 || numa_info[0].node_memdev == NULL)) {
1435 static bool warned;
1436 if (!warned) {
1437 error_report("Huge page support disabled (n/a for main memory).");
1438 warned = true;
1440 return mainrampagesize;
1443 return hpsize;
1445 #else
1446 long qemu_getrampagesize(void)
1448 return getpagesize();
1450 #endif
1452 #ifdef __linux__
1453 static int64_t get_file_size(int fd)
1455 int64_t size = lseek(fd, 0, SEEK_END);
1456 if (size < 0) {
1457 return -errno;
1459 return size;
1462 static void *file_ram_alloc(RAMBlock *block,
1463 ram_addr_t memory,
1464 const char *path,
1465 Error **errp)
1467 bool unlink_on_error = false;
1468 char *filename;
1469 char *sanitized_name;
1470 char *c;
1471 void *area = MAP_FAILED;
1472 int fd = -1;
1473 int64_t file_size;
1475 if (kvm_enabled() && !kvm_has_sync_mmu()) {
1476 error_setg(errp,
1477 "host lacks kvm mmu notifiers, -mem-path unsupported");
1478 return NULL;
1481 for (;;) {
1482 fd = open(path, O_RDWR);
1483 if (fd >= 0) {
1484 /* @path names an existing file, use it */
1485 break;
1487 if (errno == ENOENT) {
1488 /* @path names a file that doesn't exist, create it */
1489 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1490 if (fd >= 0) {
1491 unlink_on_error = true;
1492 break;
1494 } else if (errno == EISDIR) {
1495 /* @path names a directory, create a file there */
1496 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1497 sanitized_name = g_strdup(memory_region_name(block->mr));
1498 for (c = sanitized_name; *c != '\0'; c++) {
1499 if (*c == '/') {
1500 *c = '_';
1504 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1505 sanitized_name);
1506 g_free(sanitized_name);
1508 fd = mkstemp(filename);
1509 if (fd >= 0) {
1510 unlink(filename);
1511 g_free(filename);
1512 break;
1514 g_free(filename);
1516 if (errno != EEXIST && errno != EINTR) {
1517 error_setg_errno(errp, errno,
1518 "can't open backing store %s for guest RAM",
1519 path);
1520 goto error;
1523 * Try again on EINTR and EEXIST. The latter happens when
1524 * something else creates the file between our two open().
1528 block->page_size = qemu_fd_getpagesize(fd);
1529 block->mr->align = block->page_size;
1530 #if defined(__s390x__)
1531 if (kvm_enabled()) {
1532 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1534 #endif
1536 file_size = get_file_size(fd);
1538 if (memory < block->page_size) {
1539 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1540 "or larger than page size 0x%zx",
1541 memory, block->page_size);
1542 goto error;
1545 if (file_size > 0 && file_size < memory) {
1546 error_setg(errp, "backing store %s size 0x%" PRIx64
1547 " does not match 'size' option 0x" RAM_ADDR_FMT,
1548 path, file_size, memory);
1549 goto error;
1552 memory = ROUND_UP(memory, block->page_size);
1555 * ftruncate is not supported by hugetlbfs in older
1556 * hosts, so don't bother bailing out on errors.
1557 * If anything goes wrong with it under other filesystems,
1558 * mmap will fail.
1560 * Do not truncate the non-empty backend file to avoid corrupting
1561 * the existing data in the file. Disabling shrinking is not
1562 * enough. For example, the current vNVDIMM implementation stores
1563 * the guest NVDIMM labels at the end of the backend file. If the
1564 * backend file is later extended, QEMU will not be able to find
1565 * those labels. Therefore, extending the non-empty backend file
1566 * is disabled as well.
1568 if (!file_size && ftruncate(fd, memory)) {
1569 perror("ftruncate");
1572 area = qemu_ram_mmap(fd, memory, block->mr->align,
1573 block->flags & RAM_SHARED);
1574 if (area == MAP_FAILED) {
1575 error_setg_errno(errp, errno,
1576 "unable to map backing store for guest RAM");
1577 goto error;
1580 if (mem_prealloc) {
1581 os_mem_prealloc(fd, area, memory, smp_cpus, errp);
1582 if (errp && *errp) {
1583 goto error;
1587 block->fd = fd;
1588 return area;
1590 error:
1591 if (area != MAP_FAILED) {
1592 qemu_ram_munmap(area, memory);
1594 if (unlink_on_error) {
1595 unlink(path);
1597 if (fd != -1) {
1598 close(fd);
1600 return NULL;
1602 #endif
1604 /* Called with the ramlist lock held. */
1605 static ram_addr_t find_ram_offset(ram_addr_t size)
1607 RAMBlock *block, *next_block;
1608 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1610 assert(size != 0); /* it would hand out same offset multiple times */
1612 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1613 return 0;
1616 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1617 ram_addr_t end, next = RAM_ADDR_MAX;
1619 end = block->offset + block->max_length;
1621 QLIST_FOREACH_RCU(next_block, &ram_list.blocks, next) {
1622 if (next_block->offset >= end) {
1623 next = MIN(next, next_block->offset);
1626 if (next - end >= size && next - end < mingap) {
1627 offset = end;
1628 mingap = next - end;
1632 if (offset == RAM_ADDR_MAX) {
1633 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1634 (uint64_t)size);
1635 abort();
1638 return offset;
1641 unsigned long last_ram_page(void)
1643 RAMBlock *block;
1644 ram_addr_t last = 0;
1646 rcu_read_lock();
1647 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1648 last = MAX(last, block->offset + block->max_length);
1650 rcu_read_unlock();
1651 return last >> TARGET_PAGE_BITS;
1654 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1656 int ret;
1658 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1659 if (!machine_dump_guest_core(current_machine)) {
1660 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1661 if (ret) {
1662 perror("qemu_madvise");
1663 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1664 "but dump_guest_core=off specified\n");
1669 const char *qemu_ram_get_idstr(RAMBlock *rb)
1671 return rb->idstr;
1674 bool qemu_ram_is_shared(RAMBlock *rb)
1676 return rb->flags & RAM_SHARED;
1679 /* Called with iothread lock held. */
1680 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1682 RAMBlock *block;
1684 assert(new_block);
1685 assert(!new_block->idstr[0]);
1687 if (dev) {
1688 char *id = qdev_get_dev_path(dev);
1689 if (id) {
1690 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1691 g_free(id);
1694 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1696 rcu_read_lock();
1697 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1698 if (block != new_block &&
1699 !strcmp(block->idstr, new_block->idstr)) {
1700 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1701 new_block->idstr);
1702 abort();
1705 rcu_read_unlock();
1708 /* Called with iothread lock held. */
1709 void qemu_ram_unset_idstr(RAMBlock *block)
1711 /* FIXME: arch_init.c assumes that this is not called throughout
1712 * migration. Ignore the problem since hot-unplug during migration
1713 * does not work anyway.
1715 if (block) {
1716 memset(block->idstr, 0, sizeof(block->idstr));
1720 size_t qemu_ram_pagesize(RAMBlock *rb)
1722 return rb->page_size;
1725 /* Returns the largest size of page in use */
1726 size_t qemu_ram_pagesize_largest(void)
1728 RAMBlock *block;
1729 size_t largest = 0;
1731 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1732 largest = MAX(largest, qemu_ram_pagesize(block));
1735 return largest;
1738 static int memory_try_enable_merging(void *addr, size_t len)
1740 if (!machine_mem_merge(current_machine)) {
1741 /* disabled by the user */
1742 return 0;
1745 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1748 /* Only legal before guest might have detected the memory size: e.g. on
1749 * incoming migration, or right after reset.
1751 * As memory core doesn't know how is memory accessed, it is up to
1752 * resize callback to update device state and/or add assertions to detect
1753 * misuse, if necessary.
1755 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1757 assert(block);
1759 newsize = HOST_PAGE_ALIGN(newsize);
1761 if (block->used_length == newsize) {
1762 return 0;
1765 if (!(block->flags & RAM_RESIZEABLE)) {
1766 error_setg_errno(errp, EINVAL,
1767 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1768 " in != 0x" RAM_ADDR_FMT, block->idstr,
1769 newsize, block->used_length);
1770 return -EINVAL;
1773 if (block->max_length < newsize) {
1774 error_setg_errno(errp, EINVAL,
1775 "Length too large: %s: 0x" RAM_ADDR_FMT
1776 " > 0x" RAM_ADDR_FMT, block->idstr,
1777 newsize, block->max_length);
1778 return -EINVAL;
1781 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1782 block->used_length = newsize;
1783 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1784 DIRTY_CLIENTS_ALL);
1785 memory_region_set_size(block->mr, newsize);
1786 if (block->resized) {
1787 block->resized(block->idstr, newsize, block->host);
1789 return 0;
1792 /* Called with ram_list.mutex held */
1793 static void dirty_memory_extend(ram_addr_t old_ram_size,
1794 ram_addr_t new_ram_size)
1796 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1797 DIRTY_MEMORY_BLOCK_SIZE);
1798 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1799 DIRTY_MEMORY_BLOCK_SIZE);
1800 int i;
1802 /* Only need to extend if block count increased */
1803 if (new_num_blocks <= old_num_blocks) {
1804 return;
1807 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1808 DirtyMemoryBlocks *old_blocks;
1809 DirtyMemoryBlocks *new_blocks;
1810 int j;
1812 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
1813 new_blocks = g_malloc(sizeof(*new_blocks) +
1814 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1816 if (old_num_blocks) {
1817 memcpy(new_blocks->blocks, old_blocks->blocks,
1818 old_num_blocks * sizeof(old_blocks->blocks[0]));
1821 for (j = old_num_blocks; j < new_num_blocks; j++) {
1822 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1825 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1827 if (old_blocks) {
1828 g_free_rcu(old_blocks, rcu);
1833 static void ram_block_add(RAMBlock *new_block, Error **errp)
1835 RAMBlock *block;
1836 RAMBlock *last_block = NULL;
1837 ram_addr_t old_ram_size, new_ram_size;
1838 Error *err = NULL;
1840 old_ram_size = last_ram_page();
1842 qemu_mutex_lock_ramlist();
1843 new_block->offset = find_ram_offset(new_block->max_length);
1845 if (!new_block->host) {
1846 if (xen_enabled()) {
1847 xen_ram_alloc(new_block->offset, new_block->max_length,
1848 new_block->mr, &err);
1849 if (err) {
1850 error_propagate(errp, err);
1851 qemu_mutex_unlock_ramlist();
1852 return;
1854 } else {
1855 new_block->host = phys_mem_alloc(new_block->max_length,
1856 &new_block->mr->align);
1857 if (!new_block->host) {
1858 error_setg_errno(errp, errno,
1859 "cannot set up guest memory '%s'",
1860 memory_region_name(new_block->mr));
1861 qemu_mutex_unlock_ramlist();
1862 return;
1864 memory_try_enable_merging(new_block->host, new_block->max_length);
1868 new_ram_size = MAX(old_ram_size,
1869 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1870 if (new_ram_size > old_ram_size) {
1871 dirty_memory_extend(old_ram_size, new_ram_size);
1873 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1874 * QLIST (which has an RCU-friendly variant) does not have insertion at
1875 * tail, so save the last element in last_block.
1877 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1878 last_block = block;
1879 if (block->max_length < new_block->max_length) {
1880 break;
1883 if (block) {
1884 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1885 } else if (last_block) {
1886 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
1887 } else { /* list is empty */
1888 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1890 ram_list.mru_block = NULL;
1892 /* Write list before version */
1893 smp_wmb();
1894 ram_list.version++;
1895 qemu_mutex_unlock_ramlist();
1897 cpu_physical_memory_set_dirty_range(new_block->offset,
1898 new_block->used_length,
1899 DIRTY_CLIENTS_ALL);
1901 if (new_block->host) {
1902 qemu_ram_setup_dump(new_block->host, new_block->max_length);
1903 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
1904 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
1905 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
1906 ram_block_notify_add(new_block->host, new_block->max_length);
1910 #ifdef __linux__
1911 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
1912 bool share, const char *mem_path,
1913 Error **errp)
1915 RAMBlock *new_block;
1916 Error *local_err = NULL;
1918 if (xen_enabled()) {
1919 error_setg(errp, "-mem-path not supported with Xen");
1920 return NULL;
1923 if (phys_mem_alloc != qemu_anon_ram_alloc) {
1925 * file_ram_alloc() needs to allocate just like
1926 * phys_mem_alloc, but we haven't bothered to provide
1927 * a hook there.
1929 error_setg(errp,
1930 "-mem-path not supported with this accelerator");
1931 return NULL;
1934 size = HOST_PAGE_ALIGN(size);
1935 new_block = g_malloc0(sizeof(*new_block));
1936 new_block->mr = mr;
1937 new_block->used_length = size;
1938 new_block->max_length = size;
1939 new_block->flags = share ? RAM_SHARED : 0;
1940 new_block->host = file_ram_alloc(new_block, size,
1941 mem_path, errp);
1942 if (!new_block->host) {
1943 g_free(new_block);
1944 return NULL;
1947 ram_block_add(new_block, &local_err);
1948 if (local_err) {
1949 g_free(new_block);
1950 error_propagate(errp, local_err);
1951 return NULL;
1953 return new_block;
1955 #endif
1957 static
1958 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
1959 void (*resized)(const char*,
1960 uint64_t length,
1961 void *host),
1962 void *host, bool resizeable,
1963 MemoryRegion *mr, Error **errp)
1965 RAMBlock *new_block;
1966 Error *local_err = NULL;
1968 size = HOST_PAGE_ALIGN(size);
1969 max_size = HOST_PAGE_ALIGN(max_size);
1970 new_block = g_malloc0(sizeof(*new_block));
1971 new_block->mr = mr;
1972 new_block->resized = resized;
1973 new_block->used_length = size;
1974 new_block->max_length = max_size;
1975 assert(max_size >= size);
1976 new_block->fd = -1;
1977 new_block->page_size = getpagesize();
1978 new_block->host = host;
1979 if (host) {
1980 new_block->flags |= RAM_PREALLOC;
1982 if (resizeable) {
1983 new_block->flags |= RAM_RESIZEABLE;
1985 ram_block_add(new_block, &local_err);
1986 if (local_err) {
1987 g_free(new_block);
1988 error_propagate(errp, local_err);
1989 return NULL;
1991 return new_block;
1994 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
1995 MemoryRegion *mr, Error **errp)
1997 return qemu_ram_alloc_internal(size, size, NULL, host, false, mr, errp);
2000 RAMBlock *qemu_ram_alloc(ram_addr_t size, MemoryRegion *mr, Error **errp)
2002 return qemu_ram_alloc_internal(size, size, NULL, NULL, false, mr, errp);
2005 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2006 void (*resized)(const char*,
2007 uint64_t length,
2008 void *host),
2009 MemoryRegion *mr, Error **errp)
2011 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true, mr, errp);
2014 static void reclaim_ramblock(RAMBlock *block)
2016 if (block->flags & RAM_PREALLOC) {
2018 } else if (xen_enabled()) {
2019 xen_invalidate_map_cache_entry(block->host);
2020 #ifndef _WIN32
2021 } else if (block->fd >= 0) {
2022 qemu_ram_munmap(block->host, block->max_length);
2023 close(block->fd);
2024 #endif
2025 } else {
2026 qemu_anon_ram_free(block->host, block->max_length);
2028 g_free(block);
2031 void qemu_ram_free(RAMBlock *block)
2033 if (!block) {
2034 return;
2037 if (block->host) {
2038 ram_block_notify_remove(block->host, block->max_length);
2041 qemu_mutex_lock_ramlist();
2042 QLIST_REMOVE_RCU(block, next);
2043 ram_list.mru_block = NULL;
2044 /* Write list before version */
2045 smp_wmb();
2046 ram_list.version++;
2047 call_rcu(block, reclaim_ramblock, rcu);
2048 qemu_mutex_unlock_ramlist();
2051 #ifndef _WIN32
2052 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2054 RAMBlock *block;
2055 ram_addr_t offset;
2056 int flags;
2057 void *area, *vaddr;
2059 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
2060 offset = addr - block->offset;
2061 if (offset < block->max_length) {
2062 vaddr = ramblock_ptr(block, offset);
2063 if (block->flags & RAM_PREALLOC) {
2065 } else if (xen_enabled()) {
2066 abort();
2067 } else {
2068 flags = MAP_FIXED;
2069 if (block->fd >= 0) {
2070 flags |= (block->flags & RAM_SHARED ?
2071 MAP_SHARED : MAP_PRIVATE);
2072 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2073 flags, block->fd, offset);
2074 } else {
2076 * Remap needs to match alloc. Accelerators that
2077 * set phys_mem_alloc never remap. If they did,
2078 * we'd need a remap hook here.
2080 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2082 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2083 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2084 flags, -1, 0);
2086 if (area != vaddr) {
2087 fprintf(stderr, "Could not remap addr: "
2088 RAM_ADDR_FMT "@" RAM_ADDR_FMT "\n",
2089 length, addr);
2090 exit(1);
2092 memory_try_enable_merging(vaddr, length);
2093 qemu_ram_setup_dump(vaddr, length);
2098 #endif /* !_WIN32 */
2100 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2101 * This should not be used for general purpose DMA. Use address_space_map
2102 * or address_space_rw instead. For local memory (e.g. video ram) that the
2103 * device owns, use memory_region_get_ram_ptr.
2105 * Called within RCU critical section.
2107 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2109 RAMBlock *block = ram_block;
2111 if (block == NULL) {
2112 block = qemu_get_ram_block(addr);
2113 addr -= block->offset;
2116 if (xen_enabled() && block->host == NULL) {
2117 /* We need to check if the requested address is in the RAM
2118 * because we don't want to map the entire memory in QEMU.
2119 * In that case just map until the end of the page.
2121 if (block->offset == 0) {
2122 return xen_map_cache(addr, 0, 0);
2125 block->host = xen_map_cache(block->offset, block->max_length, 1);
2127 return ramblock_ptr(block, addr);
2130 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2131 * but takes a size argument.
2133 * Called within RCU critical section.
2135 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2136 hwaddr *size)
2138 RAMBlock *block = ram_block;
2139 if (*size == 0) {
2140 return NULL;
2143 if (block == NULL) {
2144 block = qemu_get_ram_block(addr);
2145 addr -= block->offset;
2147 *size = MIN(*size, block->max_length - addr);
2149 if (xen_enabled() && block->host == NULL) {
2150 /* We need to check if the requested address is in the RAM
2151 * because we don't want to map the entire memory in QEMU.
2152 * In that case just map the requested area.
2154 if (block->offset == 0) {
2155 return xen_map_cache(addr, *size, 1);
2158 block->host = xen_map_cache(block->offset, block->max_length, 1);
2161 return ramblock_ptr(block, addr);
2165 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2166 * in that RAMBlock.
2168 * ptr: Host pointer to look up
2169 * round_offset: If true round the result offset down to a page boundary
2170 * *ram_addr: set to result ram_addr
2171 * *offset: set to result offset within the RAMBlock
2173 * Returns: RAMBlock (or NULL if not found)
2175 * By the time this function returns, the returned pointer is not protected
2176 * by RCU anymore. If the caller is not within an RCU critical section and
2177 * does not hold the iothread lock, it must have other means of protecting the
2178 * pointer, such as a reference to the region that includes the incoming
2179 * ram_addr_t.
2181 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2182 ram_addr_t *offset)
2184 RAMBlock *block;
2185 uint8_t *host = ptr;
2187 if (xen_enabled()) {
2188 ram_addr_t ram_addr;
2189 rcu_read_lock();
2190 ram_addr = xen_ram_addr_from_mapcache(ptr);
2191 block = qemu_get_ram_block(ram_addr);
2192 if (block) {
2193 *offset = ram_addr - block->offset;
2195 rcu_read_unlock();
2196 return block;
2199 rcu_read_lock();
2200 block = atomic_rcu_read(&ram_list.mru_block);
2201 if (block && block->host && host - block->host < block->max_length) {
2202 goto found;
2205 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
2206 /* This case append when the block is not mapped. */
2207 if (block->host == NULL) {
2208 continue;
2210 if (host - block->host < block->max_length) {
2211 goto found;
2215 rcu_read_unlock();
2216 return NULL;
2218 found:
2219 *offset = (host - block->host);
2220 if (round_offset) {
2221 *offset &= TARGET_PAGE_MASK;
2223 rcu_read_unlock();
2224 return block;
2228 * Finds the named RAMBlock
2230 * name: The name of RAMBlock to find
2232 * Returns: RAMBlock (or NULL if not found)
2234 RAMBlock *qemu_ram_block_by_name(const char *name)
2236 RAMBlock *block;
2238 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
2239 if (!strcmp(name, block->idstr)) {
2240 return block;
2244 return NULL;
2247 /* Some of the softmmu routines need to translate from a host pointer
2248 (typically a TLB entry) back to a ram offset. */
2249 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2251 RAMBlock *block;
2252 ram_addr_t offset;
2254 block = qemu_ram_block_from_host(ptr, false, &offset);
2255 if (!block) {
2256 return RAM_ADDR_INVALID;
2259 return block->offset + offset;
2262 /* Called within RCU critical section. */
2263 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2264 uint64_t val, unsigned size)
2266 bool locked = false;
2268 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
2269 locked = true;
2270 tb_lock();
2271 tb_invalidate_phys_page_fast(ram_addr, size);
2273 switch (size) {
2274 case 1:
2275 stb_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2276 break;
2277 case 2:
2278 stw_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2279 break;
2280 case 4:
2281 stl_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2282 break;
2283 default:
2284 abort();
2287 if (locked) {
2288 tb_unlock();
2291 /* Set both VGA and migration bits for simplicity and to remove
2292 * the notdirty callback faster.
2294 cpu_physical_memory_set_dirty_range(ram_addr, size,
2295 DIRTY_CLIENTS_NOCODE);
2296 /* we remove the notdirty callback only if the code has been
2297 flushed */
2298 if (!cpu_physical_memory_is_clean(ram_addr)) {
2299 tlb_set_dirty(current_cpu, current_cpu->mem_io_vaddr);
2303 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
2304 unsigned size, bool is_write)
2306 return is_write;
2309 static const MemoryRegionOps notdirty_mem_ops = {
2310 .write = notdirty_mem_write,
2311 .valid.accepts = notdirty_mem_accepts,
2312 .endianness = DEVICE_NATIVE_ENDIAN,
2315 /* Generate a debug exception if a watchpoint has been hit. */
2316 static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
2318 CPUState *cpu = current_cpu;
2319 CPUClass *cc = CPU_GET_CLASS(cpu);
2320 CPUArchState *env = cpu->env_ptr;
2321 target_ulong pc, cs_base;
2322 target_ulong vaddr;
2323 CPUWatchpoint *wp;
2324 uint32_t cpu_flags;
2326 if (cpu->watchpoint_hit) {
2327 /* We re-entered the check after replacing the TB. Now raise
2328 * the debug interrupt so that is will trigger after the
2329 * current instruction. */
2330 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2331 return;
2333 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
2334 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
2335 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2336 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2337 && (wp->flags & flags)) {
2338 if (flags == BP_MEM_READ) {
2339 wp->flags |= BP_WATCHPOINT_HIT_READ;
2340 } else {
2341 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2343 wp->hitaddr = vaddr;
2344 wp->hitattrs = attrs;
2345 if (!cpu->watchpoint_hit) {
2346 if (wp->flags & BP_CPU &&
2347 !cc->debug_check_watchpoint(cpu, wp)) {
2348 wp->flags &= ~BP_WATCHPOINT_HIT;
2349 continue;
2351 cpu->watchpoint_hit = wp;
2353 /* Both tb_lock and iothread_mutex will be reset when
2354 * cpu_loop_exit or cpu_loop_exit_noexc longjmp
2355 * back into the cpu_exec main loop.
2357 tb_lock();
2358 tb_check_watchpoint(cpu);
2359 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2360 cpu->exception_index = EXCP_DEBUG;
2361 cpu_loop_exit(cpu);
2362 } else {
2363 cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags);
2364 tb_gen_code(cpu, pc, cs_base, cpu_flags, 1);
2365 cpu_loop_exit_noexc(cpu);
2368 } else {
2369 wp->flags &= ~BP_WATCHPOINT_HIT;
2374 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2375 so these check for a hit then pass through to the normal out-of-line
2376 phys routines. */
2377 static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2378 unsigned size, MemTxAttrs attrs)
2380 MemTxResult res;
2381 uint64_t data;
2382 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2383 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2385 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2386 switch (size) {
2387 case 1:
2388 data = address_space_ldub(as, addr, attrs, &res);
2389 break;
2390 case 2:
2391 data = address_space_lduw(as, addr, attrs, &res);
2392 break;
2393 case 4:
2394 data = address_space_ldl(as, addr, attrs, &res);
2395 break;
2396 default: abort();
2398 *pdata = data;
2399 return res;
2402 static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2403 uint64_t val, unsigned size,
2404 MemTxAttrs attrs)
2406 MemTxResult res;
2407 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2408 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2410 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2411 switch (size) {
2412 case 1:
2413 address_space_stb(as, addr, val, attrs, &res);
2414 break;
2415 case 2:
2416 address_space_stw(as, addr, val, attrs, &res);
2417 break;
2418 case 4:
2419 address_space_stl(as, addr, val, attrs, &res);
2420 break;
2421 default: abort();
2423 return res;
2426 static const MemoryRegionOps watch_mem_ops = {
2427 .read_with_attrs = watch_mem_read,
2428 .write_with_attrs = watch_mem_write,
2429 .endianness = DEVICE_NATIVE_ENDIAN,
2432 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2433 unsigned len, MemTxAttrs attrs)
2435 subpage_t *subpage = opaque;
2436 uint8_t buf[8];
2437 MemTxResult res;
2439 #if defined(DEBUG_SUBPAGE)
2440 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2441 subpage, len, addr);
2442 #endif
2443 res = address_space_read(subpage->as, addr + subpage->base,
2444 attrs, buf, len);
2445 if (res) {
2446 return res;
2448 switch (len) {
2449 case 1:
2450 *data = ldub_p(buf);
2451 return MEMTX_OK;
2452 case 2:
2453 *data = lduw_p(buf);
2454 return MEMTX_OK;
2455 case 4:
2456 *data = ldl_p(buf);
2457 return MEMTX_OK;
2458 case 8:
2459 *data = ldq_p(buf);
2460 return MEMTX_OK;
2461 default:
2462 abort();
2466 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2467 uint64_t value, unsigned len, MemTxAttrs attrs)
2469 subpage_t *subpage = opaque;
2470 uint8_t buf[8];
2472 #if defined(DEBUG_SUBPAGE)
2473 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2474 " value %"PRIx64"\n",
2475 __func__, subpage, len, addr, value);
2476 #endif
2477 switch (len) {
2478 case 1:
2479 stb_p(buf, value);
2480 break;
2481 case 2:
2482 stw_p(buf, value);
2483 break;
2484 case 4:
2485 stl_p(buf, value);
2486 break;
2487 case 8:
2488 stq_p(buf, value);
2489 break;
2490 default:
2491 abort();
2493 return address_space_write(subpage->as, addr + subpage->base,
2494 attrs, buf, len);
2497 static bool subpage_accepts(void *opaque, hwaddr addr,
2498 unsigned len, bool is_write)
2500 subpage_t *subpage = opaque;
2501 #if defined(DEBUG_SUBPAGE)
2502 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2503 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2504 #endif
2506 return address_space_access_valid(subpage->as, addr + subpage->base,
2507 len, is_write);
2510 static const MemoryRegionOps subpage_ops = {
2511 .read_with_attrs = subpage_read,
2512 .write_with_attrs = subpage_write,
2513 .impl.min_access_size = 1,
2514 .impl.max_access_size = 8,
2515 .valid.min_access_size = 1,
2516 .valid.max_access_size = 8,
2517 .valid.accepts = subpage_accepts,
2518 .endianness = DEVICE_NATIVE_ENDIAN,
2521 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
2522 uint16_t section)
2524 int idx, eidx;
2526 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2527 return -1;
2528 idx = SUBPAGE_IDX(start);
2529 eidx = SUBPAGE_IDX(end);
2530 #if defined(DEBUG_SUBPAGE)
2531 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2532 __func__, mmio, start, end, idx, eidx, section);
2533 #endif
2534 for (; idx <= eidx; idx++) {
2535 mmio->sub_section[idx] = section;
2538 return 0;
2541 static subpage_t *subpage_init(AddressSpace *as, hwaddr base)
2543 subpage_t *mmio;
2545 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2546 mmio->as = as;
2547 mmio->base = base;
2548 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2549 NULL, TARGET_PAGE_SIZE);
2550 mmio->iomem.subpage = true;
2551 #if defined(DEBUG_SUBPAGE)
2552 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2553 mmio, base, TARGET_PAGE_SIZE);
2554 #endif
2555 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
2557 return mmio;
2560 static uint16_t dummy_section(PhysPageMap *map, AddressSpace *as,
2561 MemoryRegion *mr)
2563 assert(as);
2564 MemoryRegionSection section = {
2565 .address_space = as,
2566 .mr = mr,
2567 .offset_within_address_space = 0,
2568 .offset_within_region = 0,
2569 .size = int128_2_64(),
2572 return phys_section_add(map, &section);
2575 MemoryRegion *iotlb_to_region(CPUState *cpu, hwaddr index, MemTxAttrs attrs)
2577 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2578 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2579 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
2580 MemoryRegionSection *sections = d->map.sections;
2582 return sections[index & ~TARGET_PAGE_MASK].mr;
2585 static void io_mem_init(void)
2587 memory_region_init_io(&io_mem_rom, NULL, &unassigned_mem_ops, NULL, NULL, UINT64_MAX);
2588 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2589 NULL, UINT64_MAX);
2591 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
2592 * which can be called without the iothread mutex.
2594 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
2595 NULL, UINT64_MAX);
2596 memory_region_clear_global_locking(&io_mem_notdirty);
2598 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
2599 NULL, UINT64_MAX);
2602 static void mem_begin(MemoryListener *listener)
2604 AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
2605 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2606 uint16_t n;
2608 n = dummy_section(&d->map, as, &io_mem_unassigned);
2609 assert(n == PHYS_SECTION_UNASSIGNED);
2610 n = dummy_section(&d->map, as, &io_mem_notdirty);
2611 assert(n == PHYS_SECTION_NOTDIRTY);
2612 n = dummy_section(&d->map, as, &io_mem_rom);
2613 assert(n == PHYS_SECTION_ROM);
2614 n = dummy_section(&d->map, as, &io_mem_watch);
2615 assert(n == PHYS_SECTION_WATCH);
2617 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2618 d->as = as;
2619 as->next_dispatch = d;
2622 static void address_space_dispatch_free(AddressSpaceDispatch *d)
2624 phys_sections_free(&d->map);
2625 g_free(d);
2628 static void mem_commit(MemoryListener *listener)
2630 AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
2631 AddressSpaceDispatch *cur = as->dispatch;
2632 AddressSpaceDispatch *next = as->next_dispatch;
2634 phys_page_compact_all(next, next->map.nodes_nb);
2636 atomic_rcu_set(&as->dispatch, next);
2637 if (cur) {
2638 call_rcu(cur, address_space_dispatch_free, rcu);
2642 static void tcg_commit(MemoryListener *listener)
2644 CPUAddressSpace *cpuas;
2645 AddressSpaceDispatch *d;
2647 /* since each CPU stores ram addresses in its TLB cache, we must
2648 reset the modified entries */
2649 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2650 cpu_reloading_memory_map();
2651 /* The CPU and TLB are protected by the iothread lock.
2652 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2653 * may have split the RCU critical section.
2655 d = atomic_rcu_read(&cpuas->as->dispatch);
2656 atomic_rcu_set(&cpuas->memory_dispatch, d);
2657 tlb_flush(cpuas->cpu);
2660 void address_space_init_dispatch(AddressSpace *as)
2662 as->dispatch = NULL;
2663 as->dispatch_listener = (MemoryListener) {
2664 .begin = mem_begin,
2665 .commit = mem_commit,
2666 .region_add = mem_add,
2667 .region_nop = mem_add,
2668 .priority = 0,
2670 memory_listener_register(&as->dispatch_listener, as);
2673 void address_space_unregister(AddressSpace *as)
2675 memory_listener_unregister(&as->dispatch_listener);
2678 void address_space_destroy_dispatch(AddressSpace *as)
2680 AddressSpaceDispatch *d = as->dispatch;
2682 atomic_rcu_set(&as->dispatch, NULL);
2683 if (d) {
2684 call_rcu(d, address_space_dispatch_free, rcu);
2688 static void memory_map_init(void)
2690 system_memory = g_malloc(sizeof(*system_memory));
2692 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2693 address_space_init(&address_space_memory, system_memory, "memory");
2695 system_io = g_malloc(sizeof(*system_io));
2696 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2697 65536);
2698 address_space_init(&address_space_io, system_io, "I/O");
2701 MemoryRegion *get_system_memory(void)
2703 return system_memory;
2706 MemoryRegion *get_system_io(void)
2708 return system_io;
2711 #endif /* !defined(CONFIG_USER_ONLY) */
2713 /* physical memory access (slow version, mainly for debug) */
2714 #if defined(CONFIG_USER_ONLY)
2715 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
2716 uint8_t *buf, int len, int is_write)
2718 int l, flags;
2719 target_ulong page;
2720 void * p;
2722 while (len > 0) {
2723 page = addr & TARGET_PAGE_MASK;
2724 l = (page + TARGET_PAGE_SIZE) - addr;
2725 if (l > len)
2726 l = len;
2727 flags = page_get_flags(page);
2728 if (!(flags & PAGE_VALID))
2729 return -1;
2730 if (is_write) {
2731 if (!(flags & PAGE_WRITE))
2732 return -1;
2733 /* XXX: this code should not depend on lock_user */
2734 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
2735 return -1;
2736 memcpy(p, buf, l);
2737 unlock_user(p, addr, l);
2738 } else {
2739 if (!(flags & PAGE_READ))
2740 return -1;
2741 /* XXX: this code should not depend on lock_user */
2742 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
2743 return -1;
2744 memcpy(buf, p, l);
2745 unlock_user(p, addr, 0);
2747 len -= l;
2748 buf += l;
2749 addr += l;
2751 return 0;
2754 #else
2756 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2757 hwaddr length)
2759 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2760 addr += memory_region_get_ram_addr(mr);
2762 /* No early return if dirty_log_mask is or becomes 0, because
2763 * cpu_physical_memory_set_dirty_range will still call
2764 * xen_modified_memory.
2766 if (dirty_log_mask) {
2767 dirty_log_mask =
2768 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2770 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2771 tb_lock();
2772 tb_invalidate_phys_range(addr, addr + length);
2773 tb_unlock();
2774 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2776 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2779 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2781 unsigned access_size_max = mr->ops->valid.max_access_size;
2783 /* Regions are assumed to support 1-4 byte accesses unless
2784 otherwise specified. */
2785 if (access_size_max == 0) {
2786 access_size_max = 4;
2789 /* Bound the maximum access by the alignment of the address. */
2790 if (!mr->ops->impl.unaligned) {
2791 unsigned align_size_max = addr & -addr;
2792 if (align_size_max != 0 && align_size_max < access_size_max) {
2793 access_size_max = align_size_max;
2797 /* Don't attempt accesses larger than the maximum. */
2798 if (l > access_size_max) {
2799 l = access_size_max;
2801 l = pow2floor(l);
2803 return l;
2806 static bool prepare_mmio_access(MemoryRegion *mr)
2808 bool unlocked = !qemu_mutex_iothread_locked();
2809 bool release_lock = false;
2811 if (unlocked && mr->global_locking) {
2812 qemu_mutex_lock_iothread();
2813 unlocked = false;
2814 release_lock = true;
2816 if (mr->flush_coalesced_mmio) {
2817 if (unlocked) {
2818 qemu_mutex_lock_iothread();
2820 qemu_flush_coalesced_mmio_buffer();
2821 if (unlocked) {
2822 qemu_mutex_unlock_iothread();
2826 return release_lock;
2829 /* Called within RCU critical section. */
2830 static MemTxResult address_space_write_continue(AddressSpace *as, hwaddr addr,
2831 MemTxAttrs attrs,
2832 const uint8_t *buf,
2833 int len, hwaddr addr1,
2834 hwaddr l, MemoryRegion *mr)
2836 uint8_t *ptr;
2837 uint64_t val;
2838 MemTxResult result = MEMTX_OK;
2839 bool release_lock = false;
2841 for (;;) {
2842 if (!memory_access_is_direct(mr, true)) {
2843 release_lock |= prepare_mmio_access(mr);
2844 l = memory_access_size(mr, l, addr1);
2845 /* XXX: could force current_cpu to NULL to avoid
2846 potential bugs */
2847 switch (l) {
2848 case 8:
2849 /* 64 bit write access */
2850 val = ldq_p(buf);
2851 result |= memory_region_dispatch_write(mr, addr1, val, 8,
2852 attrs);
2853 break;
2854 case 4:
2855 /* 32 bit write access */
2856 val = (uint32_t)ldl_p(buf);
2857 result |= memory_region_dispatch_write(mr, addr1, val, 4,
2858 attrs);
2859 break;
2860 case 2:
2861 /* 16 bit write access */
2862 val = lduw_p(buf);
2863 result |= memory_region_dispatch_write(mr, addr1, val, 2,
2864 attrs);
2865 break;
2866 case 1:
2867 /* 8 bit write access */
2868 val = ldub_p(buf);
2869 result |= memory_region_dispatch_write(mr, addr1, val, 1,
2870 attrs);
2871 break;
2872 default:
2873 abort();
2875 } else {
2876 /* RAM case */
2877 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2878 memcpy(ptr, buf, l);
2879 invalidate_and_set_dirty(mr, addr1, l);
2882 if (release_lock) {
2883 qemu_mutex_unlock_iothread();
2884 release_lock = false;
2887 len -= l;
2888 buf += l;
2889 addr += l;
2891 if (!len) {
2892 break;
2895 l = len;
2896 mr = address_space_translate(as, addr, &addr1, &l, true);
2899 return result;
2902 MemTxResult address_space_write(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2903 const uint8_t *buf, int len)
2905 hwaddr l;
2906 hwaddr addr1;
2907 MemoryRegion *mr;
2908 MemTxResult result = MEMTX_OK;
2910 if (len > 0) {
2911 rcu_read_lock();
2912 l = len;
2913 mr = address_space_translate(as, addr, &addr1, &l, true);
2914 result = address_space_write_continue(as, addr, attrs, buf, len,
2915 addr1, l, mr);
2916 rcu_read_unlock();
2919 return result;
2922 /* Called within RCU critical section. */
2923 MemTxResult address_space_read_continue(AddressSpace *as, hwaddr addr,
2924 MemTxAttrs attrs, uint8_t *buf,
2925 int len, hwaddr addr1, hwaddr l,
2926 MemoryRegion *mr)
2928 uint8_t *ptr;
2929 uint64_t val;
2930 MemTxResult result = MEMTX_OK;
2931 bool release_lock = false;
2933 for (;;) {
2934 if (!memory_access_is_direct(mr, false)) {
2935 /* I/O case */
2936 release_lock |= prepare_mmio_access(mr);
2937 l = memory_access_size(mr, l, addr1);
2938 switch (l) {
2939 case 8:
2940 /* 64 bit read access */
2941 result |= memory_region_dispatch_read(mr, addr1, &val, 8,
2942 attrs);
2943 stq_p(buf, val);
2944 break;
2945 case 4:
2946 /* 32 bit read access */
2947 result |= memory_region_dispatch_read(mr, addr1, &val, 4,
2948 attrs);
2949 stl_p(buf, val);
2950 break;
2951 case 2:
2952 /* 16 bit read access */
2953 result |= memory_region_dispatch_read(mr, addr1, &val, 2,
2954 attrs);
2955 stw_p(buf, val);
2956 break;
2957 case 1:
2958 /* 8 bit read access */
2959 result |= memory_region_dispatch_read(mr, addr1, &val, 1,
2960 attrs);
2961 stb_p(buf, val);
2962 break;
2963 default:
2964 abort();
2966 } else {
2967 /* RAM case */
2968 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2969 memcpy(buf, ptr, l);
2972 if (release_lock) {
2973 qemu_mutex_unlock_iothread();
2974 release_lock = false;
2977 len -= l;
2978 buf += l;
2979 addr += l;
2981 if (!len) {
2982 break;
2985 l = len;
2986 mr = address_space_translate(as, addr, &addr1, &l, false);
2989 return result;
2992 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2993 MemTxAttrs attrs, uint8_t *buf, int len)
2995 hwaddr l;
2996 hwaddr addr1;
2997 MemoryRegion *mr;
2998 MemTxResult result = MEMTX_OK;
3000 if (len > 0) {
3001 rcu_read_lock();
3002 l = len;
3003 mr = address_space_translate(as, addr, &addr1, &l, false);
3004 result = address_space_read_continue(as, addr, attrs, buf, len,
3005 addr1, l, mr);
3006 rcu_read_unlock();
3009 return result;
3012 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3013 uint8_t *buf, int len, bool is_write)
3015 if (is_write) {
3016 return address_space_write(as, addr, attrs, (uint8_t *)buf, len);
3017 } else {
3018 return address_space_read(as, addr, attrs, (uint8_t *)buf, len);
3022 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
3023 int len, int is_write)
3025 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3026 buf, len, is_write);
3029 enum write_rom_type {
3030 WRITE_DATA,
3031 FLUSH_CACHE,
3034 static inline void cpu_physical_memory_write_rom_internal(AddressSpace *as,
3035 hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
3037 hwaddr l;
3038 uint8_t *ptr;
3039 hwaddr addr1;
3040 MemoryRegion *mr;
3042 rcu_read_lock();
3043 while (len > 0) {
3044 l = len;
3045 mr = address_space_translate(as, addr, &addr1, &l, true);
3047 if (!(memory_region_is_ram(mr) ||
3048 memory_region_is_romd(mr))) {
3049 l = memory_access_size(mr, l, addr1);
3050 } else {
3051 /* ROM/RAM case */
3052 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3053 switch (type) {
3054 case WRITE_DATA:
3055 memcpy(ptr, buf, l);
3056 invalidate_and_set_dirty(mr, addr1, l);
3057 break;
3058 case FLUSH_CACHE:
3059 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
3060 break;
3063 len -= l;
3064 buf += l;
3065 addr += l;
3067 rcu_read_unlock();
3070 /* used for ROM loading : can write in RAM and ROM */
3071 void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
3072 const uint8_t *buf, int len)
3074 cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
3077 void cpu_flush_icache_range(hwaddr start, int len)
3080 * This function should do the same thing as an icache flush that was
3081 * triggered from within the guest. For TCG we are always cache coherent,
3082 * so there is no need to flush anything. For KVM / Xen we need to flush
3083 * the host's instruction cache at least.
3085 if (tcg_enabled()) {
3086 return;
3089 cpu_physical_memory_write_rom_internal(&address_space_memory,
3090 start, NULL, len, FLUSH_CACHE);
3093 typedef struct {
3094 MemoryRegion *mr;
3095 void *buffer;
3096 hwaddr addr;
3097 hwaddr len;
3098 bool in_use;
3099 } BounceBuffer;
3101 static BounceBuffer bounce;
3103 typedef struct MapClient {
3104 QEMUBH *bh;
3105 QLIST_ENTRY(MapClient) link;
3106 } MapClient;
3108 QemuMutex map_client_list_lock;
3109 static QLIST_HEAD(map_client_list, MapClient) map_client_list
3110 = QLIST_HEAD_INITIALIZER(map_client_list);
3112 static void cpu_unregister_map_client_do(MapClient *client)
3114 QLIST_REMOVE(client, link);
3115 g_free(client);
3118 static void cpu_notify_map_clients_locked(void)
3120 MapClient *client;
3122 while (!QLIST_EMPTY(&map_client_list)) {
3123 client = QLIST_FIRST(&map_client_list);
3124 qemu_bh_schedule(client->bh);
3125 cpu_unregister_map_client_do(client);
3129 void cpu_register_map_client(QEMUBH *bh)
3131 MapClient *client = g_malloc(sizeof(*client));
3133 qemu_mutex_lock(&map_client_list_lock);
3134 client->bh = bh;
3135 QLIST_INSERT_HEAD(&map_client_list, client, link);
3136 if (!atomic_read(&bounce.in_use)) {
3137 cpu_notify_map_clients_locked();
3139 qemu_mutex_unlock(&map_client_list_lock);
3142 void cpu_exec_init_all(void)
3144 qemu_mutex_init(&ram_list.mutex);
3145 /* The data structures we set up here depend on knowing the page size,
3146 * so no more changes can be made after this point.
3147 * In an ideal world, nothing we did before we had finished the
3148 * machine setup would care about the target page size, and we could
3149 * do this much later, rather than requiring board models to state
3150 * up front what their requirements are.
3152 finalize_target_page_bits();
3153 io_mem_init();
3154 memory_map_init();
3155 qemu_mutex_init(&map_client_list_lock);
3158 void cpu_unregister_map_client(QEMUBH *bh)
3160 MapClient *client;
3162 qemu_mutex_lock(&map_client_list_lock);
3163 QLIST_FOREACH(client, &map_client_list, link) {
3164 if (client->bh == bh) {
3165 cpu_unregister_map_client_do(client);
3166 break;
3169 qemu_mutex_unlock(&map_client_list_lock);
3172 static void cpu_notify_map_clients(void)
3174 qemu_mutex_lock(&map_client_list_lock);
3175 cpu_notify_map_clients_locked();
3176 qemu_mutex_unlock(&map_client_list_lock);
3179 bool address_space_access_valid(AddressSpace *as, hwaddr addr, int len, bool is_write)
3181 MemoryRegion *mr;
3182 hwaddr l, xlat;
3184 rcu_read_lock();
3185 while (len > 0) {
3186 l = len;
3187 mr = address_space_translate(as, addr, &xlat, &l, is_write);
3188 if (!memory_access_is_direct(mr, is_write)) {
3189 l = memory_access_size(mr, l, addr);
3190 if (!memory_region_access_valid(mr, xlat, l, is_write)) {
3191 rcu_read_unlock();
3192 return false;
3196 len -= l;
3197 addr += l;
3199 rcu_read_unlock();
3200 return true;
3203 static hwaddr
3204 address_space_extend_translation(AddressSpace *as, hwaddr addr, hwaddr target_len,
3205 MemoryRegion *mr, hwaddr base, hwaddr len,
3206 bool is_write)
3208 hwaddr done = 0;
3209 hwaddr xlat;
3210 MemoryRegion *this_mr;
3212 for (;;) {
3213 target_len -= len;
3214 addr += len;
3215 done += len;
3216 if (target_len == 0) {
3217 return done;
3220 len = target_len;
3221 this_mr = address_space_translate(as, addr, &xlat, &len, is_write);
3222 if (this_mr != mr || xlat != base + done) {
3223 return done;
3228 /* Map a physical memory region into a host virtual address.
3229 * May map a subset of the requested range, given by and returned in *plen.
3230 * May return NULL if resources needed to perform the mapping are exhausted.
3231 * Use only for reads OR writes - not for read-modify-write operations.
3232 * Use cpu_register_map_client() to know when retrying the map operation is
3233 * likely to succeed.
3235 void *address_space_map(AddressSpace *as,
3236 hwaddr addr,
3237 hwaddr *plen,
3238 bool is_write)
3240 hwaddr len = *plen;
3241 hwaddr l, xlat;
3242 MemoryRegion *mr;
3243 void *ptr;
3245 if (len == 0) {
3246 return NULL;
3249 l = len;
3250 rcu_read_lock();
3251 mr = address_space_translate(as, addr, &xlat, &l, is_write);
3253 if (!memory_access_is_direct(mr, is_write)) {
3254 if (atomic_xchg(&bounce.in_use, true)) {
3255 rcu_read_unlock();
3256 return NULL;
3258 /* Avoid unbounded allocations */
3259 l = MIN(l, TARGET_PAGE_SIZE);
3260 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3261 bounce.addr = addr;
3262 bounce.len = l;
3264 memory_region_ref(mr);
3265 bounce.mr = mr;
3266 if (!is_write) {
3267 address_space_read(as, addr, MEMTXATTRS_UNSPECIFIED,
3268 bounce.buffer, l);
3271 rcu_read_unlock();
3272 *plen = l;
3273 return bounce.buffer;
3277 memory_region_ref(mr);
3278 *plen = address_space_extend_translation(as, addr, len, mr, xlat, l, is_write);
3279 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen);
3280 rcu_read_unlock();
3282 return ptr;
3285 /* Unmaps a memory region previously mapped by address_space_map().
3286 * Will also mark the memory as dirty if is_write == 1. access_len gives
3287 * the amount of memory that was actually read or written by the caller.
3289 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3290 int is_write, hwaddr access_len)
3292 if (buffer != bounce.buffer) {
3293 MemoryRegion *mr;
3294 ram_addr_t addr1;
3296 mr = memory_region_from_host(buffer, &addr1);
3297 assert(mr != NULL);
3298 if (is_write) {
3299 invalidate_and_set_dirty(mr, addr1, access_len);
3301 if (xen_enabled()) {
3302 xen_invalidate_map_cache_entry(buffer);
3304 memory_region_unref(mr);
3305 return;
3307 if (is_write) {
3308 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3309 bounce.buffer, access_len);
3311 qemu_vfree(bounce.buffer);
3312 bounce.buffer = NULL;
3313 memory_region_unref(bounce.mr);
3314 atomic_mb_set(&bounce.in_use, false);
3315 cpu_notify_map_clients();
3318 void *cpu_physical_memory_map(hwaddr addr,
3319 hwaddr *plen,
3320 int is_write)
3322 return address_space_map(&address_space_memory, addr, plen, is_write);
3325 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3326 int is_write, hwaddr access_len)
3328 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3331 #define ARG1_DECL AddressSpace *as
3332 #define ARG1 as
3333 #define SUFFIX
3334 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3335 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3336 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3337 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3338 #define RCU_READ_LOCK(...) rcu_read_lock()
3339 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3340 #include "memory_ldst.inc.c"
3342 int64_t address_space_cache_init(MemoryRegionCache *cache,
3343 AddressSpace *as,
3344 hwaddr addr,
3345 hwaddr len,
3346 bool is_write)
3348 cache->len = len;
3349 cache->as = as;
3350 cache->xlat = addr;
3351 return len;
3354 void address_space_cache_invalidate(MemoryRegionCache *cache,
3355 hwaddr addr,
3356 hwaddr access_len)
3360 void address_space_cache_destroy(MemoryRegionCache *cache)
3362 cache->as = NULL;
3365 #define ARG1_DECL MemoryRegionCache *cache
3366 #define ARG1 cache
3367 #define SUFFIX _cached
3368 #define TRANSLATE(addr, ...) \
3369 address_space_translate(cache->as, cache->xlat + (addr), __VA_ARGS__)
3370 #define IS_DIRECT(mr, is_write) true
3371 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3372 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3373 #define RCU_READ_LOCK() rcu_read_lock()
3374 #define RCU_READ_UNLOCK() rcu_read_unlock()
3375 #include "memory_ldst.inc.c"
3377 /* virtual memory access for debug (includes writing to ROM) */
3378 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3379 uint8_t *buf, int len, int is_write)
3381 int l;
3382 hwaddr phys_addr;
3383 target_ulong page;
3385 cpu_synchronize_state(cpu);
3386 while (len > 0) {
3387 int asidx;
3388 MemTxAttrs attrs;
3390 page = addr & TARGET_PAGE_MASK;
3391 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3392 asidx = cpu_asidx_from_attrs(cpu, attrs);
3393 /* if no physical page mapped, return an error */
3394 if (phys_addr == -1)
3395 return -1;
3396 l = (page + TARGET_PAGE_SIZE) - addr;
3397 if (l > len)
3398 l = len;
3399 phys_addr += (addr & ~TARGET_PAGE_MASK);
3400 if (is_write) {
3401 cpu_physical_memory_write_rom(cpu->cpu_ases[asidx].as,
3402 phys_addr, buf, l);
3403 } else {
3404 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3405 MEMTXATTRS_UNSPECIFIED,
3406 buf, l, 0);
3408 len -= l;
3409 buf += l;
3410 addr += l;
3412 return 0;
3416 * Allows code that needs to deal with migration bitmaps etc to still be built
3417 * target independent.
3419 size_t qemu_target_page_size(void)
3421 return TARGET_PAGE_SIZE;
3424 #endif
3427 * A helper function for the _utterly broken_ virtio device model to find out if
3428 * it's running on a big endian machine. Don't do this at home kids!
3430 bool target_words_bigendian(void);
3431 bool target_words_bigendian(void)
3433 #if defined(TARGET_WORDS_BIGENDIAN)
3434 return true;
3435 #else
3436 return false;
3437 #endif
3440 #ifndef CONFIG_USER_ONLY
3441 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3443 MemoryRegion*mr;
3444 hwaddr l = 1;
3445 bool res;
3447 rcu_read_lock();
3448 mr = address_space_translate(&address_space_memory,
3449 phys_addr, &phys_addr, &l, false);
3451 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3452 rcu_read_unlock();
3453 return res;
3456 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3458 RAMBlock *block;
3459 int ret = 0;
3461 rcu_read_lock();
3462 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
3463 ret = func(block->idstr, block->host, block->offset,
3464 block->used_length, opaque);
3465 if (ret) {
3466 break;
3469 rcu_read_unlock();
3470 return ret;
3474 * Unmap pages of memory from start to start+length such that
3475 * they a) read as 0, b) Trigger whatever fault mechanism
3476 * the OS provides for postcopy.
3477 * The pages must be unmapped by the end of the function.
3478 * Returns: 0 on success, none-0 on failure
3481 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3483 int ret = -1;
3485 uint8_t *host_startaddr = rb->host + start;
3487 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
3488 error_report("ram_block_discard_range: Unaligned start address: %p",
3489 host_startaddr);
3490 goto err;
3493 if ((start + length) <= rb->used_length) {
3494 uint8_t *host_endaddr = host_startaddr + length;
3495 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
3496 error_report("ram_block_discard_range: Unaligned end address: %p",
3497 host_endaddr);
3498 goto err;
3501 errno = ENOTSUP; /* If we are missing MADVISE etc */
3503 if (rb->page_size == qemu_host_page_size) {
3504 #if defined(CONFIG_MADVISE)
3505 /* Note: We need the madvise MADV_DONTNEED behaviour of definitely
3506 * freeing the page.
3508 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3509 #endif
3510 } else {
3511 /* Huge page case - unfortunately it can't do DONTNEED, but
3512 * it can do the equivalent by FALLOC_FL_PUNCH_HOLE in the
3513 * huge page file.
3515 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3516 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3517 start, length);
3518 #endif
3520 if (ret) {
3521 ret = -errno;
3522 error_report("ram_block_discard_range: Failed to discard range "
3523 "%s:%" PRIx64 " +%zx (%d)",
3524 rb->idstr, start, length, ret);
3526 } else {
3527 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3528 "/%zx/" RAM_ADDR_FMT")",
3529 rb->idstr, start, length, rb->used_length);
3532 err:
3533 return ret;
3536 #endif