Create empty dummy file "loaders.cache" (bug #1766841)
[qemu/ar7.git] / exec.c
blob3590e1f37946fbdc37d196789100c2440fad0ff8
1 /*
2 * Virtual page mapping
4 * Copyright (c) 2003 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 #include "qemu/osdep.h"
20 #include "qapi/error.h"
22 #include "qemu/cutils.h"
23 #include "cpu.h"
24 #include "exec/exec-all.h"
25 #include "exec/target_page.h"
26 #include "tcg.h"
27 #include "hw/qdev-core.h"
28 #include "hw/qdev-properties.h"
29 #if !defined(CONFIG_USER_ONLY)
30 #include "hw/boards.h"
31 #include "hw/xen/xen.h"
32 #endif
33 #include "sysemu/kvm.h"
34 #include "sysemu/sysemu.h"
35 #include "qemu/timer.h"
36 #include "qemu/config-file.h"
37 #include "qemu/error-report.h"
38 #if defined(CONFIG_USER_ONLY)
39 #include "qemu.h"
40 #else /* !CONFIG_USER_ONLY */
41 #include "hw/hw.h"
42 #include "exec/memory.h"
43 #include "exec/ioport.h"
44 #include "sysemu/dma.h"
45 #include "sysemu/numa.h"
46 #include "sysemu/hw_accel.h"
47 #include "exec/address-spaces.h"
48 #include "sysemu/xen-mapcache.h"
49 #include "trace-root.h"
51 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
52 #include <linux/falloc.h>
53 #endif
55 #endif
56 #include "qemu/rcu_queue.h"
57 #include "qemu/main-loop.h"
58 #include "translate-all.h"
59 #include "sysemu/replay.h"
61 #include "exec/memory-internal.h"
62 #include "exec/ram_addr.h"
63 #include "exec/log.h"
65 #include "migration/vmstate.h"
67 #include "qemu/range.h"
68 #ifndef _WIN32
69 #include "qemu/mmap-alloc.h"
70 #endif
72 #include "monitor/monitor.h"
74 //#define DEBUG_SUBPAGE
76 #if !defined(CONFIG_USER_ONLY)
77 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
78 * are protected by the ramlist lock.
80 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
82 static MemoryRegion *system_memory;
83 static MemoryRegion *system_io;
85 AddressSpace address_space_io;
86 AddressSpace address_space_memory;
88 MemoryRegion io_mem_rom, io_mem_notdirty;
89 static MemoryRegion io_mem_unassigned;
91 /* RAM is pre-allocated and passed into qemu_ram_alloc_from_ptr */
92 #define RAM_PREALLOC (1 << 0)
94 /* RAM is mmap-ed with MAP_SHARED */
95 #define RAM_SHARED (1 << 1)
97 /* Only a portion of RAM (used_length) is actually used, and migrated.
98 * This used_length size can change across reboots.
100 #define RAM_RESIZEABLE (1 << 2)
102 /* UFFDIO_ZEROPAGE is available on this RAMBlock to atomically
103 * zero the page and wake waiting processes.
104 * (Set during postcopy)
106 #define RAM_UF_ZEROPAGE (1 << 3)
107 #endif
109 #ifdef TARGET_PAGE_BITS_VARY
110 int target_page_bits;
111 bool target_page_bits_decided;
112 #endif
114 struct CPUTailQ cpus = QTAILQ_HEAD_INITIALIZER(cpus);
115 /* current CPU in the current thread. It is only valid inside
116 cpu_exec() */
117 __thread CPUState *current_cpu;
118 /* 0 = Do not count executed instructions.
119 1 = Precise instruction counting.
120 2 = Adaptive rate instruction counting. */
121 int use_icount;
123 uintptr_t qemu_host_page_size;
124 intptr_t qemu_host_page_mask;
126 bool set_preferred_target_page_bits(int bits)
128 /* The target page size is the lowest common denominator for all
129 * the CPUs in the system, so we can only make it smaller, never
130 * larger. And we can't make it smaller once we've committed to
131 * a particular size.
133 #ifdef TARGET_PAGE_BITS_VARY
134 assert(bits >= TARGET_PAGE_BITS_MIN);
135 if (target_page_bits == 0 || target_page_bits > bits) {
136 if (target_page_bits_decided) {
137 return false;
139 target_page_bits = bits;
141 #endif
142 return true;
145 #if !defined(CONFIG_USER_ONLY)
147 static void finalize_target_page_bits(void)
149 #ifdef TARGET_PAGE_BITS_VARY
150 if (target_page_bits == 0) {
151 target_page_bits = TARGET_PAGE_BITS_MIN;
153 target_page_bits_decided = true;
154 #endif
157 typedef struct PhysPageEntry PhysPageEntry;
159 struct PhysPageEntry {
160 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
161 uint32_t skip : 6;
162 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
163 uint32_t ptr : 26;
166 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
168 /* Size of the L2 (and L3, etc) page tables. */
169 #define ADDR_SPACE_BITS 64
171 #define P_L2_BITS 9
172 #define P_L2_SIZE (1 << P_L2_BITS)
174 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
176 typedef PhysPageEntry Node[P_L2_SIZE];
178 typedef struct PhysPageMap {
179 struct rcu_head rcu;
181 unsigned sections_nb;
182 unsigned sections_nb_alloc;
183 unsigned nodes_nb;
184 unsigned nodes_nb_alloc;
185 Node *nodes;
186 MemoryRegionSection *sections;
187 } PhysPageMap;
189 struct AddressSpaceDispatch {
190 MemoryRegionSection *mru_section;
191 /* This is a multi-level map on the physical address space.
192 * The bottom level has pointers to MemoryRegionSections.
194 PhysPageEntry phys_map;
195 PhysPageMap map;
198 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
199 typedef struct subpage_t {
200 MemoryRegion iomem;
201 FlatView *fv;
202 hwaddr base;
203 uint16_t sub_section[];
204 } subpage_t;
206 #define PHYS_SECTION_UNASSIGNED 0
207 #define PHYS_SECTION_NOTDIRTY 1
208 #define PHYS_SECTION_ROM 2
209 #define PHYS_SECTION_WATCH 3
211 static void io_mem_init(void);
212 static void memory_map_init(void);
213 static void tcg_commit(MemoryListener *listener);
215 static MemoryRegion io_mem_watch;
218 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
219 * @cpu: the CPU whose AddressSpace this is
220 * @as: the AddressSpace itself
221 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
222 * @tcg_as_listener: listener for tracking changes to the AddressSpace
224 struct CPUAddressSpace {
225 CPUState *cpu;
226 AddressSpace *as;
227 struct AddressSpaceDispatch *memory_dispatch;
228 MemoryListener tcg_as_listener;
231 struct DirtyBitmapSnapshot {
232 ram_addr_t start;
233 ram_addr_t end;
234 unsigned long dirty[];
237 #endif
239 #if !defined(CONFIG_USER_ONLY)
241 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
243 static unsigned alloc_hint = 16;
244 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
245 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, alloc_hint);
246 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, map->nodes_nb + nodes);
247 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
248 alloc_hint = map->nodes_nb_alloc;
252 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
254 unsigned i;
255 uint32_t ret;
256 PhysPageEntry e;
257 PhysPageEntry *p;
259 ret = map->nodes_nb++;
260 p = map->nodes[ret];
261 assert(ret != PHYS_MAP_NODE_NIL);
262 assert(ret != map->nodes_nb_alloc);
264 e.skip = leaf ? 0 : 1;
265 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
266 for (i = 0; i < P_L2_SIZE; ++i) {
267 memcpy(&p[i], &e, sizeof(e));
269 return ret;
272 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
273 hwaddr *index, hwaddr *nb, uint16_t leaf,
274 int level)
276 PhysPageEntry *p;
277 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
279 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
280 lp->ptr = phys_map_node_alloc(map, level == 0);
282 p = map->nodes[lp->ptr];
283 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
285 while (*nb && lp < &p[P_L2_SIZE]) {
286 if ((*index & (step - 1)) == 0 && *nb >= step) {
287 lp->skip = 0;
288 lp->ptr = leaf;
289 *index += step;
290 *nb -= step;
291 } else {
292 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
294 ++lp;
298 static void phys_page_set(AddressSpaceDispatch *d,
299 hwaddr index, hwaddr nb,
300 uint16_t leaf)
302 /* Wildly overreserve - it doesn't matter much. */
303 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
305 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
308 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
309 * and update our entry so we can skip it and go directly to the destination.
311 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
313 unsigned valid_ptr = P_L2_SIZE;
314 int valid = 0;
315 PhysPageEntry *p;
316 int i;
318 if (lp->ptr == PHYS_MAP_NODE_NIL) {
319 return;
322 p = nodes[lp->ptr];
323 for (i = 0; i < P_L2_SIZE; i++) {
324 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
325 continue;
328 valid_ptr = i;
329 valid++;
330 if (p[i].skip) {
331 phys_page_compact(&p[i], nodes);
335 /* We can only compress if there's only one child. */
336 if (valid != 1) {
337 return;
340 assert(valid_ptr < P_L2_SIZE);
342 /* Don't compress if it won't fit in the # of bits we have. */
343 if (lp->skip + p[valid_ptr].skip >= (1 << 3)) {
344 return;
347 lp->ptr = p[valid_ptr].ptr;
348 if (!p[valid_ptr].skip) {
349 /* If our only child is a leaf, make this a leaf. */
350 /* By design, we should have made this node a leaf to begin with so we
351 * should never reach here.
352 * But since it's so simple to handle this, let's do it just in case we
353 * change this rule.
355 lp->skip = 0;
356 } else {
357 lp->skip += p[valid_ptr].skip;
361 void address_space_dispatch_compact(AddressSpaceDispatch *d)
363 if (d->phys_map.skip) {
364 phys_page_compact(&d->phys_map, d->map.nodes);
368 static inline bool section_covers_addr(const MemoryRegionSection *section,
369 hwaddr addr)
371 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
372 * the section must cover the entire address space.
374 return int128_gethi(section->size) ||
375 range_covers_byte(section->offset_within_address_space,
376 int128_getlo(section->size), addr);
379 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
381 PhysPageEntry lp = d->phys_map, *p;
382 Node *nodes = d->map.nodes;
383 MemoryRegionSection *sections = d->map.sections;
384 hwaddr index = addr >> TARGET_PAGE_BITS;
385 int i;
387 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
388 if (lp.ptr == PHYS_MAP_NODE_NIL) {
389 return &sections[PHYS_SECTION_UNASSIGNED];
391 p = nodes[lp.ptr];
392 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
395 if (section_covers_addr(&sections[lp.ptr], addr)) {
396 return &sections[lp.ptr];
397 } else {
398 return &sections[PHYS_SECTION_UNASSIGNED];
402 bool memory_region_is_unassigned(MemoryRegion *mr)
404 return mr != &io_mem_rom && mr != &io_mem_notdirty && !mr->rom_device
405 && mr != &io_mem_watch;
408 /* Called from RCU critical section */
409 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
410 hwaddr addr,
411 bool resolve_subpage)
413 MemoryRegionSection *section = atomic_read(&d->mru_section);
414 subpage_t *subpage;
416 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
417 !section_covers_addr(section, addr)) {
418 section = phys_page_find(d, addr);
419 atomic_set(&d->mru_section, section);
421 if (resolve_subpage && section->mr->subpage) {
422 subpage = container_of(section->mr, subpage_t, iomem);
423 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
425 return section;
428 /* Called from RCU critical section */
429 static MemoryRegionSection *
430 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
431 hwaddr *plen, bool resolve_subpage)
433 MemoryRegionSection *section;
434 MemoryRegion *mr;
435 Int128 diff;
437 section = address_space_lookup_region(d, addr, resolve_subpage);
438 /* Compute offset within MemoryRegionSection */
439 addr -= section->offset_within_address_space;
441 /* Compute offset within MemoryRegion */
442 *xlat = addr + section->offset_within_region;
444 mr = section->mr;
446 /* MMIO registers can be expected to perform full-width accesses based only
447 * on their address, without considering adjacent registers that could
448 * decode to completely different MemoryRegions. When such registers
449 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
450 * regions overlap wildly. For this reason we cannot clamp the accesses
451 * here.
453 * If the length is small (as is the case for address_space_ldl/stl),
454 * everything works fine. If the incoming length is large, however,
455 * the caller really has to do the clamping through memory_access_size.
457 if (memory_region_is_ram(mr)) {
458 diff = int128_sub(section->size, int128_make64(addr));
459 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
461 return section;
465 * flatview_do_translate - translate an address in FlatView
467 * @fv: the flat view that we want to translate on
468 * @addr: the address to be translated in above address space
469 * @xlat: the translated address offset within memory region. It
470 * cannot be @NULL.
471 * @plen_out: valid read/write length of the translated address. It
472 * can be @NULL when we don't care about it.
473 * @page_mask_out: page mask for the translated address. This
474 * should only be meaningful for IOMMU translated
475 * addresses, since there may be huge pages that this bit
476 * would tell. It can be @NULL if we don't care about it.
477 * @is_write: whether the translation operation is for write
478 * @is_mmio: whether this can be MMIO, set true if it can
480 * This function is called from RCU critical section
482 static MemoryRegionSection flatview_do_translate(FlatView *fv,
483 hwaddr addr,
484 hwaddr *xlat,
485 hwaddr *plen_out,
486 hwaddr *page_mask_out,
487 bool is_write,
488 bool is_mmio,
489 AddressSpace **target_as)
491 IOMMUTLBEntry iotlb;
492 MemoryRegionSection *section;
493 IOMMUMemoryRegion *iommu_mr;
494 IOMMUMemoryRegionClass *imrc;
495 hwaddr page_mask = (hwaddr)(-1);
496 hwaddr plen = (hwaddr)(-1);
498 if (plen_out) {
499 plen = *plen_out;
502 for (;;) {
503 section = address_space_translate_internal(
504 flatview_to_dispatch(fv), addr, &addr,
505 &plen, is_mmio);
507 iommu_mr = memory_region_get_iommu(section->mr);
508 if (!iommu_mr) {
509 break;
511 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
513 iotlb = imrc->translate(iommu_mr, addr, is_write ?
514 IOMMU_WO : IOMMU_RO);
515 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
516 | (addr & iotlb.addr_mask));
517 page_mask &= iotlb.addr_mask;
518 plen = MIN(plen, (addr | iotlb.addr_mask) - addr + 1);
519 if (!(iotlb.perm & (1 << is_write))) {
520 goto translate_fail;
523 fv = address_space_to_flatview(iotlb.target_as);
524 *target_as = iotlb.target_as;
527 *xlat = addr;
529 if (page_mask == (hwaddr)(-1)) {
530 /* Not behind an IOMMU, use default page size. */
531 page_mask = ~TARGET_PAGE_MASK;
534 if (page_mask_out) {
535 *page_mask_out = page_mask;
538 if (plen_out) {
539 *plen_out = plen;
542 return *section;
544 translate_fail:
545 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
548 /* Called from RCU critical section */
549 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
550 bool is_write)
552 MemoryRegionSection section;
553 hwaddr xlat, page_mask;
556 * This can never be MMIO, and we don't really care about plen,
557 * but page mask.
559 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
560 NULL, &page_mask, is_write, false, &as);
562 /* Illegal translation */
563 if (section.mr == &io_mem_unassigned) {
564 goto iotlb_fail;
567 /* Convert memory region offset into address space offset */
568 xlat += section.offset_within_address_space -
569 section.offset_within_region;
571 return (IOMMUTLBEntry) {
572 .target_as = as,
573 .iova = addr & ~page_mask,
574 .translated_addr = xlat & ~page_mask,
575 .addr_mask = page_mask,
576 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
577 .perm = IOMMU_RW,
580 iotlb_fail:
581 return (IOMMUTLBEntry) {0};
584 /* Called from RCU critical section */
585 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
586 hwaddr *plen, bool is_write)
588 MemoryRegion *mr;
589 MemoryRegionSection section;
590 AddressSpace *as = NULL;
592 /* This can be MMIO, so setup MMIO bit. */
593 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
594 is_write, true, &as);
595 mr = section.mr;
597 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
598 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
599 *plen = MIN(page, *plen);
602 return mr;
605 /* Called from RCU critical section */
606 MemoryRegionSection *
607 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
608 hwaddr *xlat, hwaddr *plen)
610 MemoryRegionSection *section;
611 AddressSpaceDispatch *d = atomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
613 section = address_space_translate_internal(d, addr, xlat, plen, false);
615 assert(!memory_region_is_iommu(section->mr));
616 return section;
618 #endif
620 #if !defined(CONFIG_USER_ONLY)
622 static int cpu_common_post_load(void *opaque, int version_id)
624 CPUState *cpu = opaque;
626 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
627 version_id is increased. */
628 cpu->interrupt_request &= ~0x01;
629 tlb_flush(cpu);
631 /* loadvm has just updated the content of RAM, bypassing the
632 * usual mechanisms that ensure we flush TBs for writes to
633 * memory we've translated code from. So we must flush all TBs,
634 * which will now be stale.
636 tb_flush(cpu);
638 return 0;
641 static int cpu_common_pre_load(void *opaque)
643 CPUState *cpu = opaque;
645 cpu->exception_index = -1;
647 return 0;
650 static bool cpu_common_exception_index_needed(void *opaque)
652 CPUState *cpu = opaque;
654 return tcg_enabled() && cpu->exception_index != -1;
657 static const VMStateDescription vmstate_cpu_common_exception_index = {
658 .name = "cpu_common/exception_index",
659 .version_id = 1,
660 .minimum_version_id = 1,
661 .needed = cpu_common_exception_index_needed,
662 .fields = (VMStateField[]) {
663 VMSTATE_INT32(exception_index, CPUState),
664 VMSTATE_END_OF_LIST()
668 static bool cpu_common_crash_occurred_needed(void *opaque)
670 CPUState *cpu = opaque;
672 return cpu->crash_occurred;
675 static const VMStateDescription vmstate_cpu_common_crash_occurred = {
676 .name = "cpu_common/crash_occurred",
677 .version_id = 1,
678 .minimum_version_id = 1,
679 .needed = cpu_common_crash_occurred_needed,
680 .fields = (VMStateField[]) {
681 VMSTATE_BOOL(crash_occurred, CPUState),
682 VMSTATE_END_OF_LIST()
686 const VMStateDescription vmstate_cpu_common = {
687 .name = "cpu_common",
688 .version_id = 1,
689 .minimum_version_id = 1,
690 .pre_load = cpu_common_pre_load,
691 .post_load = cpu_common_post_load,
692 .fields = (VMStateField[]) {
693 VMSTATE_UINT32(halted, CPUState),
694 VMSTATE_UINT32(interrupt_request, CPUState),
695 VMSTATE_END_OF_LIST()
697 .subsections = (const VMStateDescription*[]) {
698 &vmstate_cpu_common_exception_index,
699 &vmstate_cpu_common_crash_occurred,
700 NULL
704 #endif
706 CPUState *qemu_get_cpu(int index)
708 CPUState *cpu;
710 CPU_FOREACH(cpu) {
711 if (cpu->cpu_index == index) {
712 return cpu;
716 return NULL;
719 #if !defined(CONFIG_USER_ONLY)
720 void cpu_address_space_init(CPUState *cpu, int asidx,
721 const char *prefix, MemoryRegion *mr)
723 CPUAddressSpace *newas;
724 AddressSpace *as = g_new0(AddressSpace, 1);
725 char *as_name;
727 assert(mr);
728 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
729 address_space_init(as, mr, as_name);
730 g_free(as_name);
732 /* Target code should have set num_ases before calling us */
733 assert(asidx < cpu->num_ases);
735 if (asidx == 0) {
736 /* address space 0 gets the convenience alias */
737 cpu->as = as;
740 /* KVM cannot currently support multiple address spaces. */
741 assert(asidx == 0 || !kvm_enabled());
743 if (!cpu->cpu_ases) {
744 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
747 newas = &cpu->cpu_ases[asidx];
748 newas->cpu = cpu;
749 newas->as = as;
750 if (tcg_enabled()) {
751 newas->tcg_as_listener.commit = tcg_commit;
752 memory_listener_register(&newas->tcg_as_listener, as);
756 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
758 /* Return the AddressSpace corresponding to the specified index */
759 return cpu->cpu_ases[asidx].as;
761 #endif
763 void cpu_exec_unrealizefn(CPUState *cpu)
765 CPUClass *cc = CPU_GET_CLASS(cpu);
767 cpu_list_remove(cpu);
769 if (cc->vmsd != NULL) {
770 vmstate_unregister(NULL, cc->vmsd, cpu);
772 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
773 vmstate_unregister(NULL, &vmstate_cpu_common, cpu);
777 Property cpu_common_props[] = {
778 #ifndef CONFIG_USER_ONLY
779 /* Create a memory property for softmmu CPU object,
780 * so users can wire up its memory. (This can't go in qom/cpu.c
781 * because that file is compiled only once for both user-mode
782 * and system builds.) The default if no link is set up is to use
783 * the system address space.
785 DEFINE_PROP_LINK("memory", CPUState, memory, TYPE_MEMORY_REGION,
786 MemoryRegion *),
787 #endif
788 DEFINE_PROP_END_OF_LIST(),
791 void cpu_exec_initfn(CPUState *cpu)
793 #ifdef TARGET_WORDS_BIGENDIAN
794 cpu->bigendian = true;
795 #else
796 cpu->bigendian = false;
797 #endif
798 cpu->as = NULL;
799 cpu->num_ases = 0;
801 #ifndef CONFIG_USER_ONLY
802 cpu->thread_id = qemu_get_thread_id();
803 cpu->memory = system_memory;
804 object_ref(OBJECT(cpu->memory));
805 #endif
808 void cpu_exec_realizefn(CPUState *cpu, Error **errp)
810 CPUClass *cc = CPU_GET_CLASS(cpu);
811 static bool tcg_target_initialized;
813 cpu_list_add(cpu);
815 if (tcg_enabled() && !tcg_target_initialized) {
816 tcg_target_initialized = true;
817 cc->tcg_initialize();
820 #ifndef CONFIG_USER_ONLY
821 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
822 vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
824 if (cc->vmsd != NULL) {
825 vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);
827 #endif
830 const char *parse_cpu_model(const char *cpu_model)
832 ObjectClass *oc;
833 CPUClass *cc;
834 gchar **model_pieces;
835 const char *cpu_type;
837 model_pieces = g_strsplit(cpu_model, ",", 2);
839 oc = cpu_class_by_name(CPU_RESOLVING_TYPE, model_pieces[0]);
840 if (oc == NULL) {
841 error_report("unable to find CPU model '%s'", model_pieces[0]);
842 g_strfreev(model_pieces);
843 exit(EXIT_FAILURE);
846 cpu_type = object_class_get_name(oc);
847 cc = CPU_CLASS(oc);
848 cc->parse_features(cpu_type, model_pieces[1], &error_fatal);
849 g_strfreev(model_pieces);
850 return cpu_type;
853 #if defined(CONFIG_USER_ONLY)
854 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
856 mmap_lock();
857 tb_lock();
858 tb_invalidate_phys_page_range(pc, pc + 1, 0);
859 tb_unlock();
860 mmap_unlock();
862 #else
863 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
865 MemTxAttrs attrs;
866 hwaddr phys = cpu_get_phys_page_attrs_debug(cpu, pc, &attrs);
867 int asidx = cpu_asidx_from_attrs(cpu, attrs);
868 if (phys != -1) {
869 /* Locks grabbed by tb_invalidate_phys_addr */
870 tb_invalidate_phys_addr(cpu->cpu_ases[asidx].as,
871 phys | (pc & ~TARGET_PAGE_MASK));
874 #endif
876 #if defined(CONFIG_USER_ONLY)
877 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
882 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
883 int flags)
885 return -ENOSYS;
888 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
892 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
893 int flags, CPUWatchpoint **watchpoint)
895 return -ENOSYS;
897 #else
898 /* Add a watchpoint. */
899 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
900 int flags, CPUWatchpoint **watchpoint)
902 CPUWatchpoint *wp;
904 /* forbid ranges which are empty or run off the end of the address space */
905 if (len == 0 || (addr + len - 1) < addr) {
906 error_report("tried to set invalid watchpoint at %"
907 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
908 return -EINVAL;
910 wp = g_malloc(sizeof(*wp));
912 wp->vaddr = addr;
913 wp->len = len;
914 wp->flags = flags;
916 /* keep all GDB-injected watchpoints in front */
917 if (flags & BP_GDB) {
918 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
919 } else {
920 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
923 tlb_flush_page(cpu, addr);
925 if (watchpoint)
926 *watchpoint = wp;
927 return 0;
930 /* Remove a specific watchpoint. */
931 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
932 int flags)
934 CPUWatchpoint *wp;
936 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
937 if (addr == wp->vaddr && len == wp->len
938 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
939 cpu_watchpoint_remove_by_ref(cpu, wp);
940 return 0;
943 return -ENOENT;
946 /* Remove a specific watchpoint by reference. */
947 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
949 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
951 tlb_flush_page(cpu, watchpoint->vaddr);
953 g_free(watchpoint);
956 /* Remove all matching watchpoints. */
957 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
959 CPUWatchpoint *wp, *next;
961 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
962 if (wp->flags & mask) {
963 cpu_watchpoint_remove_by_ref(cpu, wp);
968 /* Return true if this watchpoint address matches the specified
969 * access (ie the address range covered by the watchpoint overlaps
970 * partially or completely with the address range covered by the
971 * access).
973 static inline bool cpu_watchpoint_address_matches(CPUWatchpoint *wp,
974 vaddr addr,
975 vaddr len)
977 /* We know the lengths are non-zero, but a little caution is
978 * required to avoid errors in the case where the range ends
979 * exactly at the top of the address space and so addr + len
980 * wraps round to zero.
982 vaddr wpend = wp->vaddr + wp->len - 1;
983 vaddr addrend = addr + len - 1;
985 return !(addr > wpend || wp->vaddr > addrend);
988 #endif
990 /* Add a breakpoint. */
991 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
992 CPUBreakpoint **breakpoint)
994 CPUBreakpoint *bp;
996 bp = g_malloc(sizeof(*bp));
998 bp->pc = pc;
999 bp->flags = flags;
1001 /* keep all GDB-injected breakpoints in front */
1002 if (flags & BP_GDB) {
1003 QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
1004 } else {
1005 QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
1008 breakpoint_invalidate(cpu, pc);
1010 if (breakpoint) {
1011 *breakpoint = bp;
1013 return 0;
1016 /* Remove a specific breakpoint. */
1017 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
1019 CPUBreakpoint *bp;
1021 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
1022 if (bp->pc == pc && bp->flags == flags) {
1023 cpu_breakpoint_remove_by_ref(cpu, bp);
1024 return 0;
1027 return -ENOENT;
1030 /* Remove a specific breakpoint by reference. */
1031 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
1033 QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);
1035 breakpoint_invalidate(cpu, breakpoint->pc);
1037 g_free(breakpoint);
1040 /* Remove all matching breakpoints. */
1041 void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
1043 CPUBreakpoint *bp, *next;
1045 QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
1046 if (bp->flags & mask) {
1047 cpu_breakpoint_remove_by_ref(cpu, bp);
1052 /* enable or disable single step mode. EXCP_DEBUG is returned by the
1053 CPU loop after each instruction */
1054 void cpu_single_step(CPUState *cpu, int enabled)
1056 if (cpu->singlestep_enabled != enabled) {
1057 cpu->singlestep_enabled = enabled;
1058 if (kvm_enabled()) {
1059 kvm_update_guest_debug(cpu, 0);
1060 } else {
1061 /* must flush all the translated code to avoid inconsistencies */
1062 /* XXX: only flush what is necessary */
1063 tb_flush(cpu);
1068 void QEMU_NORETURN cpu_abort(CPUState *cpu, const char *fmt, ...)
1070 va_list ap;
1071 va_list ap2;
1073 va_start(ap, fmt);
1074 va_copy(ap2, ap);
1075 fprintf(stderr, "qemu: fatal: ");
1076 vfprintf(stderr, fmt, ap);
1077 fprintf(stderr, "\n");
1078 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1079 if (qemu_log_separate()) {
1080 qemu_log_lock();
1081 qemu_log("qemu: fatal: ");
1082 qemu_log_vprintf(fmt, ap2);
1083 qemu_log("\n");
1084 log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1085 qemu_log_flush();
1086 qemu_log_unlock();
1087 qemu_log_close();
1089 va_end(ap2);
1090 va_end(ap);
1091 replay_finish();
1092 #if defined(CONFIG_USER_ONLY)
1094 struct sigaction act;
1095 sigfillset(&act.sa_mask);
1096 act.sa_handler = SIG_DFL;
1097 sigaction(SIGABRT, &act, NULL);
1099 #endif
1100 abort();
1103 #if !defined(CONFIG_USER_ONLY)
1104 /* Called from RCU critical section */
1105 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
1107 RAMBlock *block;
1109 block = atomic_rcu_read(&ram_list.mru_block);
1110 if (block && addr - block->offset < block->max_length) {
1111 return block;
1113 RAMBLOCK_FOREACH(block) {
1114 if (addr - block->offset < block->max_length) {
1115 goto found;
1119 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1120 abort();
1122 found:
1123 /* It is safe to write mru_block outside the iothread lock. This
1124 * is what happens:
1126 * mru_block = xxx
1127 * rcu_read_unlock()
1128 * xxx removed from list
1129 * rcu_read_lock()
1130 * read mru_block
1131 * mru_block = NULL;
1132 * call_rcu(reclaim_ramblock, xxx);
1133 * rcu_read_unlock()
1135 * atomic_rcu_set is not needed here. The block was already published
1136 * when it was placed into the list. Here we're just making an extra
1137 * copy of the pointer.
1139 ram_list.mru_block = block;
1140 return block;
1143 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1145 CPUState *cpu;
1146 ram_addr_t start1;
1147 RAMBlock *block;
1148 ram_addr_t end;
1150 end = TARGET_PAGE_ALIGN(start + length);
1151 start &= TARGET_PAGE_MASK;
1153 rcu_read_lock();
1154 block = qemu_get_ram_block(start);
1155 assert(block == qemu_get_ram_block(end - 1));
1156 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1157 CPU_FOREACH(cpu) {
1158 tlb_reset_dirty(cpu, start1, length);
1160 rcu_read_unlock();
1163 /* Note: start and end must be within the same ram block. */
1164 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1165 ram_addr_t length,
1166 unsigned client)
1168 DirtyMemoryBlocks *blocks;
1169 unsigned long end, page;
1170 bool dirty = false;
1172 if (length == 0) {
1173 return false;
1176 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1177 page = start >> TARGET_PAGE_BITS;
1179 rcu_read_lock();
1181 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1183 while (page < end) {
1184 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1185 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1186 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1188 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1189 offset, num);
1190 page += num;
1193 rcu_read_unlock();
1195 if (dirty && tcg_enabled()) {
1196 tlb_reset_dirty_range_all(start, length);
1199 return dirty;
1202 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1203 (ram_addr_t start, ram_addr_t length, unsigned client)
1205 DirtyMemoryBlocks *blocks;
1206 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1207 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1208 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1209 DirtyBitmapSnapshot *snap;
1210 unsigned long page, end, dest;
1212 snap = g_malloc0(sizeof(*snap) +
1213 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1214 snap->start = first;
1215 snap->end = last;
1217 page = first >> TARGET_PAGE_BITS;
1218 end = last >> TARGET_PAGE_BITS;
1219 dest = 0;
1221 rcu_read_lock();
1223 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1225 while (page < end) {
1226 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1227 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1228 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1230 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1231 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1232 offset >>= BITS_PER_LEVEL;
1234 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1235 blocks->blocks[idx] + offset,
1236 num);
1237 page += num;
1238 dest += num >> BITS_PER_LEVEL;
1241 rcu_read_unlock();
1243 if (tcg_enabled()) {
1244 tlb_reset_dirty_range_all(start, length);
1247 return snap;
1250 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1251 ram_addr_t start,
1252 ram_addr_t length)
1254 unsigned long page, end;
1256 assert(start >= snap->start);
1257 assert(start + length <= snap->end);
1259 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1260 page = (start - snap->start) >> TARGET_PAGE_BITS;
1262 while (page < end) {
1263 if (test_bit(page, snap->dirty)) {
1264 return true;
1266 page++;
1268 return false;
1271 /* Called from RCU critical section */
1272 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1273 MemoryRegionSection *section,
1274 target_ulong vaddr,
1275 hwaddr paddr, hwaddr xlat,
1276 int prot,
1277 target_ulong *address)
1279 hwaddr iotlb;
1280 CPUWatchpoint *wp;
1282 if (memory_region_is_ram(section->mr)) {
1283 /* Normal RAM. */
1284 iotlb = memory_region_get_ram_addr(section->mr) + xlat;
1285 if (!section->readonly) {
1286 iotlb |= PHYS_SECTION_NOTDIRTY;
1287 } else {
1288 iotlb |= PHYS_SECTION_ROM;
1290 } else {
1291 AddressSpaceDispatch *d;
1293 d = flatview_to_dispatch(section->fv);
1294 iotlb = section - d->map.sections;
1295 iotlb += xlat;
1298 /* Make accesses to pages with watchpoints go via the
1299 watchpoint trap routines. */
1300 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1301 if (cpu_watchpoint_address_matches(wp, vaddr, TARGET_PAGE_SIZE)) {
1302 /* Avoid trapping reads of pages with a write breakpoint. */
1303 if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
1304 iotlb = PHYS_SECTION_WATCH + paddr;
1305 *address |= TLB_MMIO;
1306 break;
1311 return iotlb;
1313 #endif /* defined(CONFIG_USER_ONLY) */
1315 #if !defined(CONFIG_USER_ONLY)
1317 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
1318 uint16_t section);
1319 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1321 static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
1322 qemu_anon_ram_alloc;
1325 * Set a custom physical guest memory alloator.
1326 * Accelerators with unusual needs may need this. Hopefully, we can
1327 * get rid of it eventually.
1329 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
1331 phys_mem_alloc = alloc;
1334 static uint16_t phys_section_add(PhysPageMap *map,
1335 MemoryRegionSection *section)
1337 /* The physical section number is ORed with a page-aligned
1338 * pointer to produce the iotlb entries. Thus it should
1339 * never overflow into the page-aligned value.
1341 assert(map->sections_nb < TARGET_PAGE_SIZE);
1343 if (map->sections_nb == map->sections_nb_alloc) {
1344 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1345 map->sections = g_renew(MemoryRegionSection, map->sections,
1346 map->sections_nb_alloc);
1348 map->sections[map->sections_nb] = *section;
1349 memory_region_ref(section->mr);
1350 return map->sections_nb++;
1353 static void phys_section_destroy(MemoryRegion *mr)
1355 bool have_sub_page = mr->subpage;
1357 memory_region_unref(mr);
1359 if (have_sub_page) {
1360 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1361 object_unref(OBJECT(&subpage->iomem));
1362 g_free(subpage);
1366 static void phys_sections_free(PhysPageMap *map)
1368 while (map->sections_nb > 0) {
1369 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1370 phys_section_destroy(section->mr);
1372 g_free(map->sections);
1373 g_free(map->nodes);
1376 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1378 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1379 subpage_t *subpage;
1380 hwaddr base = section->offset_within_address_space
1381 & TARGET_PAGE_MASK;
1382 MemoryRegionSection *existing = phys_page_find(d, base);
1383 MemoryRegionSection subsection = {
1384 .offset_within_address_space = base,
1385 .size = int128_make64(TARGET_PAGE_SIZE),
1387 hwaddr start, end;
1389 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1391 if (!(existing->mr->subpage)) {
1392 subpage = subpage_init(fv, base);
1393 subsection.fv = fv;
1394 subsection.mr = &subpage->iomem;
1395 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1396 phys_section_add(&d->map, &subsection));
1397 } else {
1398 subpage = container_of(existing->mr, subpage_t, iomem);
1400 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1401 end = start + int128_get64(section->size) - 1;
1402 subpage_register(subpage, start, end,
1403 phys_section_add(&d->map, section));
1407 static void register_multipage(FlatView *fv,
1408 MemoryRegionSection *section)
1410 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1411 hwaddr start_addr = section->offset_within_address_space;
1412 uint16_t section_index = phys_section_add(&d->map, section);
1413 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1414 TARGET_PAGE_BITS));
1416 assert(num_pages);
1417 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1420 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1422 MemoryRegionSection now = *section, remain = *section;
1423 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1425 if (now.offset_within_address_space & ~TARGET_PAGE_MASK) {
1426 uint64_t left = TARGET_PAGE_ALIGN(now.offset_within_address_space)
1427 - now.offset_within_address_space;
1429 now.size = int128_min(int128_make64(left), now.size);
1430 register_subpage(fv, &now);
1431 } else {
1432 now.size = int128_zero();
1434 while (int128_ne(remain.size, now.size)) {
1435 remain.size = int128_sub(remain.size, now.size);
1436 remain.offset_within_address_space += int128_get64(now.size);
1437 remain.offset_within_region += int128_get64(now.size);
1438 now = remain;
1439 if (int128_lt(remain.size, page_size)) {
1440 register_subpage(fv, &now);
1441 } else if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1442 now.size = page_size;
1443 register_subpage(fv, &now);
1444 } else {
1445 now.size = int128_and(now.size, int128_neg(page_size));
1446 register_multipage(fv, &now);
1451 void qemu_flush_coalesced_mmio_buffer(void)
1453 if (kvm_enabled())
1454 kvm_flush_coalesced_mmio_buffer();
1457 void qemu_mutex_lock_ramlist(void)
1459 qemu_mutex_lock(&ram_list.mutex);
1462 void qemu_mutex_unlock_ramlist(void)
1464 qemu_mutex_unlock(&ram_list.mutex);
1467 void ram_block_dump(Monitor *mon)
1469 RAMBlock *block;
1470 char *psize;
1472 rcu_read_lock();
1473 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1474 "Block Name", "PSize", "Offset", "Used", "Total");
1475 RAMBLOCK_FOREACH(block) {
1476 psize = size_to_str(block->page_size);
1477 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1478 " 0x%016" PRIx64 "\n", block->idstr, psize,
1479 (uint64_t)block->offset,
1480 (uint64_t)block->used_length,
1481 (uint64_t)block->max_length);
1482 g_free(psize);
1484 rcu_read_unlock();
1487 #ifdef __linux__
1489 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1490 * may or may not name the same files / on the same filesystem now as
1491 * when we actually open and map them. Iterate over the file
1492 * descriptors instead, and use qemu_fd_getpagesize().
1494 static int find_max_supported_pagesize(Object *obj, void *opaque)
1496 char *mem_path;
1497 long *hpsize_min = opaque;
1499 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1500 mem_path = object_property_get_str(obj, "mem-path", NULL);
1501 if (mem_path) {
1502 long hpsize = qemu_mempath_getpagesize(mem_path);
1503 g_free(mem_path);
1504 if (hpsize < *hpsize_min) {
1505 *hpsize_min = hpsize;
1507 } else {
1508 *hpsize_min = getpagesize();
1512 return 0;
1515 long qemu_getrampagesize(void)
1517 long hpsize = LONG_MAX;
1518 long mainrampagesize;
1519 Object *memdev_root;
1521 if (mem_path) {
1522 mainrampagesize = qemu_mempath_getpagesize(mem_path);
1523 } else {
1524 mainrampagesize = getpagesize();
1527 /* it's possible we have memory-backend objects with
1528 * hugepage-backed RAM. these may get mapped into system
1529 * address space via -numa parameters or memory hotplug
1530 * hooks. we want to take these into account, but we
1531 * also want to make sure these supported hugepage
1532 * sizes are applicable across the entire range of memory
1533 * we may boot from, so we take the min across all
1534 * backends, and assume normal pages in cases where a
1535 * backend isn't backed by hugepages.
1537 memdev_root = object_resolve_path("/objects", NULL);
1538 if (memdev_root) {
1539 object_child_foreach(memdev_root, find_max_supported_pagesize, &hpsize);
1541 if (hpsize == LONG_MAX) {
1542 /* No additional memory regions found ==> Report main RAM page size */
1543 return mainrampagesize;
1546 /* If NUMA is disabled or the NUMA nodes are not backed with a
1547 * memory-backend, then there is at least one node using "normal" RAM,
1548 * so if its page size is smaller we have got to report that size instead.
1550 if (hpsize > mainrampagesize &&
1551 (nb_numa_nodes == 0 || numa_info[0].node_memdev == NULL)) {
1552 static bool warned;
1553 if (!warned) {
1554 error_report("Huge page support disabled (n/a for main memory).");
1555 warned = true;
1557 return mainrampagesize;
1560 return hpsize;
1562 #else
1563 long qemu_getrampagesize(void)
1565 return getpagesize();
1567 #endif
1569 #ifdef __linux__
1570 static int64_t get_file_size(int fd)
1572 int64_t size = lseek(fd, 0, SEEK_END);
1573 if (size < 0) {
1574 return -errno;
1576 return size;
1579 static int file_ram_open(const char *path,
1580 const char *region_name,
1581 bool *created,
1582 Error **errp)
1584 char *filename;
1585 char *sanitized_name;
1586 char *c;
1587 int fd = -1;
1589 *created = false;
1590 for (;;) {
1591 fd = open(path, O_RDWR);
1592 if (fd >= 0) {
1593 /* @path names an existing file, use it */
1594 break;
1596 if (errno == ENOENT) {
1597 /* @path names a file that doesn't exist, create it */
1598 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1599 if (fd >= 0) {
1600 *created = true;
1601 break;
1603 } else if (errno == EISDIR) {
1604 /* @path names a directory, create a file there */
1605 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1606 sanitized_name = g_strdup(region_name);
1607 for (c = sanitized_name; *c != '\0'; c++) {
1608 if (*c == '/') {
1609 *c = '_';
1613 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1614 sanitized_name);
1615 g_free(sanitized_name);
1617 fd = mkstemp(filename);
1618 if (fd >= 0) {
1619 unlink(filename);
1620 g_free(filename);
1621 break;
1623 g_free(filename);
1625 if (errno != EEXIST && errno != EINTR) {
1626 error_setg_errno(errp, errno,
1627 "can't open backing store %s for guest RAM",
1628 path);
1629 return -1;
1632 * Try again on EINTR and EEXIST. The latter happens when
1633 * something else creates the file between our two open().
1637 return fd;
1640 static void *file_ram_alloc(RAMBlock *block,
1641 ram_addr_t memory,
1642 int fd,
1643 bool truncate,
1644 Error **errp)
1646 void *area;
1648 block->page_size = qemu_fd_getpagesize(fd);
1649 if (block->mr->align % block->page_size) {
1650 error_setg(errp, "alignment 0x%" PRIx64
1651 " must be multiples of page size 0x%zx",
1652 block->mr->align, block->page_size);
1653 return NULL;
1655 block->mr->align = MAX(block->page_size, block->mr->align);
1656 #if defined(__s390x__)
1657 if (kvm_enabled()) {
1658 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1660 #endif
1662 if (memory < block->page_size) {
1663 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1664 "or larger than page size 0x%zx",
1665 memory, block->page_size);
1666 return NULL;
1669 memory = ROUND_UP(memory, block->page_size);
1672 * ftruncate is not supported by hugetlbfs in older
1673 * hosts, so don't bother bailing out on errors.
1674 * If anything goes wrong with it under other filesystems,
1675 * mmap will fail.
1677 * Do not truncate the non-empty backend file to avoid corrupting
1678 * the existing data in the file. Disabling shrinking is not
1679 * enough. For example, the current vNVDIMM implementation stores
1680 * the guest NVDIMM labels at the end of the backend file. If the
1681 * backend file is later extended, QEMU will not be able to find
1682 * those labels. Therefore, extending the non-empty backend file
1683 * is disabled as well.
1685 if (truncate && ftruncate(fd, memory)) {
1686 perror("ftruncate");
1689 area = qemu_ram_mmap(fd, memory, block->mr->align,
1690 block->flags & RAM_SHARED);
1691 if (area == MAP_FAILED) {
1692 error_setg_errno(errp, errno,
1693 "unable to map backing store for guest RAM");
1694 return NULL;
1697 if (mem_prealloc) {
1698 os_mem_prealloc(fd, area, memory, smp_cpus, errp);
1699 if (errp && *errp) {
1700 qemu_ram_munmap(area, memory);
1701 return NULL;
1705 block->fd = fd;
1706 return area;
1708 #endif
1710 /* Allocate space within the ram_addr_t space that governs the
1711 * dirty bitmaps.
1712 * Called with the ramlist lock held.
1714 static ram_addr_t find_ram_offset(ram_addr_t size)
1716 RAMBlock *block, *next_block;
1717 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1719 assert(size != 0); /* it would hand out same offset multiple times */
1721 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1722 return 0;
1725 RAMBLOCK_FOREACH(block) {
1726 ram_addr_t candidate, next = RAM_ADDR_MAX;
1728 /* Align blocks to start on a 'long' in the bitmap
1729 * which makes the bitmap sync'ing take the fast path.
1731 candidate = block->offset + block->max_length;
1732 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1734 /* Search for the closest following block
1735 * and find the gap.
1737 RAMBLOCK_FOREACH(next_block) {
1738 if (next_block->offset >= candidate) {
1739 next = MIN(next, next_block->offset);
1743 /* If it fits remember our place and remember the size
1744 * of gap, but keep going so that we might find a smaller
1745 * gap to fill so avoiding fragmentation.
1747 if (next - candidate >= size && next - candidate < mingap) {
1748 offset = candidate;
1749 mingap = next - candidate;
1752 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1755 if (offset == RAM_ADDR_MAX) {
1756 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1757 (uint64_t)size);
1758 abort();
1761 trace_find_ram_offset(size, offset);
1763 return offset;
1766 unsigned long last_ram_page(void)
1768 RAMBlock *block;
1769 ram_addr_t last = 0;
1771 rcu_read_lock();
1772 RAMBLOCK_FOREACH(block) {
1773 last = MAX(last, block->offset + block->max_length);
1775 rcu_read_unlock();
1776 return last >> TARGET_PAGE_BITS;
1779 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1781 int ret;
1783 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1784 if (!machine_dump_guest_core(current_machine)) {
1785 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1786 if (ret) {
1787 perror("qemu_madvise");
1788 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1789 "but dump_guest_core=off specified\n");
1794 const char *qemu_ram_get_idstr(RAMBlock *rb)
1796 return rb->idstr;
1799 bool qemu_ram_is_shared(RAMBlock *rb)
1801 return rb->flags & RAM_SHARED;
1804 /* Note: Only set at the start of postcopy */
1805 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1807 return rb->flags & RAM_UF_ZEROPAGE;
1810 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1812 rb->flags |= RAM_UF_ZEROPAGE;
1815 /* Called with iothread lock held. */
1816 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1818 RAMBlock *block;
1820 assert(new_block);
1821 assert(!new_block->idstr[0]);
1823 if (dev) {
1824 char *id = qdev_get_dev_path(dev);
1825 if (id) {
1826 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1827 g_free(id);
1830 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1832 rcu_read_lock();
1833 RAMBLOCK_FOREACH(block) {
1834 if (block != new_block &&
1835 !strcmp(block->idstr, new_block->idstr)) {
1836 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1837 new_block->idstr);
1838 abort();
1841 rcu_read_unlock();
1844 /* Called with iothread lock held. */
1845 void qemu_ram_unset_idstr(RAMBlock *block)
1847 /* FIXME: arch_init.c assumes that this is not called throughout
1848 * migration. Ignore the problem since hot-unplug during migration
1849 * does not work anyway.
1851 if (block) {
1852 memset(block->idstr, 0, sizeof(block->idstr));
1856 size_t qemu_ram_pagesize(RAMBlock *rb)
1858 return rb->page_size;
1861 /* Returns the largest size of page in use */
1862 size_t qemu_ram_pagesize_largest(void)
1864 RAMBlock *block;
1865 size_t largest = 0;
1867 RAMBLOCK_FOREACH(block) {
1868 largest = MAX(largest, qemu_ram_pagesize(block));
1871 return largest;
1874 static int memory_try_enable_merging(void *addr, size_t len)
1876 if (!machine_mem_merge(current_machine)) {
1877 /* disabled by the user */
1878 return 0;
1881 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1884 /* Only legal before guest might have detected the memory size: e.g. on
1885 * incoming migration, or right after reset.
1887 * As memory core doesn't know how is memory accessed, it is up to
1888 * resize callback to update device state and/or add assertions to detect
1889 * misuse, if necessary.
1891 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1893 assert(block);
1895 newsize = HOST_PAGE_ALIGN(newsize);
1897 if (block->used_length == newsize) {
1898 return 0;
1901 if (!(block->flags & RAM_RESIZEABLE)) {
1902 error_setg_errno(errp, EINVAL,
1903 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1904 " in != 0x" RAM_ADDR_FMT, block->idstr,
1905 newsize, block->used_length);
1906 return -EINVAL;
1909 if (block->max_length < newsize) {
1910 error_setg_errno(errp, EINVAL,
1911 "Length too large: %s: 0x" RAM_ADDR_FMT
1912 " > 0x" RAM_ADDR_FMT, block->idstr,
1913 newsize, block->max_length);
1914 return -EINVAL;
1917 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1918 block->used_length = newsize;
1919 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1920 DIRTY_CLIENTS_ALL);
1921 memory_region_set_size(block->mr, newsize);
1922 if (block->resized) {
1923 block->resized(block->idstr, newsize, block->host);
1925 return 0;
1928 /* Called with ram_list.mutex held */
1929 static void dirty_memory_extend(ram_addr_t old_ram_size,
1930 ram_addr_t new_ram_size)
1932 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1933 DIRTY_MEMORY_BLOCK_SIZE);
1934 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1935 DIRTY_MEMORY_BLOCK_SIZE);
1936 int i;
1938 /* Only need to extend if block count increased */
1939 if (new_num_blocks <= old_num_blocks) {
1940 return;
1943 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1944 DirtyMemoryBlocks *old_blocks;
1945 DirtyMemoryBlocks *new_blocks;
1946 int j;
1948 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
1949 new_blocks = g_malloc(sizeof(*new_blocks) +
1950 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1952 if (old_num_blocks) {
1953 memcpy(new_blocks->blocks, old_blocks->blocks,
1954 old_num_blocks * sizeof(old_blocks->blocks[0]));
1957 for (j = old_num_blocks; j < new_num_blocks; j++) {
1958 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1961 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1963 if (old_blocks) {
1964 g_free_rcu(old_blocks, rcu);
1969 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
1971 RAMBlock *block;
1972 RAMBlock *last_block = NULL;
1973 ram_addr_t old_ram_size, new_ram_size;
1974 Error *err = NULL;
1976 old_ram_size = last_ram_page();
1978 qemu_mutex_lock_ramlist();
1979 new_block->offset = find_ram_offset(new_block->max_length);
1981 if (!new_block->host) {
1982 if (xen_enabled()) {
1983 xen_ram_alloc(new_block->offset, new_block->max_length,
1984 new_block->mr, &err);
1985 if (err) {
1986 error_propagate(errp, err);
1987 qemu_mutex_unlock_ramlist();
1988 return;
1990 } else {
1991 new_block->host = phys_mem_alloc(new_block->max_length,
1992 &new_block->mr->align, shared);
1993 if (!new_block->host) {
1994 error_setg_errno(errp, errno,
1995 "cannot set up guest memory '%s'",
1996 memory_region_name(new_block->mr));
1997 qemu_mutex_unlock_ramlist();
1998 return;
2000 memory_try_enable_merging(new_block->host, new_block->max_length);
2004 new_ram_size = MAX(old_ram_size,
2005 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
2006 if (new_ram_size > old_ram_size) {
2007 dirty_memory_extend(old_ram_size, new_ram_size);
2009 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2010 * QLIST (which has an RCU-friendly variant) does not have insertion at
2011 * tail, so save the last element in last_block.
2013 RAMBLOCK_FOREACH(block) {
2014 last_block = block;
2015 if (block->max_length < new_block->max_length) {
2016 break;
2019 if (block) {
2020 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
2021 } else if (last_block) {
2022 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
2023 } else { /* list is empty */
2024 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
2026 ram_list.mru_block = NULL;
2028 /* Write list before version */
2029 smp_wmb();
2030 ram_list.version++;
2031 qemu_mutex_unlock_ramlist();
2033 cpu_physical_memory_set_dirty_range(new_block->offset,
2034 new_block->used_length,
2035 DIRTY_CLIENTS_ALL);
2037 if (new_block->host) {
2038 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2039 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2040 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
2041 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
2042 ram_block_notify_add(new_block->host, new_block->max_length);
2046 #ifdef __linux__
2047 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2048 bool share, int fd,
2049 Error **errp)
2051 RAMBlock *new_block;
2052 Error *local_err = NULL;
2053 int64_t file_size;
2055 if (xen_enabled()) {
2056 error_setg(errp, "-mem-path not supported with Xen");
2057 return NULL;
2060 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2061 error_setg(errp,
2062 "host lacks kvm mmu notifiers, -mem-path unsupported");
2063 return NULL;
2066 if (phys_mem_alloc != qemu_anon_ram_alloc) {
2068 * file_ram_alloc() needs to allocate just like
2069 * phys_mem_alloc, but we haven't bothered to provide
2070 * a hook there.
2072 error_setg(errp,
2073 "-mem-path not supported with this accelerator");
2074 return NULL;
2077 size = HOST_PAGE_ALIGN(size);
2078 file_size = get_file_size(fd);
2079 if (file_size > 0 && file_size < size) {
2080 error_setg(errp, "backing store %s size 0x%" PRIx64
2081 " does not match 'size' option 0x" RAM_ADDR_FMT,
2082 mem_path, file_size, size);
2083 return NULL;
2086 new_block = g_malloc0(sizeof(*new_block));
2087 new_block->mr = mr;
2088 new_block->used_length = size;
2089 new_block->max_length = size;
2090 new_block->flags = share ? RAM_SHARED : 0;
2091 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
2092 if (!new_block->host) {
2093 g_free(new_block);
2094 return NULL;
2097 ram_block_add(new_block, &local_err, share);
2098 if (local_err) {
2099 g_free(new_block);
2100 error_propagate(errp, local_err);
2101 return NULL;
2103 return new_block;
2108 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2109 bool share, const char *mem_path,
2110 Error **errp)
2112 int fd;
2113 bool created;
2114 RAMBlock *block;
2116 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2117 if (fd < 0) {
2118 return NULL;
2121 block = qemu_ram_alloc_from_fd(size, mr, share, fd, errp);
2122 if (!block) {
2123 if (created) {
2124 unlink(mem_path);
2126 close(fd);
2127 return NULL;
2130 return block;
2132 #endif
2134 static
2135 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2136 void (*resized)(const char*,
2137 uint64_t length,
2138 void *host),
2139 void *host, bool resizeable, bool share,
2140 MemoryRegion *mr, Error **errp)
2142 RAMBlock *new_block;
2143 Error *local_err = NULL;
2145 size = HOST_PAGE_ALIGN(size);
2146 max_size = HOST_PAGE_ALIGN(max_size);
2147 new_block = g_malloc0(sizeof(*new_block));
2148 new_block->mr = mr;
2149 new_block->resized = resized;
2150 new_block->used_length = size;
2151 new_block->max_length = max_size;
2152 assert(max_size >= size);
2153 new_block->fd = -1;
2154 new_block->page_size = getpagesize();
2155 new_block->host = host;
2156 if (host) {
2157 new_block->flags |= RAM_PREALLOC;
2159 if (resizeable) {
2160 new_block->flags |= RAM_RESIZEABLE;
2162 ram_block_add(new_block, &local_err, share);
2163 if (local_err) {
2164 g_free(new_block);
2165 error_propagate(errp, local_err);
2166 return NULL;
2168 return new_block;
2171 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2172 MemoryRegion *mr, Error **errp)
2174 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2175 false, mr, errp);
2178 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2179 MemoryRegion *mr, Error **errp)
2181 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2182 share, mr, errp);
2185 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2186 void (*resized)(const char*,
2187 uint64_t length,
2188 void *host),
2189 MemoryRegion *mr, Error **errp)
2191 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2192 false, mr, errp);
2195 static void reclaim_ramblock(RAMBlock *block)
2197 if (block->flags & RAM_PREALLOC) {
2199 } else if (xen_enabled()) {
2200 xen_invalidate_map_cache_entry(block->host);
2201 #ifndef _WIN32
2202 } else if (block->fd >= 0) {
2203 qemu_ram_munmap(block->host, block->max_length);
2204 close(block->fd);
2205 #endif
2206 } else {
2207 qemu_anon_ram_free(block->host, block->max_length);
2209 g_free(block);
2212 void qemu_ram_free(RAMBlock *block)
2214 if (!block) {
2215 return;
2218 if (block->host) {
2219 ram_block_notify_remove(block->host, block->max_length);
2222 qemu_mutex_lock_ramlist();
2223 QLIST_REMOVE_RCU(block, next);
2224 ram_list.mru_block = NULL;
2225 /* Write list before version */
2226 smp_wmb();
2227 ram_list.version++;
2228 call_rcu(block, reclaim_ramblock, rcu);
2229 qemu_mutex_unlock_ramlist();
2232 #ifndef _WIN32
2233 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2235 RAMBlock *block;
2236 ram_addr_t offset;
2237 int flags;
2238 void *area, *vaddr;
2240 RAMBLOCK_FOREACH(block) {
2241 offset = addr - block->offset;
2242 if (offset < block->max_length) {
2243 vaddr = ramblock_ptr(block, offset);
2244 if (block->flags & RAM_PREALLOC) {
2246 } else if (xen_enabled()) {
2247 abort();
2248 } else {
2249 flags = MAP_FIXED;
2250 if (block->fd >= 0) {
2251 flags |= (block->flags & RAM_SHARED ?
2252 MAP_SHARED : MAP_PRIVATE);
2253 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2254 flags, block->fd, offset);
2255 } else {
2257 * Remap needs to match alloc. Accelerators that
2258 * set phys_mem_alloc never remap. If they did,
2259 * we'd need a remap hook here.
2261 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2263 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2264 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2265 flags, -1, 0);
2267 if (area != vaddr) {
2268 error_report("Could not remap addr: "
2269 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2270 length, addr);
2271 exit(1);
2273 memory_try_enable_merging(vaddr, length);
2274 qemu_ram_setup_dump(vaddr, length);
2279 #endif /* !_WIN32 */
2281 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2282 * This should not be used for general purpose DMA. Use address_space_map
2283 * or address_space_rw instead. For local memory (e.g. video ram) that the
2284 * device owns, use memory_region_get_ram_ptr.
2286 * Called within RCU critical section.
2288 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2290 RAMBlock *block = ram_block;
2292 if (block == NULL) {
2293 block = qemu_get_ram_block(addr);
2294 addr -= block->offset;
2297 if (xen_enabled() && block->host == NULL) {
2298 /* We need to check if the requested address is in the RAM
2299 * because we don't want to map the entire memory in QEMU.
2300 * In that case just map until the end of the page.
2302 if (block->offset == 0) {
2303 return xen_map_cache(addr, 0, 0, false);
2306 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2308 return ramblock_ptr(block, addr);
2311 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2312 * but takes a size argument.
2314 * Called within RCU critical section.
2316 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2317 hwaddr *size, bool lock)
2319 RAMBlock *block = ram_block;
2320 if (*size == 0) {
2321 return NULL;
2324 if (block == NULL) {
2325 block = qemu_get_ram_block(addr);
2326 addr -= block->offset;
2328 *size = MIN(*size, block->max_length - addr);
2330 if (xen_enabled() && block->host == NULL) {
2331 /* We need to check if the requested address is in the RAM
2332 * because we don't want to map the entire memory in QEMU.
2333 * In that case just map the requested area.
2335 if (block->offset == 0) {
2336 return xen_map_cache(addr, *size, lock, lock);
2339 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2342 return ramblock_ptr(block, addr);
2345 /* Return the offset of a hostpointer within a ramblock */
2346 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2348 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2349 assert((uintptr_t)host >= (uintptr_t)rb->host);
2350 assert(res < rb->max_length);
2352 return res;
2356 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2357 * in that RAMBlock.
2359 * ptr: Host pointer to look up
2360 * round_offset: If true round the result offset down to a page boundary
2361 * *ram_addr: set to result ram_addr
2362 * *offset: set to result offset within the RAMBlock
2364 * Returns: RAMBlock (or NULL if not found)
2366 * By the time this function returns, the returned pointer is not protected
2367 * by RCU anymore. If the caller is not within an RCU critical section and
2368 * does not hold the iothread lock, it must have other means of protecting the
2369 * pointer, such as a reference to the region that includes the incoming
2370 * ram_addr_t.
2372 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2373 ram_addr_t *offset)
2375 RAMBlock *block;
2376 uint8_t *host = ptr;
2378 if (xen_enabled()) {
2379 ram_addr_t ram_addr;
2380 rcu_read_lock();
2381 ram_addr = xen_ram_addr_from_mapcache(ptr);
2382 block = qemu_get_ram_block(ram_addr);
2383 if (block) {
2384 *offset = ram_addr - block->offset;
2386 rcu_read_unlock();
2387 return block;
2390 rcu_read_lock();
2391 block = atomic_rcu_read(&ram_list.mru_block);
2392 if (block && block->host && host - block->host < block->max_length) {
2393 goto found;
2396 RAMBLOCK_FOREACH(block) {
2397 /* This case append when the block is not mapped. */
2398 if (block->host == NULL) {
2399 continue;
2401 if (host - block->host < block->max_length) {
2402 goto found;
2406 rcu_read_unlock();
2407 return NULL;
2409 found:
2410 *offset = (host - block->host);
2411 if (round_offset) {
2412 *offset &= TARGET_PAGE_MASK;
2414 rcu_read_unlock();
2415 return block;
2419 * Finds the named RAMBlock
2421 * name: The name of RAMBlock to find
2423 * Returns: RAMBlock (or NULL if not found)
2425 RAMBlock *qemu_ram_block_by_name(const char *name)
2427 RAMBlock *block;
2429 RAMBLOCK_FOREACH(block) {
2430 if (!strcmp(name, block->idstr)) {
2431 return block;
2435 return NULL;
2438 /* Some of the softmmu routines need to translate from a host pointer
2439 (typically a TLB entry) back to a ram offset. */
2440 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2442 RAMBlock *block;
2443 ram_addr_t offset;
2445 block = qemu_ram_block_from_host(ptr, false, &offset);
2446 if (!block) {
2447 return RAM_ADDR_INVALID;
2450 return block->offset + offset;
2453 /* Called within RCU critical section. */
2454 void memory_notdirty_write_prepare(NotDirtyInfo *ndi,
2455 CPUState *cpu,
2456 vaddr mem_vaddr,
2457 ram_addr_t ram_addr,
2458 unsigned size)
2460 ndi->cpu = cpu;
2461 ndi->ram_addr = ram_addr;
2462 ndi->mem_vaddr = mem_vaddr;
2463 ndi->size = size;
2464 ndi->locked = false;
2466 assert(tcg_enabled());
2467 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
2468 ndi->locked = true;
2469 tb_lock();
2470 tb_invalidate_phys_page_fast(ram_addr, size);
2474 /* Called within RCU critical section. */
2475 void memory_notdirty_write_complete(NotDirtyInfo *ndi)
2477 if (ndi->locked) {
2478 tb_unlock();
2481 /* Set both VGA and migration bits for simplicity and to remove
2482 * the notdirty callback faster.
2484 cpu_physical_memory_set_dirty_range(ndi->ram_addr, ndi->size,
2485 DIRTY_CLIENTS_NOCODE);
2486 /* we remove the notdirty callback only if the code has been
2487 flushed */
2488 if (!cpu_physical_memory_is_clean(ndi->ram_addr)) {
2489 tlb_set_dirty(ndi->cpu, ndi->mem_vaddr);
2493 /* Called within RCU critical section. */
2494 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2495 uint64_t val, unsigned size)
2497 NotDirtyInfo ndi;
2499 memory_notdirty_write_prepare(&ndi, current_cpu, current_cpu->mem_io_vaddr,
2500 ram_addr, size);
2502 switch (size) {
2503 case 1:
2504 stb_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2505 break;
2506 case 2:
2507 stw_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2508 break;
2509 case 4:
2510 stl_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2511 break;
2512 case 8:
2513 stq_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2514 break;
2515 default:
2516 abort();
2518 memory_notdirty_write_complete(&ndi);
2521 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
2522 unsigned size, bool is_write)
2524 return is_write;
2527 static const MemoryRegionOps notdirty_mem_ops = {
2528 .write = notdirty_mem_write,
2529 .valid.accepts = notdirty_mem_accepts,
2530 .endianness = DEVICE_NATIVE_ENDIAN,
2531 .valid = {
2532 .min_access_size = 1,
2533 .max_access_size = 8,
2534 .unaligned = false,
2536 .impl = {
2537 .min_access_size = 1,
2538 .max_access_size = 8,
2539 .unaligned = false,
2543 /* Generate a debug exception if a watchpoint has been hit. */
2544 static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
2546 CPUState *cpu = current_cpu;
2547 CPUClass *cc = CPU_GET_CLASS(cpu);
2548 target_ulong vaddr;
2549 CPUWatchpoint *wp;
2551 assert(tcg_enabled());
2552 if (cpu->watchpoint_hit) {
2553 /* We re-entered the check after replacing the TB. Now raise
2554 * the debug interrupt so that is will trigger after the
2555 * current instruction. */
2556 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2557 return;
2559 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
2560 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
2561 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2562 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2563 && (wp->flags & flags)) {
2564 if (flags == BP_MEM_READ) {
2565 wp->flags |= BP_WATCHPOINT_HIT_READ;
2566 } else {
2567 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2569 wp->hitaddr = vaddr;
2570 wp->hitattrs = attrs;
2571 if (!cpu->watchpoint_hit) {
2572 if (wp->flags & BP_CPU &&
2573 !cc->debug_check_watchpoint(cpu, wp)) {
2574 wp->flags &= ~BP_WATCHPOINT_HIT;
2575 continue;
2577 cpu->watchpoint_hit = wp;
2579 /* Both tb_lock and iothread_mutex will be reset when
2580 * cpu_loop_exit or cpu_loop_exit_noexc longjmp
2581 * back into the cpu_exec main loop.
2583 tb_lock();
2584 tb_check_watchpoint(cpu);
2585 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2586 cpu->exception_index = EXCP_DEBUG;
2587 cpu_loop_exit(cpu);
2588 } else {
2589 /* Force execution of one insn next time. */
2590 cpu->cflags_next_tb = 1 | curr_cflags();
2591 cpu_loop_exit_noexc(cpu);
2594 } else {
2595 wp->flags &= ~BP_WATCHPOINT_HIT;
2600 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2601 so these check for a hit then pass through to the normal out-of-line
2602 phys routines. */
2603 static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2604 unsigned size, MemTxAttrs attrs)
2606 MemTxResult res;
2607 uint64_t data;
2608 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2609 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2611 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2612 switch (size) {
2613 case 1:
2614 data = address_space_ldub(as, addr, attrs, &res);
2615 break;
2616 case 2:
2617 data = address_space_lduw(as, addr, attrs, &res);
2618 break;
2619 case 4:
2620 data = address_space_ldl(as, addr, attrs, &res);
2621 break;
2622 case 8:
2623 data = address_space_ldq(as, addr, attrs, &res);
2624 break;
2625 default: abort();
2627 *pdata = data;
2628 return res;
2631 static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2632 uint64_t val, unsigned size,
2633 MemTxAttrs attrs)
2635 MemTxResult res;
2636 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2637 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2639 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2640 switch (size) {
2641 case 1:
2642 address_space_stb(as, addr, val, attrs, &res);
2643 break;
2644 case 2:
2645 address_space_stw(as, addr, val, attrs, &res);
2646 break;
2647 case 4:
2648 address_space_stl(as, addr, val, attrs, &res);
2649 break;
2650 case 8:
2651 address_space_stq(as, addr, val, attrs, &res);
2652 break;
2653 default: abort();
2655 return res;
2658 static const MemoryRegionOps watch_mem_ops = {
2659 .read_with_attrs = watch_mem_read,
2660 .write_with_attrs = watch_mem_write,
2661 .endianness = DEVICE_NATIVE_ENDIAN,
2662 .valid = {
2663 .min_access_size = 1,
2664 .max_access_size = 8,
2665 .unaligned = false,
2667 .impl = {
2668 .min_access_size = 1,
2669 .max_access_size = 8,
2670 .unaligned = false,
2674 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2675 MemTxAttrs attrs, uint8_t *buf, int len);
2676 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2677 const uint8_t *buf, int len);
2678 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
2679 bool is_write);
2681 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2682 unsigned len, MemTxAttrs attrs)
2684 subpage_t *subpage = opaque;
2685 uint8_t buf[8];
2686 MemTxResult res;
2688 #if defined(DEBUG_SUBPAGE)
2689 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2690 subpage, len, addr);
2691 #endif
2692 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2693 if (res) {
2694 return res;
2696 switch (len) {
2697 case 1:
2698 *data = ldub_p(buf);
2699 return MEMTX_OK;
2700 case 2:
2701 *data = lduw_p(buf);
2702 return MEMTX_OK;
2703 case 4:
2704 *data = ldl_p(buf);
2705 return MEMTX_OK;
2706 case 8:
2707 *data = ldq_p(buf);
2708 return MEMTX_OK;
2709 default:
2710 abort();
2714 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2715 uint64_t value, unsigned len, MemTxAttrs attrs)
2717 subpage_t *subpage = opaque;
2718 uint8_t buf[8];
2720 #if defined(DEBUG_SUBPAGE)
2721 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2722 " value %"PRIx64"\n",
2723 __func__, subpage, len, addr, value);
2724 #endif
2725 switch (len) {
2726 case 1:
2727 stb_p(buf, value);
2728 break;
2729 case 2:
2730 stw_p(buf, value);
2731 break;
2732 case 4:
2733 stl_p(buf, value);
2734 break;
2735 case 8:
2736 stq_p(buf, value);
2737 break;
2738 default:
2739 abort();
2741 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2744 static bool subpage_accepts(void *opaque, hwaddr addr,
2745 unsigned len, bool is_write)
2747 subpage_t *subpage = opaque;
2748 #if defined(DEBUG_SUBPAGE)
2749 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2750 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2751 #endif
2753 return flatview_access_valid(subpage->fv, addr + subpage->base,
2754 len, is_write);
2757 static const MemoryRegionOps subpage_ops = {
2758 .read_with_attrs = subpage_read,
2759 .write_with_attrs = subpage_write,
2760 .impl.min_access_size = 1,
2761 .impl.max_access_size = 8,
2762 .valid.min_access_size = 1,
2763 .valid.max_access_size = 8,
2764 .valid.accepts = subpage_accepts,
2765 .endianness = DEVICE_NATIVE_ENDIAN,
2768 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
2769 uint16_t section)
2771 int idx, eidx;
2773 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2774 return -1;
2775 idx = SUBPAGE_IDX(start);
2776 eidx = SUBPAGE_IDX(end);
2777 #if defined(DEBUG_SUBPAGE)
2778 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2779 __func__, mmio, start, end, idx, eidx, section);
2780 #endif
2781 for (; idx <= eidx; idx++) {
2782 mmio->sub_section[idx] = section;
2785 return 0;
2788 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2790 subpage_t *mmio;
2792 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2793 mmio->fv = fv;
2794 mmio->base = base;
2795 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2796 NULL, TARGET_PAGE_SIZE);
2797 mmio->iomem.subpage = true;
2798 #if defined(DEBUG_SUBPAGE)
2799 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2800 mmio, base, TARGET_PAGE_SIZE);
2801 #endif
2802 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
2804 return mmio;
2807 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2809 assert(fv);
2810 MemoryRegionSection section = {
2811 .fv = fv,
2812 .mr = mr,
2813 .offset_within_address_space = 0,
2814 .offset_within_region = 0,
2815 .size = int128_2_64(),
2818 return phys_section_add(map, &section);
2821 static void readonly_mem_write(void *opaque, hwaddr addr,
2822 uint64_t val, unsigned size)
2824 /* Ignore any write to ROM. */
2827 static bool readonly_mem_accepts(void *opaque, hwaddr addr,
2828 unsigned size, bool is_write)
2830 return is_write;
2833 /* This will only be used for writes, because reads are special cased
2834 * to directly access the underlying host ram.
2836 static const MemoryRegionOps readonly_mem_ops = {
2837 .write = readonly_mem_write,
2838 .valid.accepts = readonly_mem_accepts,
2839 .endianness = DEVICE_NATIVE_ENDIAN,
2840 .valid = {
2841 .min_access_size = 1,
2842 .max_access_size = 8,
2843 .unaligned = false,
2845 .impl = {
2846 .min_access_size = 1,
2847 .max_access_size = 8,
2848 .unaligned = false,
2852 MemoryRegion *iotlb_to_region(CPUState *cpu, hwaddr index, MemTxAttrs attrs)
2854 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2855 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2856 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
2857 MemoryRegionSection *sections = d->map.sections;
2859 return sections[index & ~TARGET_PAGE_MASK].mr;
2862 static void io_mem_init(void)
2864 memory_region_init_io(&io_mem_rom, NULL, &readonly_mem_ops,
2865 NULL, NULL, UINT64_MAX);
2866 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2867 NULL, UINT64_MAX);
2869 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
2870 * which can be called without the iothread mutex.
2872 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
2873 NULL, UINT64_MAX);
2874 memory_region_clear_global_locking(&io_mem_notdirty);
2876 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
2877 NULL, UINT64_MAX);
2880 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2882 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2883 uint16_t n;
2885 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2886 assert(n == PHYS_SECTION_UNASSIGNED);
2887 n = dummy_section(&d->map, fv, &io_mem_notdirty);
2888 assert(n == PHYS_SECTION_NOTDIRTY);
2889 n = dummy_section(&d->map, fv, &io_mem_rom);
2890 assert(n == PHYS_SECTION_ROM);
2891 n = dummy_section(&d->map, fv, &io_mem_watch);
2892 assert(n == PHYS_SECTION_WATCH);
2894 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2896 return d;
2899 void address_space_dispatch_free(AddressSpaceDispatch *d)
2901 phys_sections_free(&d->map);
2902 g_free(d);
2905 static void tcg_commit(MemoryListener *listener)
2907 CPUAddressSpace *cpuas;
2908 AddressSpaceDispatch *d;
2910 /* since each CPU stores ram addresses in its TLB cache, we must
2911 reset the modified entries */
2912 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2913 cpu_reloading_memory_map();
2914 /* The CPU and TLB are protected by the iothread lock.
2915 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2916 * may have split the RCU critical section.
2918 d = address_space_to_dispatch(cpuas->as);
2919 atomic_rcu_set(&cpuas->memory_dispatch, d);
2920 tlb_flush(cpuas->cpu);
2923 static void memory_map_init(void)
2925 system_memory = g_malloc(sizeof(*system_memory));
2927 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2928 address_space_init(&address_space_memory, system_memory, "memory");
2930 system_io = g_malloc(sizeof(*system_io));
2931 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2932 65536);
2933 address_space_init(&address_space_io, system_io, "I/O");
2936 MemoryRegion *get_system_memory(void)
2938 return system_memory;
2941 MemoryRegion *get_system_io(void)
2943 return system_io;
2946 #endif /* !defined(CONFIG_USER_ONLY) */
2948 /* physical memory access (slow version, mainly for debug) */
2949 #if defined(CONFIG_USER_ONLY)
2950 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
2951 uint8_t *buf, int len, int is_write)
2953 int l, flags;
2954 target_ulong page;
2955 void * p;
2957 while (len > 0) {
2958 page = addr & TARGET_PAGE_MASK;
2959 l = (page + TARGET_PAGE_SIZE) - addr;
2960 if (l > len)
2961 l = len;
2962 flags = page_get_flags(page);
2963 if (!(flags & PAGE_VALID))
2964 return -1;
2965 if (is_write) {
2966 if (!(flags & PAGE_WRITE))
2967 return -1;
2968 /* XXX: this code should not depend on lock_user */
2969 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
2970 return -1;
2971 memcpy(p, buf, l);
2972 unlock_user(p, addr, l);
2973 } else {
2974 if (!(flags & PAGE_READ))
2975 return -1;
2976 /* XXX: this code should not depend on lock_user */
2977 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
2978 return -1;
2979 memcpy(buf, p, l);
2980 unlock_user(p, addr, 0);
2982 len -= l;
2983 buf += l;
2984 addr += l;
2986 return 0;
2989 #else
2991 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2992 hwaddr length)
2994 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2995 addr += memory_region_get_ram_addr(mr);
2997 /* No early return if dirty_log_mask is or becomes 0, because
2998 * cpu_physical_memory_set_dirty_range will still call
2999 * xen_modified_memory.
3001 if (dirty_log_mask) {
3002 dirty_log_mask =
3003 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
3005 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
3006 assert(tcg_enabled());
3007 tb_lock();
3008 tb_invalidate_phys_range(addr, addr + length);
3009 tb_unlock();
3010 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
3012 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
3015 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
3017 unsigned access_size_max = mr->ops->valid.max_access_size;
3019 /* Regions are assumed to support 1-4 byte accesses unless
3020 otherwise specified. */
3021 if (access_size_max == 0) {
3022 access_size_max = 4;
3025 /* Bound the maximum access by the alignment of the address. */
3026 if (!mr->ops->impl.unaligned) {
3027 unsigned align_size_max = addr & -addr;
3028 if (align_size_max != 0 && align_size_max < access_size_max) {
3029 access_size_max = align_size_max;
3033 /* Don't attempt accesses larger than the maximum. */
3034 if (l > access_size_max) {
3035 l = access_size_max;
3037 l = pow2floor(l);
3039 return l;
3042 static bool prepare_mmio_access(MemoryRegion *mr)
3044 bool unlocked = !qemu_mutex_iothread_locked();
3045 bool release_lock = false;
3047 if (unlocked && mr->global_locking) {
3048 qemu_mutex_lock_iothread();
3049 unlocked = false;
3050 release_lock = true;
3052 if (mr->flush_coalesced_mmio) {
3053 if (unlocked) {
3054 qemu_mutex_lock_iothread();
3056 qemu_flush_coalesced_mmio_buffer();
3057 if (unlocked) {
3058 qemu_mutex_unlock_iothread();
3062 return release_lock;
3065 /* Called within RCU critical section. */
3066 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
3067 MemTxAttrs attrs,
3068 const uint8_t *buf,
3069 int len, hwaddr addr1,
3070 hwaddr l, MemoryRegion *mr)
3072 uint8_t *ptr;
3073 uint64_t val;
3074 MemTxResult result = MEMTX_OK;
3075 bool release_lock = false;
3077 for (;;) {
3078 if (!memory_access_is_direct(mr, true)) {
3079 release_lock |= prepare_mmio_access(mr);
3080 l = memory_access_size(mr, l, addr1);
3081 /* XXX: could force current_cpu to NULL to avoid
3082 potential bugs */
3083 switch (l) {
3084 case 8:
3085 /* 64 bit write access */
3086 val = ldq_p(buf);
3087 result |= memory_region_dispatch_write(mr, addr1, val, 8,
3088 attrs);
3089 break;
3090 case 4:
3091 /* 32 bit write access */
3092 val = (uint32_t)ldl_p(buf);
3093 result |= memory_region_dispatch_write(mr, addr1, val, 4,
3094 attrs);
3095 break;
3096 case 2:
3097 /* 16 bit write access */
3098 val = lduw_p(buf);
3099 result |= memory_region_dispatch_write(mr, addr1, val, 2,
3100 attrs);
3101 break;
3102 case 1:
3103 /* 8 bit write access */
3104 val = ldub_p(buf);
3105 result |= memory_region_dispatch_write(mr, addr1, val, 1,
3106 attrs);
3107 break;
3108 default:
3109 abort();
3111 } else {
3112 /* RAM case */
3113 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3114 memcpy(ptr, buf, l);
3115 invalidate_and_set_dirty(mr, addr1, l);
3118 if (release_lock) {
3119 qemu_mutex_unlock_iothread();
3120 release_lock = false;
3123 len -= l;
3124 buf += l;
3125 addr += l;
3127 if (!len) {
3128 break;
3131 l = len;
3132 mr = flatview_translate(fv, addr, &addr1, &l, true);
3135 return result;
3138 /* Called from RCU critical section. */
3139 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
3140 const uint8_t *buf, int len)
3142 hwaddr l;
3143 hwaddr addr1;
3144 MemoryRegion *mr;
3145 MemTxResult result = MEMTX_OK;
3147 l = len;
3148 mr = flatview_translate(fv, addr, &addr1, &l, true);
3149 result = flatview_write_continue(fv, addr, attrs, buf, len,
3150 addr1, l, mr);
3152 return result;
3155 /* Called within RCU critical section. */
3156 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
3157 MemTxAttrs attrs, uint8_t *buf,
3158 int len, hwaddr addr1, hwaddr l,
3159 MemoryRegion *mr)
3161 uint8_t *ptr;
3162 uint64_t val;
3163 MemTxResult result = MEMTX_OK;
3164 bool release_lock = false;
3166 for (;;) {
3167 if (!memory_access_is_direct(mr, false)) {
3168 /* I/O case */
3169 release_lock |= prepare_mmio_access(mr);
3170 l = memory_access_size(mr, l, addr1);
3171 switch (l) {
3172 case 8:
3173 /* 64 bit read access */
3174 result |= memory_region_dispatch_read(mr, addr1, &val, 8,
3175 attrs);
3176 stq_p(buf, val);
3177 break;
3178 case 4:
3179 /* 32 bit read access */
3180 result |= memory_region_dispatch_read(mr, addr1, &val, 4,
3181 attrs);
3182 stl_p(buf, val);
3183 break;
3184 case 2:
3185 /* 16 bit read access */
3186 result |= memory_region_dispatch_read(mr, addr1, &val, 2,
3187 attrs);
3188 stw_p(buf, val);
3189 break;
3190 case 1:
3191 /* 8 bit read access */
3192 result |= memory_region_dispatch_read(mr, addr1, &val, 1,
3193 attrs);
3194 stb_p(buf, val);
3195 break;
3196 default:
3197 abort();
3199 } else {
3200 /* RAM case */
3201 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3202 memcpy(buf, ptr, l);
3205 if (release_lock) {
3206 qemu_mutex_unlock_iothread();
3207 release_lock = false;
3210 len -= l;
3211 buf += l;
3212 addr += l;
3214 if (!len) {
3215 break;
3218 l = len;
3219 mr = flatview_translate(fv, addr, &addr1, &l, false);
3222 return result;
3225 /* Called from RCU critical section. */
3226 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
3227 MemTxAttrs attrs, uint8_t *buf, int len)
3229 hwaddr l;
3230 hwaddr addr1;
3231 MemoryRegion *mr;
3233 l = len;
3234 mr = flatview_translate(fv, addr, &addr1, &l, false);
3235 return flatview_read_continue(fv, addr, attrs, buf, len,
3236 addr1, l, mr);
3239 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3240 MemTxAttrs attrs, uint8_t *buf, int len)
3242 MemTxResult result = MEMTX_OK;
3243 FlatView *fv;
3245 if (len > 0) {
3246 rcu_read_lock();
3247 fv = address_space_to_flatview(as);
3248 result = flatview_read(fv, addr, attrs, buf, len);
3249 rcu_read_unlock();
3252 return result;
3255 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
3256 MemTxAttrs attrs,
3257 const uint8_t *buf, int len)
3259 MemTxResult result = MEMTX_OK;
3260 FlatView *fv;
3262 if (len > 0) {
3263 rcu_read_lock();
3264 fv = address_space_to_flatview(as);
3265 result = flatview_write(fv, addr, attrs, buf, len);
3266 rcu_read_unlock();
3269 return result;
3272 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3273 uint8_t *buf, int len, bool is_write)
3275 if (is_write) {
3276 return address_space_write(as, addr, attrs, buf, len);
3277 } else {
3278 return address_space_read_full(as, addr, attrs, buf, len);
3282 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
3283 int len, int is_write)
3285 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3286 buf, len, is_write);
3289 enum write_rom_type {
3290 WRITE_DATA,
3291 FLUSH_CACHE,
3294 static inline void cpu_physical_memory_write_rom_internal(AddressSpace *as,
3295 hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
3297 hwaddr l;
3298 uint8_t *ptr;
3299 hwaddr addr1;
3300 MemoryRegion *mr;
3302 rcu_read_lock();
3303 while (len > 0) {
3304 l = len;
3305 mr = address_space_translate(as, addr, &addr1, &l, true);
3307 if (!(memory_region_is_ram(mr) ||
3308 memory_region_is_romd(mr))) {
3309 l = memory_access_size(mr, l, addr1);
3310 } else {
3311 /* ROM/RAM case */
3312 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3313 switch (type) {
3314 case WRITE_DATA:
3315 memcpy(ptr, buf, l);
3316 invalidate_and_set_dirty(mr, addr1, l);
3317 break;
3318 case FLUSH_CACHE:
3319 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
3320 break;
3323 len -= l;
3324 buf += l;
3325 addr += l;
3327 rcu_read_unlock();
3330 /* used for ROM loading : can write in RAM and ROM */
3331 void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
3332 const uint8_t *buf, int len)
3334 cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
3337 void cpu_flush_icache_range(hwaddr start, int len)
3340 * This function should do the same thing as an icache flush that was
3341 * triggered from within the guest. For TCG we are always cache coherent,
3342 * so there is no need to flush anything. For KVM / Xen we need to flush
3343 * the host's instruction cache at least.
3345 if (tcg_enabled()) {
3346 return;
3349 cpu_physical_memory_write_rom_internal(&address_space_memory,
3350 start, NULL, len, FLUSH_CACHE);
3353 typedef struct {
3354 MemoryRegion *mr;
3355 void *buffer;
3356 hwaddr addr;
3357 hwaddr len;
3358 bool in_use;
3359 } BounceBuffer;
3361 static BounceBuffer bounce;
3363 typedef struct MapClient {
3364 QEMUBH *bh;
3365 QLIST_ENTRY(MapClient) link;
3366 } MapClient;
3368 QemuMutex map_client_list_lock;
3369 static QLIST_HEAD(map_client_list, MapClient) map_client_list
3370 = QLIST_HEAD_INITIALIZER(map_client_list);
3372 static void cpu_unregister_map_client_do(MapClient *client)
3374 QLIST_REMOVE(client, link);
3375 g_free(client);
3378 static void cpu_notify_map_clients_locked(void)
3380 MapClient *client;
3382 while (!QLIST_EMPTY(&map_client_list)) {
3383 client = QLIST_FIRST(&map_client_list);
3384 qemu_bh_schedule(client->bh);
3385 cpu_unregister_map_client_do(client);
3389 void cpu_register_map_client(QEMUBH *bh)
3391 MapClient *client = g_malloc(sizeof(*client));
3393 qemu_mutex_lock(&map_client_list_lock);
3394 client->bh = bh;
3395 QLIST_INSERT_HEAD(&map_client_list, client, link);
3396 if (!atomic_read(&bounce.in_use)) {
3397 cpu_notify_map_clients_locked();
3399 qemu_mutex_unlock(&map_client_list_lock);
3402 void cpu_exec_init_all(void)
3404 qemu_mutex_init(&ram_list.mutex);
3405 /* The data structures we set up here depend on knowing the page size,
3406 * so no more changes can be made after this point.
3407 * In an ideal world, nothing we did before we had finished the
3408 * machine setup would care about the target page size, and we could
3409 * do this much later, rather than requiring board models to state
3410 * up front what their requirements are.
3412 finalize_target_page_bits();
3413 io_mem_init();
3414 memory_map_init();
3415 qemu_mutex_init(&map_client_list_lock);
3418 void cpu_unregister_map_client(QEMUBH *bh)
3420 MapClient *client;
3422 qemu_mutex_lock(&map_client_list_lock);
3423 QLIST_FOREACH(client, &map_client_list, link) {
3424 if (client->bh == bh) {
3425 cpu_unregister_map_client_do(client);
3426 break;
3429 qemu_mutex_unlock(&map_client_list_lock);
3432 static void cpu_notify_map_clients(void)
3434 qemu_mutex_lock(&map_client_list_lock);
3435 cpu_notify_map_clients_locked();
3436 qemu_mutex_unlock(&map_client_list_lock);
3439 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
3440 bool is_write)
3442 MemoryRegion *mr;
3443 hwaddr l, xlat;
3445 while (len > 0) {
3446 l = len;
3447 mr = flatview_translate(fv, addr, &xlat, &l, is_write);
3448 if (!memory_access_is_direct(mr, is_write)) {
3449 l = memory_access_size(mr, l, addr);
3450 if (!memory_region_access_valid(mr, xlat, l, is_write)) {
3451 return false;
3455 len -= l;
3456 addr += l;
3458 return true;
3461 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3462 int len, bool is_write)
3464 FlatView *fv;
3465 bool result;
3467 rcu_read_lock();
3468 fv = address_space_to_flatview(as);
3469 result = flatview_access_valid(fv, addr, len, is_write);
3470 rcu_read_unlock();
3471 return result;
3474 static hwaddr
3475 flatview_extend_translation(FlatView *fv, hwaddr addr,
3476 hwaddr target_len,
3477 MemoryRegion *mr, hwaddr base, hwaddr len,
3478 bool is_write)
3480 hwaddr done = 0;
3481 hwaddr xlat;
3482 MemoryRegion *this_mr;
3484 for (;;) {
3485 target_len -= len;
3486 addr += len;
3487 done += len;
3488 if (target_len == 0) {
3489 return done;
3492 len = target_len;
3493 this_mr = flatview_translate(fv, addr, &xlat,
3494 &len, is_write);
3495 if (this_mr != mr || xlat != base + done) {
3496 return done;
3501 /* Map a physical memory region into a host virtual address.
3502 * May map a subset of the requested range, given by and returned in *plen.
3503 * May return NULL if resources needed to perform the mapping are exhausted.
3504 * Use only for reads OR writes - not for read-modify-write operations.
3505 * Use cpu_register_map_client() to know when retrying the map operation is
3506 * likely to succeed.
3508 void *address_space_map(AddressSpace *as,
3509 hwaddr addr,
3510 hwaddr *plen,
3511 bool is_write)
3513 hwaddr len = *plen;
3514 hwaddr l, xlat;
3515 MemoryRegion *mr;
3516 void *ptr;
3517 FlatView *fv;
3519 if (len == 0) {
3520 return NULL;
3523 l = len;
3524 rcu_read_lock();
3525 fv = address_space_to_flatview(as);
3526 mr = flatview_translate(fv, addr, &xlat, &l, is_write);
3528 if (!memory_access_is_direct(mr, is_write)) {
3529 if (atomic_xchg(&bounce.in_use, true)) {
3530 rcu_read_unlock();
3531 return NULL;
3533 /* Avoid unbounded allocations */
3534 l = MIN(l, TARGET_PAGE_SIZE);
3535 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3536 bounce.addr = addr;
3537 bounce.len = l;
3539 memory_region_ref(mr);
3540 bounce.mr = mr;
3541 if (!is_write) {
3542 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3543 bounce.buffer, l);
3546 rcu_read_unlock();
3547 *plen = l;
3548 return bounce.buffer;
3552 memory_region_ref(mr);
3553 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3554 l, is_write);
3555 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3556 rcu_read_unlock();
3558 return ptr;
3561 /* Unmaps a memory region previously mapped by address_space_map().
3562 * Will also mark the memory as dirty if is_write == 1. access_len gives
3563 * the amount of memory that was actually read or written by the caller.
3565 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3566 int is_write, hwaddr access_len)
3568 if (buffer != bounce.buffer) {
3569 MemoryRegion *mr;
3570 ram_addr_t addr1;
3572 mr = memory_region_from_host(buffer, &addr1);
3573 assert(mr != NULL);
3574 if (is_write) {
3575 invalidate_and_set_dirty(mr, addr1, access_len);
3577 if (xen_enabled()) {
3578 xen_invalidate_map_cache_entry(buffer);
3580 memory_region_unref(mr);
3581 return;
3583 if (is_write) {
3584 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3585 bounce.buffer, access_len);
3587 qemu_vfree(bounce.buffer);
3588 bounce.buffer = NULL;
3589 memory_region_unref(bounce.mr);
3590 atomic_mb_set(&bounce.in_use, false);
3591 cpu_notify_map_clients();
3594 void *cpu_physical_memory_map(hwaddr addr,
3595 hwaddr *plen,
3596 int is_write)
3598 return address_space_map(&address_space_memory, addr, plen, is_write);
3601 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3602 int is_write, hwaddr access_len)
3604 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3607 #define ARG1_DECL AddressSpace *as
3608 #define ARG1 as
3609 #define SUFFIX
3610 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3611 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3612 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3613 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3614 #define RCU_READ_LOCK(...) rcu_read_lock()
3615 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3616 #include "memory_ldst.inc.c"
3618 int64_t address_space_cache_init(MemoryRegionCache *cache,
3619 AddressSpace *as,
3620 hwaddr addr,
3621 hwaddr len,
3622 bool is_write)
3624 cache->len = len;
3625 cache->as = as;
3626 cache->xlat = addr;
3627 return len;
3630 void address_space_cache_invalidate(MemoryRegionCache *cache,
3631 hwaddr addr,
3632 hwaddr access_len)
3636 void address_space_cache_destroy(MemoryRegionCache *cache)
3638 cache->as = NULL;
3641 #define ARG1_DECL MemoryRegionCache *cache
3642 #define ARG1 cache
3643 #define SUFFIX _cached
3644 #define TRANSLATE(addr, ...) \
3645 address_space_translate(cache->as, cache->xlat + (addr), __VA_ARGS__)
3646 #define IS_DIRECT(mr, is_write) true
3647 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3648 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3649 #define RCU_READ_LOCK() rcu_read_lock()
3650 #define RCU_READ_UNLOCK() rcu_read_unlock()
3651 #include "memory_ldst.inc.c"
3653 /* virtual memory access for debug (includes writing to ROM) */
3654 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3655 uint8_t *buf, int len, int is_write)
3657 int l;
3658 hwaddr phys_addr;
3659 target_ulong page;
3661 cpu_synchronize_state(cpu);
3662 while (len > 0) {
3663 int asidx;
3664 MemTxAttrs attrs;
3666 page = addr & TARGET_PAGE_MASK;
3667 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3668 asidx = cpu_asidx_from_attrs(cpu, attrs);
3669 /* if no physical page mapped, return an error */
3670 if (phys_addr == -1)
3671 return -1;
3672 l = (page + TARGET_PAGE_SIZE) - addr;
3673 if (l > len)
3674 l = len;
3675 phys_addr += (addr & ~TARGET_PAGE_MASK);
3676 if (is_write) {
3677 cpu_physical_memory_write_rom(cpu->cpu_ases[asidx].as,
3678 phys_addr, buf, l);
3679 } else {
3680 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3681 MEMTXATTRS_UNSPECIFIED,
3682 buf, l, 0);
3684 len -= l;
3685 buf += l;
3686 addr += l;
3688 return 0;
3692 * Allows code that needs to deal with migration bitmaps etc to still be built
3693 * target independent.
3695 size_t qemu_target_page_size(void)
3697 return TARGET_PAGE_SIZE;
3700 int qemu_target_page_bits(void)
3702 return TARGET_PAGE_BITS;
3705 int qemu_target_page_bits_min(void)
3707 return TARGET_PAGE_BITS_MIN;
3709 #endif
3712 * A helper function for the _utterly broken_ virtio device model to find out if
3713 * it's running on a big endian machine. Don't do this at home kids!
3715 bool target_words_bigendian(void);
3716 bool target_words_bigendian(void)
3718 #if defined(TARGET_WORDS_BIGENDIAN)
3719 return true;
3720 #else
3721 return false;
3722 #endif
3725 #ifndef CONFIG_USER_ONLY
3726 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3728 MemoryRegion*mr;
3729 hwaddr l = 1;
3730 bool res;
3732 rcu_read_lock();
3733 mr = address_space_translate(&address_space_memory,
3734 phys_addr, &phys_addr, &l, false);
3736 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3737 rcu_read_unlock();
3738 return res;
3741 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3743 RAMBlock *block;
3744 int ret = 0;
3746 rcu_read_lock();
3747 RAMBLOCK_FOREACH(block) {
3748 ret = func(block->idstr, block->host, block->offset,
3749 block->used_length, opaque);
3750 if (ret) {
3751 break;
3754 rcu_read_unlock();
3755 return ret;
3759 * Unmap pages of memory from start to start+length such that
3760 * they a) read as 0, b) Trigger whatever fault mechanism
3761 * the OS provides for postcopy.
3762 * The pages must be unmapped by the end of the function.
3763 * Returns: 0 on success, none-0 on failure
3766 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3768 int ret = -1;
3770 uint8_t *host_startaddr = rb->host + start;
3772 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
3773 error_report("ram_block_discard_range: Unaligned start address: %p",
3774 host_startaddr);
3775 goto err;
3778 if ((start + length) <= rb->used_length) {
3779 bool need_madvise, need_fallocate;
3780 uint8_t *host_endaddr = host_startaddr + length;
3781 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
3782 error_report("ram_block_discard_range: Unaligned end address: %p",
3783 host_endaddr);
3784 goto err;
3787 errno = ENOTSUP; /* If we are missing MADVISE etc */
3789 /* The logic here is messy;
3790 * madvise DONTNEED fails for hugepages
3791 * fallocate works on hugepages and shmem
3793 need_madvise = (rb->page_size == qemu_host_page_size);
3794 need_fallocate = rb->fd != -1;
3795 if (need_fallocate) {
3796 /* For a file, this causes the area of the file to be zero'd
3797 * if read, and for hugetlbfs also causes it to be unmapped
3798 * so a userfault will trigger.
3800 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3801 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3802 start, length);
3803 if (ret) {
3804 ret = -errno;
3805 error_report("ram_block_discard_range: Failed to fallocate "
3806 "%s:%" PRIx64 " +%zx (%d)",
3807 rb->idstr, start, length, ret);
3808 goto err;
3810 #else
3811 ret = -ENOSYS;
3812 error_report("ram_block_discard_range: fallocate not available/file"
3813 "%s:%" PRIx64 " +%zx (%d)",
3814 rb->idstr, start, length, ret);
3815 goto err;
3816 #endif
3818 if (need_madvise) {
3819 /* For normal RAM this causes it to be unmapped,
3820 * for shared memory it causes the local mapping to disappear
3821 * and to fall back on the file contents (which we just
3822 * fallocate'd away).
3824 #if defined(CONFIG_MADVISE)
3825 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3826 if (ret) {
3827 ret = -errno;
3828 error_report("ram_block_discard_range: Failed to discard range "
3829 "%s:%" PRIx64 " +%zx (%d)",
3830 rb->idstr, start, length, ret);
3831 goto err;
3833 #else
3834 ret = -ENOSYS;
3835 error_report("ram_block_discard_range: MADVISE not available"
3836 "%s:%" PRIx64 " +%zx (%d)",
3837 rb->idstr, start, length, ret);
3838 goto err;
3839 #endif
3841 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3842 need_madvise, need_fallocate, ret);
3843 } else {
3844 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3845 "/%zx/" RAM_ADDR_FMT")",
3846 rb->idstr, start, length, rb->used_length);
3849 err:
3850 return ret;
3853 #endif
3855 void page_size_init(void)
3857 /* NOTE: we can always suppose that qemu_host_page_size >=
3858 TARGET_PAGE_SIZE */
3859 if (qemu_host_page_size == 0) {
3860 qemu_host_page_size = qemu_real_host_page_size;
3862 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
3863 qemu_host_page_size = TARGET_PAGE_SIZE;
3865 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;
3868 #if !defined(CONFIG_USER_ONLY)
3870 static void mtree_print_phys_entries(fprintf_function mon, void *f,
3871 int start, int end, int skip, int ptr)
3873 if (start == end - 1) {
3874 mon(f, "\t%3d ", start);
3875 } else {
3876 mon(f, "\t%3d..%-3d ", start, end - 1);
3878 mon(f, " skip=%d ", skip);
3879 if (ptr == PHYS_MAP_NODE_NIL) {
3880 mon(f, " ptr=NIL");
3881 } else if (!skip) {
3882 mon(f, " ptr=#%d", ptr);
3883 } else {
3884 mon(f, " ptr=[%d]", ptr);
3886 mon(f, "\n");
3889 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3890 int128_sub((size), int128_one())) : 0)
3892 void mtree_print_dispatch(fprintf_function mon, void *f,
3893 AddressSpaceDispatch *d, MemoryRegion *root)
3895 int i;
3897 mon(f, " Dispatch\n");
3898 mon(f, " Physical sections\n");
3900 for (i = 0; i < d->map.sections_nb; ++i) {
3901 MemoryRegionSection *s = d->map.sections + i;
3902 const char *names[] = { " [unassigned]", " [not dirty]",
3903 " [ROM]", " [watch]" };
3905 mon(f, " #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx " %s%s%s%s%s",
3907 s->offset_within_address_space,
3908 s->offset_within_address_space + MR_SIZE(s->mr->size),
3909 s->mr->name ? s->mr->name : "(noname)",
3910 i < ARRAY_SIZE(names) ? names[i] : "",
3911 s->mr == root ? " [ROOT]" : "",
3912 s == d->mru_section ? " [MRU]" : "",
3913 s->mr->is_iommu ? " [iommu]" : "");
3915 if (s->mr->alias) {
3916 mon(f, " alias=%s", s->mr->alias->name ?
3917 s->mr->alias->name : "noname");
3919 mon(f, "\n");
3922 mon(f, " Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3923 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3924 for (i = 0; i < d->map.nodes_nb; ++i) {
3925 int j, jprev;
3926 PhysPageEntry prev;
3927 Node *n = d->map.nodes + i;
3929 mon(f, " [%d]\n", i);
3931 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3932 PhysPageEntry *pe = *n + j;
3934 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3935 continue;
3938 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
3940 jprev = j;
3941 prev = *pe;
3944 if (jprev != ARRAY_SIZE(*n)) {
3945 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
3950 #endif