vhost+postcopy: Add vhost waker
[qemu.git] / exec.c
blob0eb890dca8e0ce3c03d09093f293366168faef85
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 cpu->as = NULL;
794 cpu->num_ases = 0;
796 #ifndef CONFIG_USER_ONLY
797 cpu->thread_id = qemu_get_thread_id();
798 cpu->memory = system_memory;
799 object_ref(OBJECT(cpu->memory));
800 #endif
803 void cpu_exec_realizefn(CPUState *cpu, Error **errp)
805 CPUClass *cc = CPU_GET_CLASS(cpu);
806 static bool tcg_target_initialized;
808 cpu_list_add(cpu);
810 if (tcg_enabled() && !tcg_target_initialized) {
811 tcg_target_initialized = true;
812 cc->tcg_initialize();
815 #ifndef CONFIG_USER_ONLY
816 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
817 vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
819 if (cc->vmsd != NULL) {
820 vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);
822 #endif
825 #if defined(CONFIG_USER_ONLY)
826 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
828 mmap_lock();
829 tb_lock();
830 tb_invalidate_phys_page_range(pc, pc + 1, 0);
831 tb_unlock();
832 mmap_unlock();
834 #else
835 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
837 MemTxAttrs attrs;
838 hwaddr phys = cpu_get_phys_page_attrs_debug(cpu, pc, &attrs);
839 int asidx = cpu_asidx_from_attrs(cpu, attrs);
840 if (phys != -1) {
841 /* Locks grabbed by tb_invalidate_phys_addr */
842 tb_invalidate_phys_addr(cpu->cpu_ases[asidx].as,
843 phys | (pc & ~TARGET_PAGE_MASK));
846 #endif
848 #if defined(CONFIG_USER_ONLY)
849 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
854 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
855 int flags)
857 return -ENOSYS;
860 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
864 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
865 int flags, CPUWatchpoint **watchpoint)
867 return -ENOSYS;
869 #else
870 /* Add a watchpoint. */
871 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
872 int flags, CPUWatchpoint **watchpoint)
874 CPUWatchpoint *wp;
876 /* forbid ranges which are empty or run off the end of the address space */
877 if (len == 0 || (addr + len - 1) < addr) {
878 error_report("tried to set invalid watchpoint at %"
879 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
880 return -EINVAL;
882 wp = g_malloc(sizeof(*wp));
884 wp->vaddr = addr;
885 wp->len = len;
886 wp->flags = flags;
888 /* keep all GDB-injected watchpoints in front */
889 if (flags & BP_GDB) {
890 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
891 } else {
892 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
895 tlb_flush_page(cpu, addr);
897 if (watchpoint)
898 *watchpoint = wp;
899 return 0;
902 /* Remove a specific watchpoint. */
903 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
904 int flags)
906 CPUWatchpoint *wp;
908 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
909 if (addr == wp->vaddr && len == wp->len
910 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
911 cpu_watchpoint_remove_by_ref(cpu, wp);
912 return 0;
915 return -ENOENT;
918 /* Remove a specific watchpoint by reference. */
919 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
921 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
923 tlb_flush_page(cpu, watchpoint->vaddr);
925 g_free(watchpoint);
928 /* Remove all matching watchpoints. */
929 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
931 CPUWatchpoint *wp, *next;
933 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
934 if (wp->flags & mask) {
935 cpu_watchpoint_remove_by_ref(cpu, wp);
940 /* Return true if this watchpoint address matches the specified
941 * access (ie the address range covered by the watchpoint overlaps
942 * partially or completely with the address range covered by the
943 * access).
945 static inline bool cpu_watchpoint_address_matches(CPUWatchpoint *wp,
946 vaddr addr,
947 vaddr len)
949 /* We know the lengths are non-zero, but a little caution is
950 * required to avoid errors in the case where the range ends
951 * exactly at the top of the address space and so addr + len
952 * wraps round to zero.
954 vaddr wpend = wp->vaddr + wp->len - 1;
955 vaddr addrend = addr + len - 1;
957 return !(addr > wpend || wp->vaddr > addrend);
960 #endif
962 /* Add a breakpoint. */
963 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
964 CPUBreakpoint **breakpoint)
966 CPUBreakpoint *bp;
968 bp = g_malloc(sizeof(*bp));
970 bp->pc = pc;
971 bp->flags = flags;
973 /* keep all GDB-injected breakpoints in front */
974 if (flags & BP_GDB) {
975 QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
976 } else {
977 QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
980 breakpoint_invalidate(cpu, pc);
982 if (breakpoint) {
983 *breakpoint = bp;
985 return 0;
988 /* Remove a specific breakpoint. */
989 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
991 CPUBreakpoint *bp;
993 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
994 if (bp->pc == pc && bp->flags == flags) {
995 cpu_breakpoint_remove_by_ref(cpu, bp);
996 return 0;
999 return -ENOENT;
1002 /* Remove a specific breakpoint by reference. */
1003 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
1005 QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);
1007 breakpoint_invalidate(cpu, breakpoint->pc);
1009 g_free(breakpoint);
1012 /* Remove all matching breakpoints. */
1013 void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
1015 CPUBreakpoint *bp, *next;
1017 QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
1018 if (bp->flags & mask) {
1019 cpu_breakpoint_remove_by_ref(cpu, bp);
1024 /* enable or disable single step mode. EXCP_DEBUG is returned by the
1025 CPU loop after each instruction */
1026 void cpu_single_step(CPUState *cpu, int enabled)
1028 if (cpu->singlestep_enabled != enabled) {
1029 cpu->singlestep_enabled = enabled;
1030 if (kvm_enabled()) {
1031 kvm_update_guest_debug(cpu, 0);
1032 } else {
1033 /* must flush all the translated code to avoid inconsistencies */
1034 /* XXX: only flush what is necessary */
1035 tb_flush(cpu);
1040 void cpu_abort(CPUState *cpu, const char *fmt, ...)
1042 va_list ap;
1043 va_list ap2;
1045 va_start(ap, fmt);
1046 va_copy(ap2, ap);
1047 fprintf(stderr, "qemu: fatal: ");
1048 vfprintf(stderr, fmt, ap);
1049 fprintf(stderr, "\n");
1050 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1051 if (qemu_log_separate()) {
1052 qemu_log_lock();
1053 qemu_log("qemu: fatal: ");
1054 qemu_log_vprintf(fmt, ap2);
1055 qemu_log("\n");
1056 log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1057 qemu_log_flush();
1058 qemu_log_unlock();
1059 qemu_log_close();
1061 va_end(ap2);
1062 va_end(ap);
1063 replay_finish();
1064 #if defined(CONFIG_USER_ONLY)
1066 struct sigaction act;
1067 sigfillset(&act.sa_mask);
1068 act.sa_handler = SIG_DFL;
1069 sigaction(SIGABRT, &act, NULL);
1071 #endif
1072 abort();
1075 #if !defined(CONFIG_USER_ONLY)
1076 /* Called from RCU critical section */
1077 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
1079 RAMBlock *block;
1081 block = atomic_rcu_read(&ram_list.mru_block);
1082 if (block && addr - block->offset < block->max_length) {
1083 return block;
1085 RAMBLOCK_FOREACH(block) {
1086 if (addr - block->offset < block->max_length) {
1087 goto found;
1091 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1092 abort();
1094 found:
1095 /* It is safe to write mru_block outside the iothread lock. This
1096 * is what happens:
1098 * mru_block = xxx
1099 * rcu_read_unlock()
1100 * xxx removed from list
1101 * rcu_read_lock()
1102 * read mru_block
1103 * mru_block = NULL;
1104 * call_rcu(reclaim_ramblock, xxx);
1105 * rcu_read_unlock()
1107 * atomic_rcu_set is not needed here. The block was already published
1108 * when it was placed into the list. Here we're just making an extra
1109 * copy of the pointer.
1111 ram_list.mru_block = block;
1112 return block;
1115 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1117 CPUState *cpu;
1118 ram_addr_t start1;
1119 RAMBlock *block;
1120 ram_addr_t end;
1122 end = TARGET_PAGE_ALIGN(start + length);
1123 start &= TARGET_PAGE_MASK;
1125 rcu_read_lock();
1126 block = qemu_get_ram_block(start);
1127 assert(block == qemu_get_ram_block(end - 1));
1128 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1129 CPU_FOREACH(cpu) {
1130 tlb_reset_dirty(cpu, start1, length);
1132 rcu_read_unlock();
1135 /* Note: start and end must be within the same ram block. */
1136 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1137 ram_addr_t length,
1138 unsigned client)
1140 DirtyMemoryBlocks *blocks;
1141 unsigned long end, page;
1142 bool dirty = false;
1144 if (length == 0) {
1145 return false;
1148 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1149 page = start >> TARGET_PAGE_BITS;
1151 rcu_read_lock();
1153 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1155 while (page < end) {
1156 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1157 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1158 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1160 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1161 offset, num);
1162 page += num;
1165 rcu_read_unlock();
1167 if (dirty && tcg_enabled()) {
1168 tlb_reset_dirty_range_all(start, length);
1171 return dirty;
1174 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1175 (ram_addr_t start, ram_addr_t length, unsigned client)
1177 DirtyMemoryBlocks *blocks;
1178 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1179 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1180 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1181 DirtyBitmapSnapshot *snap;
1182 unsigned long page, end, dest;
1184 snap = g_malloc0(sizeof(*snap) +
1185 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1186 snap->start = first;
1187 snap->end = last;
1189 page = first >> TARGET_PAGE_BITS;
1190 end = last >> TARGET_PAGE_BITS;
1191 dest = 0;
1193 rcu_read_lock();
1195 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1197 while (page < end) {
1198 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1199 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1200 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1202 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1203 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1204 offset >>= BITS_PER_LEVEL;
1206 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1207 blocks->blocks[idx] + offset,
1208 num);
1209 page += num;
1210 dest += num >> BITS_PER_LEVEL;
1213 rcu_read_unlock();
1215 if (tcg_enabled()) {
1216 tlb_reset_dirty_range_all(start, length);
1219 return snap;
1222 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1223 ram_addr_t start,
1224 ram_addr_t length)
1226 unsigned long page, end;
1228 assert(start >= snap->start);
1229 assert(start + length <= snap->end);
1231 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1232 page = (start - snap->start) >> TARGET_PAGE_BITS;
1234 while (page < end) {
1235 if (test_bit(page, snap->dirty)) {
1236 return true;
1238 page++;
1240 return false;
1243 /* Called from RCU critical section */
1244 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1245 MemoryRegionSection *section,
1246 target_ulong vaddr,
1247 hwaddr paddr, hwaddr xlat,
1248 int prot,
1249 target_ulong *address)
1251 hwaddr iotlb;
1252 CPUWatchpoint *wp;
1254 if (memory_region_is_ram(section->mr)) {
1255 /* Normal RAM. */
1256 iotlb = memory_region_get_ram_addr(section->mr) + xlat;
1257 if (!section->readonly) {
1258 iotlb |= PHYS_SECTION_NOTDIRTY;
1259 } else {
1260 iotlb |= PHYS_SECTION_ROM;
1262 } else {
1263 AddressSpaceDispatch *d;
1265 d = flatview_to_dispatch(section->fv);
1266 iotlb = section - d->map.sections;
1267 iotlb += xlat;
1270 /* Make accesses to pages with watchpoints go via the
1271 watchpoint trap routines. */
1272 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1273 if (cpu_watchpoint_address_matches(wp, vaddr, TARGET_PAGE_SIZE)) {
1274 /* Avoid trapping reads of pages with a write breakpoint. */
1275 if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
1276 iotlb = PHYS_SECTION_WATCH + paddr;
1277 *address |= TLB_MMIO;
1278 break;
1283 return iotlb;
1285 #endif /* defined(CONFIG_USER_ONLY) */
1287 #if !defined(CONFIG_USER_ONLY)
1289 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
1290 uint16_t section);
1291 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1293 static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
1294 qemu_anon_ram_alloc;
1297 * Set a custom physical guest memory alloator.
1298 * Accelerators with unusual needs may need this. Hopefully, we can
1299 * get rid of it eventually.
1301 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
1303 phys_mem_alloc = alloc;
1306 static uint16_t phys_section_add(PhysPageMap *map,
1307 MemoryRegionSection *section)
1309 /* The physical section number is ORed with a page-aligned
1310 * pointer to produce the iotlb entries. Thus it should
1311 * never overflow into the page-aligned value.
1313 assert(map->sections_nb < TARGET_PAGE_SIZE);
1315 if (map->sections_nb == map->sections_nb_alloc) {
1316 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1317 map->sections = g_renew(MemoryRegionSection, map->sections,
1318 map->sections_nb_alloc);
1320 map->sections[map->sections_nb] = *section;
1321 memory_region_ref(section->mr);
1322 return map->sections_nb++;
1325 static void phys_section_destroy(MemoryRegion *mr)
1327 bool have_sub_page = mr->subpage;
1329 memory_region_unref(mr);
1331 if (have_sub_page) {
1332 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1333 object_unref(OBJECT(&subpage->iomem));
1334 g_free(subpage);
1338 static void phys_sections_free(PhysPageMap *map)
1340 while (map->sections_nb > 0) {
1341 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1342 phys_section_destroy(section->mr);
1344 g_free(map->sections);
1345 g_free(map->nodes);
1348 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1350 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1351 subpage_t *subpage;
1352 hwaddr base = section->offset_within_address_space
1353 & TARGET_PAGE_MASK;
1354 MemoryRegionSection *existing = phys_page_find(d, base);
1355 MemoryRegionSection subsection = {
1356 .offset_within_address_space = base,
1357 .size = int128_make64(TARGET_PAGE_SIZE),
1359 hwaddr start, end;
1361 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1363 if (!(existing->mr->subpage)) {
1364 subpage = subpage_init(fv, base);
1365 subsection.fv = fv;
1366 subsection.mr = &subpage->iomem;
1367 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1368 phys_section_add(&d->map, &subsection));
1369 } else {
1370 subpage = container_of(existing->mr, subpage_t, iomem);
1372 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1373 end = start + int128_get64(section->size) - 1;
1374 subpage_register(subpage, start, end,
1375 phys_section_add(&d->map, section));
1379 static void register_multipage(FlatView *fv,
1380 MemoryRegionSection *section)
1382 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1383 hwaddr start_addr = section->offset_within_address_space;
1384 uint16_t section_index = phys_section_add(&d->map, section);
1385 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1386 TARGET_PAGE_BITS));
1388 assert(num_pages);
1389 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1392 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1394 MemoryRegionSection now = *section, remain = *section;
1395 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1397 if (now.offset_within_address_space & ~TARGET_PAGE_MASK) {
1398 uint64_t left = TARGET_PAGE_ALIGN(now.offset_within_address_space)
1399 - now.offset_within_address_space;
1401 now.size = int128_min(int128_make64(left), now.size);
1402 register_subpage(fv, &now);
1403 } else {
1404 now.size = int128_zero();
1406 while (int128_ne(remain.size, now.size)) {
1407 remain.size = int128_sub(remain.size, now.size);
1408 remain.offset_within_address_space += int128_get64(now.size);
1409 remain.offset_within_region += int128_get64(now.size);
1410 now = remain;
1411 if (int128_lt(remain.size, page_size)) {
1412 register_subpage(fv, &now);
1413 } else if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1414 now.size = page_size;
1415 register_subpage(fv, &now);
1416 } else {
1417 now.size = int128_and(now.size, int128_neg(page_size));
1418 register_multipage(fv, &now);
1423 void qemu_flush_coalesced_mmio_buffer(void)
1425 if (kvm_enabled())
1426 kvm_flush_coalesced_mmio_buffer();
1429 void qemu_mutex_lock_ramlist(void)
1431 qemu_mutex_lock(&ram_list.mutex);
1434 void qemu_mutex_unlock_ramlist(void)
1436 qemu_mutex_unlock(&ram_list.mutex);
1439 void ram_block_dump(Monitor *mon)
1441 RAMBlock *block;
1442 char *psize;
1444 rcu_read_lock();
1445 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1446 "Block Name", "PSize", "Offset", "Used", "Total");
1447 RAMBLOCK_FOREACH(block) {
1448 psize = size_to_str(block->page_size);
1449 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1450 " 0x%016" PRIx64 "\n", block->idstr, psize,
1451 (uint64_t)block->offset,
1452 (uint64_t)block->used_length,
1453 (uint64_t)block->max_length);
1454 g_free(psize);
1456 rcu_read_unlock();
1459 #ifdef __linux__
1461 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1462 * may or may not name the same files / on the same filesystem now as
1463 * when we actually open and map them. Iterate over the file
1464 * descriptors instead, and use qemu_fd_getpagesize().
1466 static int find_max_supported_pagesize(Object *obj, void *opaque)
1468 char *mem_path;
1469 long *hpsize_min = opaque;
1471 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1472 mem_path = object_property_get_str(obj, "mem-path", NULL);
1473 if (mem_path) {
1474 long hpsize = qemu_mempath_getpagesize(mem_path);
1475 if (hpsize < *hpsize_min) {
1476 *hpsize_min = hpsize;
1478 } else {
1479 *hpsize_min = getpagesize();
1483 return 0;
1486 long qemu_getrampagesize(void)
1488 long hpsize = LONG_MAX;
1489 long mainrampagesize;
1490 Object *memdev_root;
1492 if (mem_path) {
1493 mainrampagesize = qemu_mempath_getpagesize(mem_path);
1494 } else {
1495 mainrampagesize = getpagesize();
1498 /* it's possible we have memory-backend objects with
1499 * hugepage-backed RAM. these may get mapped into system
1500 * address space via -numa parameters or memory hotplug
1501 * hooks. we want to take these into account, but we
1502 * also want to make sure these supported hugepage
1503 * sizes are applicable across the entire range of memory
1504 * we may boot from, so we take the min across all
1505 * backends, and assume normal pages in cases where a
1506 * backend isn't backed by hugepages.
1508 memdev_root = object_resolve_path("/objects", NULL);
1509 if (memdev_root) {
1510 object_child_foreach(memdev_root, find_max_supported_pagesize, &hpsize);
1512 if (hpsize == LONG_MAX) {
1513 /* No additional memory regions found ==> Report main RAM page size */
1514 return mainrampagesize;
1517 /* If NUMA is disabled or the NUMA nodes are not backed with a
1518 * memory-backend, then there is at least one node using "normal" RAM,
1519 * so if its page size is smaller we have got to report that size instead.
1521 if (hpsize > mainrampagesize &&
1522 (nb_numa_nodes == 0 || numa_info[0].node_memdev == NULL)) {
1523 static bool warned;
1524 if (!warned) {
1525 error_report("Huge page support disabled (n/a for main memory).");
1526 warned = true;
1528 return mainrampagesize;
1531 return hpsize;
1533 #else
1534 long qemu_getrampagesize(void)
1536 return getpagesize();
1538 #endif
1540 #ifdef __linux__
1541 static int64_t get_file_size(int fd)
1543 int64_t size = lseek(fd, 0, SEEK_END);
1544 if (size < 0) {
1545 return -errno;
1547 return size;
1550 static int file_ram_open(const char *path,
1551 const char *region_name,
1552 bool *created,
1553 Error **errp)
1555 char *filename;
1556 char *sanitized_name;
1557 char *c;
1558 int fd = -1;
1560 *created = false;
1561 for (;;) {
1562 fd = open(path, O_RDWR);
1563 if (fd >= 0) {
1564 /* @path names an existing file, use it */
1565 break;
1567 if (errno == ENOENT) {
1568 /* @path names a file that doesn't exist, create it */
1569 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1570 if (fd >= 0) {
1571 *created = true;
1572 break;
1574 } else if (errno == EISDIR) {
1575 /* @path names a directory, create a file there */
1576 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1577 sanitized_name = g_strdup(region_name);
1578 for (c = sanitized_name; *c != '\0'; c++) {
1579 if (*c == '/') {
1580 *c = '_';
1584 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1585 sanitized_name);
1586 g_free(sanitized_name);
1588 fd = mkstemp(filename);
1589 if (fd >= 0) {
1590 unlink(filename);
1591 g_free(filename);
1592 break;
1594 g_free(filename);
1596 if (errno != EEXIST && errno != EINTR) {
1597 error_setg_errno(errp, errno,
1598 "can't open backing store %s for guest RAM",
1599 path);
1600 return -1;
1603 * Try again on EINTR and EEXIST. The latter happens when
1604 * something else creates the file between our two open().
1608 return fd;
1611 static void *file_ram_alloc(RAMBlock *block,
1612 ram_addr_t memory,
1613 int fd,
1614 bool truncate,
1615 Error **errp)
1617 void *area;
1619 block->page_size = qemu_fd_getpagesize(fd);
1620 if (block->mr->align % block->page_size) {
1621 error_setg(errp, "alignment 0x%" PRIx64
1622 " must be multiples of page size 0x%zx",
1623 block->mr->align, block->page_size);
1624 return NULL;
1626 block->mr->align = MAX(block->page_size, block->mr->align);
1627 #if defined(__s390x__)
1628 if (kvm_enabled()) {
1629 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1631 #endif
1633 if (memory < block->page_size) {
1634 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1635 "or larger than page size 0x%zx",
1636 memory, block->page_size);
1637 return NULL;
1640 memory = ROUND_UP(memory, block->page_size);
1643 * ftruncate is not supported by hugetlbfs in older
1644 * hosts, so don't bother bailing out on errors.
1645 * If anything goes wrong with it under other filesystems,
1646 * mmap will fail.
1648 * Do not truncate the non-empty backend file to avoid corrupting
1649 * the existing data in the file. Disabling shrinking is not
1650 * enough. For example, the current vNVDIMM implementation stores
1651 * the guest NVDIMM labels at the end of the backend file. If the
1652 * backend file is later extended, QEMU will not be able to find
1653 * those labels. Therefore, extending the non-empty backend file
1654 * is disabled as well.
1656 if (truncate && ftruncate(fd, memory)) {
1657 perror("ftruncate");
1660 area = qemu_ram_mmap(fd, memory, block->mr->align,
1661 block->flags & RAM_SHARED);
1662 if (area == MAP_FAILED) {
1663 error_setg_errno(errp, errno,
1664 "unable to map backing store for guest RAM");
1665 return NULL;
1668 if (mem_prealloc) {
1669 os_mem_prealloc(fd, area, memory, smp_cpus, errp);
1670 if (errp && *errp) {
1671 qemu_ram_munmap(area, memory);
1672 return NULL;
1676 block->fd = fd;
1677 return area;
1679 #endif
1681 /* Allocate space within the ram_addr_t space that governs the
1682 * dirty bitmaps.
1683 * Called with the ramlist lock held.
1685 static ram_addr_t find_ram_offset(ram_addr_t size)
1687 RAMBlock *block, *next_block;
1688 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1690 assert(size != 0); /* it would hand out same offset multiple times */
1692 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1693 return 0;
1696 RAMBLOCK_FOREACH(block) {
1697 ram_addr_t candidate, next = RAM_ADDR_MAX;
1699 /* Align blocks to start on a 'long' in the bitmap
1700 * which makes the bitmap sync'ing take the fast path.
1702 candidate = block->offset + block->max_length;
1703 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1705 /* Search for the closest following block
1706 * and find the gap.
1708 RAMBLOCK_FOREACH(next_block) {
1709 if (next_block->offset >= candidate) {
1710 next = MIN(next, next_block->offset);
1714 /* If it fits remember our place and remember the size
1715 * of gap, but keep going so that we might find a smaller
1716 * gap to fill so avoiding fragmentation.
1718 if (next - candidate >= size && next - candidate < mingap) {
1719 offset = candidate;
1720 mingap = next - candidate;
1723 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1726 if (offset == RAM_ADDR_MAX) {
1727 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1728 (uint64_t)size);
1729 abort();
1732 trace_find_ram_offset(size, offset);
1734 return offset;
1737 unsigned long last_ram_page(void)
1739 RAMBlock *block;
1740 ram_addr_t last = 0;
1742 rcu_read_lock();
1743 RAMBLOCK_FOREACH(block) {
1744 last = MAX(last, block->offset + block->max_length);
1746 rcu_read_unlock();
1747 return last >> TARGET_PAGE_BITS;
1750 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1752 int ret;
1754 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1755 if (!machine_dump_guest_core(current_machine)) {
1756 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1757 if (ret) {
1758 perror("qemu_madvise");
1759 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1760 "but dump_guest_core=off specified\n");
1765 const char *qemu_ram_get_idstr(RAMBlock *rb)
1767 return rb->idstr;
1770 bool qemu_ram_is_shared(RAMBlock *rb)
1772 return rb->flags & RAM_SHARED;
1775 /* Note: Only set at the start of postcopy */
1776 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1778 return rb->flags & RAM_UF_ZEROPAGE;
1781 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1783 rb->flags |= RAM_UF_ZEROPAGE;
1786 /* Called with iothread lock held. */
1787 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1789 RAMBlock *block;
1791 assert(new_block);
1792 assert(!new_block->idstr[0]);
1794 if (dev) {
1795 char *id = qdev_get_dev_path(dev);
1796 if (id) {
1797 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1798 g_free(id);
1801 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1803 rcu_read_lock();
1804 RAMBLOCK_FOREACH(block) {
1805 if (block != new_block &&
1806 !strcmp(block->idstr, new_block->idstr)) {
1807 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1808 new_block->idstr);
1809 abort();
1812 rcu_read_unlock();
1815 /* Called with iothread lock held. */
1816 void qemu_ram_unset_idstr(RAMBlock *block)
1818 /* FIXME: arch_init.c assumes that this is not called throughout
1819 * migration. Ignore the problem since hot-unplug during migration
1820 * does not work anyway.
1822 if (block) {
1823 memset(block->idstr, 0, sizeof(block->idstr));
1827 size_t qemu_ram_pagesize(RAMBlock *rb)
1829 return rb->page_size;
1832 /* Returns the largest size of page in use */
1833 size_t qemu_ram_pagesize_largest(void)
1835 RAMBlock *block;
1836 size_t largest = 0;
1838 RAMBLOCK_FOREACH(block) {
1839 largest = MAX(largest, qemu_ram_pagesize(block));
1842 return largest;
1845 static int memory_try_enable_merging(void *addr, size_t len)
1847 if (!machine_mem_merge(current_machine)) {
1848 /* disabled by the user */
1849 return 0;
1852 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1855 /* Only legal before guest might have detected the memory size: e.g. on
1856 * incoming migration, or right after reset.
1858 * As memory core doesn't know how is memory accessed, it is up to
1859 * resize callback to update device state and/or add assertions to detect
1860 * misuse, if necessary.
1862 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1864 assert(block);
1866 newsize = HOST_PAGE_ALIGN(newsize);
1868 if (block->used_length == newsize) {
1869 return 0;
1872 if (!(block->flags & RAM_RESIZEABLE)) {
1873 error_setg_errno(errp, EINVAL,
1874 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1875 " in != 0x" RAM_ADDR_FMT, block->idstr,
1876 newsize, block->used_length);
1877 return -EINVAL;
1880 if (block->max_length < newsize) {
1881 error_setg_errno(errp, EINVAL,
1882 "Length too large: %s: 0x" RAM_ADDR_FMT
1883 " > 0x" RAM_ADDR_FMT, block->idstr,
1884 newsize, block->max_length);
1885 return -EINVAL;
1888 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1889 block->used_length = newsize;
1890 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1891 DIRTY_CLIENTS_ALL);
1892 memory_region_set_size(block->mr, newsize);
1893 if (block->resized) {
1894 block->resized(block->idstr, newsize, block->host);
1896 return 0;
1899 /* Called with ram_list.mutex held */
1900 static void dirty_memory_extend(ram_addr_t old_ram_size,
1901 ram_addr_t new_ram_size)
1903 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1904 DIRTY_MEMORY_BLOCK_SIZE);
1905 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1906 DIRTY_MEMORY_BLOCK_SIZE);
1907 int i;
1909 /* Only need to extend if block count increased */
1910 if (new_num_blocks <= old_num_blocks) {
1911 return;
1914 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1915 DirtyMemoryBlocks *old_blocks;
1916 DirtyMemoryBlocks *new_blocks;
1917 int j;
1919 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
1920 new_blocks = g_malloc(sizeof(*new_blocks) +
1921 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1923 if (old_num_blocks) {
1924 memcpy(new_blocks->blocks, old_blocks->blocks,
1925 old_num_blocks * sizeof(old_blocks->blocks[0]));
1928 for (j = old_num_blocks; j < new_num_blocks; j++) {
1929 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1932 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1934 if (old_blocks) {
1935 g_free_rcu(old_blocks, rcu);
1940 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
1942 RAMBlock *block;
1943 RAMBlock *last_block = NULL;
1944 ram_addr_t old_ram_size, new_ram_size;
1945 Error *err = NULL;
1947 old_ram_size = last_ram_page();
1949 qemu_mutex_lock_ramlist();
1950 new_block->offset = find_ram_offset(new_block->max_length);
1952 if (!new_block->host) {
1953 if (xen_enabled()) {
1954 xen_ram_alloc(new_block->offset, new_block->max_length,
1955 new_block->mr, &err);
1956 if (err) {
1957 error_propagate(errp, err);
1958 qemu_mutex_unlock_ramlist();
1959 return;
1961 } else {
1962 new_block->host = phys_mem_alloc(new_block->max_length,
1963 &new_block->mr->align, shared);
1964 if (!new_block->host) {
1965 error_setg_errno(errp, errno,
1966 "cannot set up guest memory '%s'",
1967 memory_region_name(new_block->mr));
1968 qemu_mutex_unlock_ramlist();
1969 return;
1971 memory_try_enable_merging(new_block->host, new_block->max_length);
1975 new_ram_size = MAX(old_ram_size,
1976 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1977 if (new_ram_size > old_ram_size) {
1978 dirty_memory_extend(old_ram_size, new_ram_size);
1980 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1981 * QLIST (which has an RCU-friendly variant) does not have insertion at
1982 * tail, so save the last element in last_block.
1984 RAMBLOCK_FOREACH(block) {
1985 last_block = block;
1986 if (block->max_length < new_block->max_length) {
1987 break;
1990 if (block) {
1991 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1992 } else if (last_block) {
1993 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
1994 } else { /* list is empty */
1995 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1997 ram_list.mru_block = NULL;
1999 /* Write list before version */
2000 smp_wmb();
2001 ram_list.version++;
2002 qemu_mutex_unlock_ramlist();
2004 cpu_physical_memory_set_dirty_range(new_block->offset,
2005 new_block->used_length,
2006 DIRTY_CLIENTS_ALL);
2008 if (new_block->host) {
2009 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2010 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2011 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
2012 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
2013 ram_block_notify_add(new_block->host, new_block->max_length);
2017 #ifdef __linux__
2018 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2019 bool share, int fd,
2020 Error **errp)
2022 RAMBlock *new_block;
2023 Error *local_err = NULL;
2024 int64_t file_size;
2026 if (xen_enabled()) {
2027 error_setg(errp, "-mem-path not supported with Xen");
2028 return NULL;
2031 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2032 error_setg(errp,
2033 "host lacks kvm mmu notifiers, -mem-path unsupported");
2034 return NULL;
2037 if (phys_mem_alloc != qemu_anon_ram_alloc) {
2039 * file_ram_alloc() needs to allocate just like
2040 * phys_mem_alloc, but we haven't bothered to provide
2041 * a hook there.
2043 error_setg(errp,
2044 "-mem-path not supported with this accelerator");
2045 return NULL;
2048 size = HOST_PAGE_ALIGN(size);
2049 file_size = get_file_size(fd);
2050 if (file_size > 0 && file_size < size) {
2051 error_setg(errp, "backing store %s size 0x%" PRIx64
2052 " does not match 'size' option 0x" RAM_ADDR_FMT,
2053 mem_path, file_size, size);
2054 return NULL;
2057 new_block = g_malloc0(sizeof(*new_block));
2058 new_block->mr = mr;
2059 new_block->used_length = size;
2060 new_block->max_length = size;
2061 new_block->flags = share ? RAM_SHARED : 0;
2062 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
2063 if (!new_block->host) {
2064 g_free(new_block);
2065 return NULL;
2068 ram_block_add(new_block, &local_err, share);
2069 if (local_err) {
2070 g_free(new_block);
2071 error_propagate(errp, local_err);
2072 return NULL;
2074 return new_block;
2079 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2080 bool share, const char *mem_path,
2081 Error **errp)
2083 int fd;
2084 bool created;
2085 RAMBlock *block;
2087 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2088 if (fd < 0) {
2089 return NULL;
2092 block = qemu_ram_alloc_from_fd(size, mr, share, fd, errp);
2093 if (!block) {
2094 if (created) {
2095 unlink(mem_path);
2097 close(fd);
2098 return NULL;
2101 return block;
2103 #endif
2105 static
2106 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2107 void (*resized)(const char*,
2108 uint64_t length,
2109 void *host),
2110 void *host, bool resizeable, bool share,
2111 MemoryRegion *mr, Error **errp)
2113 RAMBlock *new_block;
2114 Error *local_err = NULL;
2116 size = HOST_PAGE_ALIGN(size);
2117 max_size = HOST_PAGE_ALIGN(max_size);
2118 new_block = g_malloc0(sizeof(*new_block));
2119 new_block->mr = mr;
2120 new_block->resized = resized;
2121 new_block->used_length = size;
2122 new_block->max_length = max_size;
2123 assert(max_size >= size);
2124 new_block->fd = -1;
2125 new_block->page_size = getpagesize();
2126 new_block->host = host;
2127 if (host) {
2128 new_block->flags |= RAM_PREALLOC;
2130 if (resizeable) {
2131 new_block->flags |= RAM_RESIZEABLE;
2133 ram_block_add(new_block, &local_err, share);
2134 if (local_err) {
2135 g_free(new_block);
2136 error_propagate(errp, local_err);
2137 return NULL;
2139 return new_block;
2142 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2143 MemoryRegion *mr, Error **errp)
2145 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2146 false, mr, errp);
2149 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2150 MemoryRegion *mr, Error **errp)
2152 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2153 share, mr, errp);
2156 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2157 void (*resized)(const char*,
2158 uint64_t length,
2159 void *host),
2160 MemoryRegion *mr, Error **errp)
2162 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2163 false, mr, errp);
2166 static void reclaim_ramblock(RAMBlock *block)
2168 if (block->flags & RAM_PREALLOC) {
2170 } else if (xen_enabled()) {
2171 xen_invalidate_map_cache_entry(block->host);
2172 #ifndef _WIN32
2173 } else if (block->fd >= 0) {
2174 qemu_ram_munmap(block->host, block->max_length);
2175 close(block->fd);
2176 #endif
2177 } else {
2178 qemu_anon_ram_free(block->host, block->max_length);
2180 g_free(block);
2183 void qemu_ram_free(RAMBlock *block)
2185 if (!block) {
2186 return;
2189 if (block->host) {
2190 ram_block_notify_remove(block->host, block->max_length);
2193 qemu_mutex_lock_ramlist();
2194 QLIST_REMOVE_RCU(block, next);
2195 ram_list.mru_block = NULL;
2196 /* Write list before version */
2197 smp_wmb();
2198 ram_list.version++;
2199 call_rcu(block, reclaim_ramblock, rcu);
2200 qemu_mutex_unlock_ramlist();
2203 #ifndef _WIN32
2204 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2206 RAMBlock *block;
2207 ram_addr_t offset;
2208 int flags;
2209 void *area, *vaddr;
2211 RAMBLOCK_FOREACH(block) {
2212 offset = addr - block->offset;
2213 if (offset < block->max_length) {
2214 vaddr = ramblock_ptr(block, offset);
2215 if (block->flags & RAM_PREALLOC) {
2217 } else if (xen_enabled()) {
2218 abort();
2219 } else {
2220 flags = MAP_FIXED;
2221 if (block->fd >= 0) {
2222 flags |= (block->flags & RAM_SHARED ?
2223 MAP_SHARED : MAP_PRIVATE);
2224 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2225 flags, block->fd, offset);
2226 } else {
2228 * Remap needs to match alloc. Accelerators that
2229 * set phys_mem_alloc never remap. If they did,
2230 * we'd need a remap hook here.
2232 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2234 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2235 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2236 flags, -1, 0);
2238 if (area != vaddr) {
2239 error_report("Could not remap addr: "
2240 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2241 length, addr);
2242 exit(1);
2244 memory_try_enable_merging(vaddr, length);
2245 qemu_ram_setup_dump(vaddr, length);
2250 #endif /* !_WIN32 */
2252 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2253 * This should not be used for general purpose DMA. Use address_space_map
2254 * or address_space_rw instead. For local memory (e.g. video ram) that the
2255 * device owns, use memory_region_get_ram_ptr.
2257 * Called within RCU critical section.
2259 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2261 RAMBlock *block = ram_block;
2263 if (block == NULL) {
2264 block = qemu_get_ram_block(addr);
2265 addr -= block->offset;
2268 if (xen_enabled() && block->host == NULL) {
2269 /* We need to check if the requested address is in the RAM
2270 * because we don't want to map the entire memory in QEMU.
2271 * In that case just map until the end of the page.
2273 if (block->offset == 0) {
2274 return xen_map_cache(addr, 0, 0, false);
2277 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2279 return ramblock_ptr(block, addr);
2282 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2283 * but takes a size argument.
2285 * Called within RCU critical section.
2287 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2288 hwaddr *size, bool lock)
2290 RAMBlock *block = ram_block;
2291 if (*size == 0) {
2292 return NULL;
2295 if (block == NULL) {
2296 block = qemu_get_ram_block(addr);
2297 addr -= block->offset;
2299 *size = MIN(*size, block->max_length - addr);
2301 if (xen_enabled() && block->host == NULL) {
2302 /* We need to check if the requested address is in the RAM
2303 * because we don't want to map the entire memory in QEMU.
2304 * In that case just map the requested area.
2306 if (block->offset == 0) {
2307 return xen_map_cache(addr, *size, lock, lock);
2310 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2313 return ramblock_ptr(block, addr);
2316 /* Return the offset of a hostpointer within a ramblock */
2317 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2319 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2320 assert((uintptr_t)host >= (uintptr_t)rb->host);
2321 assert(res < rb->max_length);
2323 return res;
2327 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2328 * in that RAMBlock.
2330 * ptr: Host pointer to look up
2331 * round_offset: If true round the result offset down to a page boundary
2332 * *ram_addr: set to result ram_addr
2333 * *offset: set to result offset within the RAMBlock
2335 * Returns: RAMBlock (or NULL if not found)
2337 * By the time this function returns, the returned pointer is not protected
2338 * by RCU anymore. If the caller is not within an RCU critical section and
2339 * does not hold the iothread lock, it must have other means of protecting the
2340 * pointer, such as a reference to the region that includes the incoming
2341 * ram_addr_t.
2343 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2344 ram_addr_t *offset)
2346 RAMBlock *block;
2347 uint8_t *host = ptr;
2349 if (xen_enabled()) {
2350 ram_addr_t ram_addr;
2351 rcu_read_lock();
2352 ram_addr = xen_ram_addr_from_mapcache(ptr);
2353 block = qemu_get_ram_block(ram_addr);
2354 if (block) {
2355 *offset = ram_addr - block->offset;
2357 rcu_read_unlock();
2358 return block;
2361 rcu_read_lock();
2362 block = atomic_rcu_read(&ram_list.mru_block);
2363 if (block && block->host && host - block->host < block->max_length) {
2364 goto found;
2367 RAMBLOCK_FOREACH(block) {
2368 /* This case append when the block is not mapped. */
2369 if (block->host == NULL) {
2370 continue;
2372 if (host - block->host < block->max_length) {
2373 goto found;
2377 rcu_read_unlock();
2378 return NULL;
2380 found:
2381 *offset = (host - block->host);
2382 if (round_offset) {
2383 *offset &= TARGET_PAGE_MASK;
2385 rcu_read_unlock();
2386 return block;
2390 * Finds the named RAMBlock
2392 * name: The name of RAMBlock to find
2394 * Returns: RAMBlock (or NULL if not found)
2396 RAMBlock *qemu_ram_block_by_name(const char *name)
2398 RAMBlock *block;
2400 RAMBLOCK_FOREACH(block) {
2401 if (!strcmp(name, block->idstr)) {
2402 return block;
2406 return NULL;
2409 /* Some of the softmmu routines need to translate from a host pointer
2410 (typically a TLB entry) back to a ram offset. */
2411 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2413 RAMBlock *block;
2414 ram_addr_t offset;
2416 block = qemu_ram_block_from_host(ptr, false, &offset);
2417 if (!block) {
2418 return RAM_ADDR_INVALID;
2421 return block->offset + offset;
2424 /* Called within RCU critical section. */
2425 void memory_notdirty_write_prepare(NotDirtyInfo *ndi,
2426 CPUState *cpu,
2427 vaddr mem_vaddr,
2428 ram_addr_t ram_addr,
2429 unsigned size)
2431 ndi->cpu = cpu;
2432 ndi->ram_addr = ram_addr;
2433 ndi->mem_vaddr = mem_vaddr;
2434 ndi->size = size;
2435 ndi->locked = false;
2437 assert(tcg_enabled());
2438 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
2439 ndi->locked = true;
2440 tb_lock();
2441 tb_invalidate_phys_page_fast(ram_addr, size);
2445 /* Called within RCU critical section. */
2446 void memory_notdirty_write_complete(NotDirtyInfo *ndi)
2448 if (ndi->locked) {
2449 tb_unlock();
2452 /* Set both VGA and migration bits for simplicity and to remove
2453 * the notdirty callback faster.
2455 cpu_physical_memory_set_dirty_range(ndi->ram_addr, ndi->size,
2456 DIRTY_CLIENTS_NOCODE);
2457 /* we remove the notdirty callback only if the code has been
2458 flushed */
2459 if (!cpu_physical_memory_is_clean(ndi->ram_addr)) {
2460 tlb_set_dirty(ndi->cpu, ndi->mem_vaddr);
2464 /* Called within RCU critical section. */
2465 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2466 uint64_t val, unsigned size)
2468 NotDirtyInfo ndi;
2470 memory_notdirty_write_prepare(&ndi, current_cpu, current_cpu->mem_io_vaddr,
2471 ram_addr, size);
2473 switch (size) {
2474 case 1:
2475 stb_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2476 break;
2477 case 2:
2478 stw_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2479 break;
2480 case 4:
2481 stl_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2482 break;
2483 case 8:
2484 stq_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2485 break;
2486 default:
2487 abort();
2489 memory_notdirty_write_complete(&ndi);
2492 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
2493 unsigned size, bool is_write)
2495 return is_write;
2498 static const MemoryRegionOps notdirty_mem_ops = {
2499 .write = notdirty_mem_write,
2500 .valid.accepts = notdirty_mem_accepts,
2501 .endianness = DEVICE_NATIVE_ENDIAN,
2502 .valid = {
2503 .min_access_size = 1,
2504 .max_access_size = 8,
2505 .unaligned = false,
2507 .impl = {
2508 .min_access_size = 1,
2509 .max_access_size = 8,
2510 .unaligned = false,
2514 /* Generate a debug exception if a watchpoint has been hit. */
2515 static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
2517 CPUState *cpu = current_cpu;
2518 CPUClass *cc = CPU_GET_CLASS(cpu);
2519 target_ulong vaddr;
2520 CPUWatchpoint *wp;
2522 assert(tcg_enabled());
2523 if (cpu->watchpoint_hit) {
2524 /* We re-entered the check after replacing the TB. Now raise
2525 * the debug interrupt so that is will trigger after the
2526 * current instruction. */
2527 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2528 return;
2530 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
2531 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
2532 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2533 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2534 && (wp->flags & flags)) {
2535 if (flags == BP_MEM_READ) {
2536 wp->flags |= BP_WATCHPOINT_HIT_READ;
2537 } else {
2538 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2540 wp->hitaddr = vaddr;
2541 wp->hitattrs = attrs;
2542 if (!cpu->watchpoint_hit) {
2543 if (wp->flags & BP_CPU &&
2544 !cc->debug_check_watchpoint(cpu, wp)) {
2545 wp->flags &= ~BP_WATCHPOINT_HIT;
2546 continue;
2548 cpu->watchpoint_hit = wp;
2550 /* Both tb_lock and iothread_mutex will be reset when
2551 * cpu_loop_exit or cpu_loop_exit_noexc longjmp
2552 * back into the cpu_exec main loop.
2554 tb_lock();
2555 tb_check_watchpoint(cpu);
2556 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2557 cpu->exception_index = EXCP_DEBUG;
2558 cpu_loop_exit(cpu);
2559 } else {
2560 /* Force execution of one insn next time. */
2561 cpu->cflags_next_tb = 1 | curr_cflags();
2562 cpu_loop_exit_noexc(cpu);
2565 } else {
2566 wp->flags &= ~BP_WATCHPOINT_HIT;
2571 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2572 so these check for a hit then pass through to the normal out-of-line
2573 phys routines. */
2574 static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2575 unsigned size, MemTxAttrs attrs)
2577 MemTxResult res;
2578 uint64_t data;
2579 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2580 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2582 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2583 switch (size) {
2584 case 1:
2585 data = address_space_ldub(as, addr, attrs, &res);
2586 break;
2587 case 2:
2588 data = address_space_lduw(as, addr, attrs, &res);
2589 break;
2590 case 4:
2591 data = address_space_ldl(as, addr, attrs, &res);
2592 break;
2593 case 8:
2594 data = address_space_ldq(as, addr, attrs, &res);
2595 break;
2596 default: abort();
2598 *pdata = data;
2599 return res;
2602 static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2603 uint64_t val, unsigned size,
2604 MemTxAttrs attrs)
2606 MemTxResult res;
2607 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2608 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2610 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2611 switch (size) {
2612 case 1:
2613 address_space_stb(as, addr, val, attrs, &res);
2614 break;
2615 case 2:
2616 address_space_stw(as, addr, val, attrs, &res);
2617 break;
2618 case 4:
2619 address_space_stl(as, addr, val, attrs, &res);
2620 break;
2621 case 8:
2622 address_space_stq(as, addr, val, attrs, &res);
2623 break;
2624 default: abort();
2626 return res;
2629 static const MemoryRegionOps watch_mem_ops = {
2630 .read_with_attrs = watch_mem_read,
2631 .write_with_attrs = watch_mem_write,
2632 .endianness = DEVICE_NATIVE_ENDIAN,
2633 .valid = {
2634 .min_access_size = 1,
2635 .max_access_size = 8,
2636 .unaligned = false,
2638 .impl = {
2639 .min_access_size = 1,
2640 .max_access_size = 8,
2641 .unaligned = false,
2645 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2646 MemTxAttrs attrs, uint8_t *buf, int len);
2647 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2648 const uint8_t *buf, int len);
2649 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
2650 bool is_write);
2652 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2653 unsigned len, MemTxAttrs attrs)
2655 subpage_t *subpage = opaque;
2656 uint8_t buf[8];
2657 MemTxResult res;
2659 #if defined(DEBUG_SUBPAGE)
2660 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2661 subpage, len, addr);
2662 #endif
2663 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2664 if (res) {
2665 return res;
2667 switch (len) {
2668 case 1:
2669 *data = ldub_p(buf);
2670 return MEMTX_OK;
2671 case 2:
2672 *data = lduw_p(buf);
2673 return MEMTX_OK;
2674 case 4:
2675 *data = ldl_p(buf);
2676 return MEMTX_OK;
2677 case 8:
2678 *data = ldq_p(buf);
2679 return MEMTX_OK;
2680 default:
2681 abort();
2685 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2686 uint64_t value, unsigned len, MemTxAttrs attrs)
2688 subpage_t *subpage = opaque;
2689 uint8_t buf[8];
2691 #if defined(DEBUG_SUBPAGE)
2692 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2693 " value %"PRIx64"\n",
2694 __func__, subpage, len, addr, value);
2695 #endif
2696 switch (len) {
2697 case 1:
2698 stb_p(buf, value);
2699 break;
2700 case 2:
2701 stw_p(buf, value);
2702 break;
2703 case 4:
2704 stl_p(buf, value);
2705 break;
2706 case 8:
2707 stq_p(buf, value);
2708 break;
2709 default:
2710 abort();
2712 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2715 static bool subpage_accepts(void *opaque, hwaddr addr,
2716 unsigned len, bool is_write)
2718 subpage_t *subpage = opaque;
2719 #if defined(DEBUG_SUBPAGE)
2720 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2721 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2722 #endif
2724 return flatview_access_valid(subpage->fv, addr + subpage->base,
2725 len, is_write);
2728 static const MemoryRegionOps subpage_ops = {
2729 .read_with_attrs = subpage_read,
2730 .write_with_attrs = subpage_write,
2731 .impl.min_access_size = 1,
2732 .impl.max_access_size = 8,
2733 .valid.min_access_size = 1,
2734 .valid.max_access_size = 8,
2735 .valid.accepts = subpage_accepts,
2736 .endianness = DEVICE_NATIVE_ENDIAN,
2739 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
2740 uint16_t section)
2742 int idx, eidx;
2744 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2745 return -1;
2746 idx = SUBPAGE_IDX(start);
2747 eidx = SUBPAGE_IDX(end);
2748 #if defined(DEBUG_SUBPAGE)
2749 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2750 __func__, mmio, start, end, idx, eidx, section);
2751 #endif
2752 for (; idx <= eidx; idx++) {
2753 mmio->sub_section[idx] = section;
2756 return 0;
2759 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2761 subpage_t *mmio;
2763 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2764 mmio->fv = fv;
2765 mmio->base = base;
2766 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2767 NULL, TARGET_PAGE_SIZE);
2768 mmio->iomem.subpage = true;
2769 #if defined(DEBUG_SUBPAGE)
2770 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2771 mmio, base, TARGET_PAGE_SIZE);
2772 #endif
2773 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
2775 return mmio;
2778 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2780 assert(fv);
2781 MemoryRegionSection section = {
2782 .fv = fv,
2783 .mr = mr,
2784 .offset_within_address_space = 0,
2785 .offset_within_region = 0,
2786 .size = int128_2_64(),
2789 return phys_section_add(map, &section);
2792 static void readonly_mem_write(void *opaque, hwaddr addr,
2793 uint64_t val, unsigned size)
2795 /* Ignore any write to ROM. */
2798 static bool readonly_mem_accepts(void *opaque, hwaddr addr,
2799 unsigned size, bool is_write)
2801 return is_write;
2804 /* This will only be used for writes, because reads are special cased
2805 * to directly access the underlying host ram.
2807 static const MemoryRegionOps readonly_mem_ops = {
2808 .write = readonly_mem_write,
2809 .valid.accepts = readonly_mem_accepts,
2810 .endianness = DEVICE_NATIVE_ENDIAN,
2811 .valid = {
2812 .min_access_size = 1,
2813 .max_access_size = 8,
2814 .unaligned = false,
2816 .impl = {
2817 .min_access_size = 1,
2818 .max_access_size = 8,
2819 .unaligned = false,
2823 MemoryRegion *iotlb_to_region(CPUState *cpu, hwaddr index, MemTxAttrs attrs)
2825 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2826 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2827 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
2828 MemoryRegionSection *sections = d->map.sections;
2830 return sections[index & ~TARGET_PAGE_MASK].mr;
2833 static void io_mem_init(void)
2835 memory_region_init_io(&io_mem_rom, NULL, &readonly_mem_ops,
2836 NULL, NULL, UINT64_MAX);
2837 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2838 NULL, UINT64_MAX);
2840 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
2841 * which can be called without the iothread mutex.
2843 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
2844 NULL, UINT64_MAX);
2845 memory_region_clear_global_locking(&io_mem_notdirty);
2847 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
2848 NULL, UINT64_MAX);
2851 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2853 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2854 uint16_t n;
2856 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2857 assert(n == PHYS_SECTION_UNASSIGNED);
2858 n = dummy_section(&d->map, fv, &io_mem_notdirty);
2859 assert(n == PHYS_SECTION_NOTDIRTY);
2860 n = dummy_section(&d->map, fv, &io_mem_rom);
2861 assert(n == PHYS_SECTION_ROM);
2862 n = dummy_section(&d->map, fv, &io_mem_watch);
2863 assert(n == PHYS_SECTION_WATCH);
2865 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2867 return d;
2870 void address_space_dispatch_free(AddressSpaceDispatch *d)
2872 phys_sections_free(&d->map);
2873 g_free(d);
2876 static void tcg_commit(MemoryListener *listener)
2878 CPUAddressSpace *cpuas;
2879 AddressSpaceDispatch *d;
2881 /* since each CPU stores ram addresses in its TLB cache, we must
2882 reset the modified entries */
2883 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2884 cpu_reloading_memory_map();
2885 /* The CPU and TLB are protected by the iothread lock.
2886 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2887 * may have split the RCU critical section.
2889 d = address_space_to_dispatch(cpuas->as);
2890 atomic_rcu_set(&cpuas->memory_dispatch, d);
2891 tlb_flush(cpuas->cpu);
2894 static void memory_map_init(void)
2896 system_memory = g_malloc(sizeof(*system_memory));
2898 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2899 address_space_init(&address_space_memory, system_memory, "memory");
2901 system_io = g_malloc(sizeof(*system_io));
2902 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2903 65536);
2904 address_space_init(&address_space_io, system_io, "I/O");
2907 MemoryRegion *get_system_memory(void)
2909 return system_memory;
2912 MemoryRegion *get_system_io(void)
2914 return system_io;
2917 #endif /* !defined(CONFIG_USER_ONLY) */
2919 /* physical memory access (slow version, mainly for debug) */
2920 #if defined(CONFIG_USER_ONLY)
2921 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
2922 uint8_t *buf, int len, int is_write)
2924 int l, flags;
2925 target_ulong page;
2926 void * p;
2928 while (len > 0) {
2929 page = addr & TARGET_PAGE_MASK;
2930 l = (page + TARGET_PAGE_SIZE) - addr;
2931 if (l > len)
2932 l = len;
2933 flags = page_get_flags(page);
2934 if (!(flags & PAGE_VALID))
2935 return -1;
2936 if (is_write) {
2937 if (!(flags & PAGE_WRITE))
2938 return -1;
2939 /* XXX: this code should not depend on lock_user */
2940 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
2941 return -1;
2942 memcpy(p, buf, l);
2943 unlock_user(p, addr, l);
2944 } else {
2945 if (!(flags & PAGE_READ))
2946 return -1;
2947 /* XXX: this code should not depend on lock_user */
2948 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
2949 return -1;
2950 memcpy(buf, p, l);
2951 unlock_user(p, addr, 0);
2953 len -= l;
2954 buf += l;
2955 addr += l;
2957 return 0;
2960 #else
2962 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2963 hwaddr length)
2965 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2966 addr += memory_region_get_ram_addr(mr);
2968 /* No early return if dirty_log_mask is or becomes 0, because
2969 * cpu_physical_memory_set_dirty_range will still call
2970 * xen_modified_memory.
2972 if (dirty_log_mask) {
2973 dirty_log_mask =
2974 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2976 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2977 assert(tcg_enabled());
2978 tb_lock();
2979 tb_invalidate_phys_range(addr, addr + length);
2980 tb_unlock();
2981 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2983 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2986 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2988 unsigned access_size_max = mr->ops->valid.max_access_size;
2990 /* Regions are assumed to support 1-4 byte accesses unless
2991 otherwise specified. */
2992 if (access_size_max == 0) {
2993 access_size_max = 4;
2996 /* Bound the maximum access by the alignment of the address. */
2997 if (!mr->ops->impl.unaligned) {
2998 unsigned align_size_max = addr & -addr;
2999 if (align_size_max != 0 && align_size_max < access_size_max) {
3000 access_size_max = align_size_max;
3004 /* Don't attempt accesses larger than the maximum. */
3005 if (l > access_size_max) {
3006 l = access_size_max;
3008 l = pow2floor(l);
3010 return l;
3013 static bool prepare_mmio_access(MemoryRegion *mr)
3015 bool unlocked = !qemu_mutex_iothread_locked();
3016 bool release_lock = false;
3018 if (unlocked && mr->global_locking) {
3019 qemu_mutex_lock_iothread();
3020 unlocked = false;
3021 release_lock = true;
3023 if (mr->flush_coalesced_mmio) {
3024 if (unlocked) {
3025 qemu_mutex_lock_iothread();
3027 qemu_flush_coalesced_mmio_buffer();
3028 if (unlocked) {
3029 qemu_mutex_unlock_iothread();
3033 return release_lock;
3036 /* Called within RCU critical section. */
3037 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
3038 MemTxAttrs attrs,
3039 const uint8_t *buf,
3040 int len, hwaddr addr1,
3041 hwaddr l, MemoryRegion *mr)
3043 uint8_t *ptr;
3044 uint64_t val;
3045 MemTxResult result = MEMTX_OK;
3046 bool release_lock = false;
3048 for (;;) {
3049 if (!memory_access_is_direct(mr, true)) {
3050 release_lock |= prepare_mmio_access(mr);
3051 l = memory_access_size(mr, l, addr1);
3052 /* XXX: could force current_cpu to NULL to avoid
3053 potential bugs */
3054 switch (l) {
3055 case 8:
3056 /* 64 bit write access */
3057 val = ldq_p(buf);
3058 result |= memory_region_dispatch_write(mr, addr1, val, 8,
3059 attrs);
3060 break;
3061 case 4:
3062 /* 32 bit write access */
3063 val = (uint32_t)ldl_p(buf);
3064 result |= memory_region_dispatch_write(mr, addr1, val, 4,
3065 attrs);
3066 break;
3067 case 2:
3068 /* 16 bit write access */
3069 val = lduw_p(buf);
3070 result |= memory_region_dispatch_write(mr, addr1, val, 2,
3071 attrs);
3072 break;
3073 case 1:
3074 /* 8 bit write access */
3075 val = ldub_p(buf);
3076 result |= memory_region_dispatch_write(mr, addr1, val, 1,
3077 attrs);
3078 break;
3079 default:
3080 abort();
3082 } else {
3083 /* RAM case */
3084 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3085 memcpy(ptr, buf, l);
3086 invalidate_and_set_dirty(mr, addr1, l);
3089 if (release_lock) {
3090 qemu_mutex_unlock_iothread();
3091 release_lock = false;
3094 len -= l;
3095 buf += l;
3096 addr += l;
3098 if (!len) {
3099 break;
3102 l = len;
3103 mr = flatview_translate(fv, addr, &addr1, &l, true);
3106 return result;
3109 /* Called from RCU critical section. */
3110 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
3111 const uint8_t *buf, int len)
3113 hwaddr l;
3114 hwaddr addr1;
3115 MemoryRegion *mr;
3116 MemTxResult result = MEMTX_OK;
3118 l = len;
3119 mr = flatview_translate(fv, addr, &addr1, &l, true);
3120 result = flatview_write_continue(fv, addr, attrs, buf, len,
3121 addr1, l, mr);
3123 return result;
3126 /* Called within RCU critical section. */
3127 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
3128 MemTxAttrs attrs, uint8_t *buf,
3129 int len, hwaddr addr1, hwaddr l,
3130 MemoryRegion *mr)
3132 uint8_t *ptr;
3133 uint64_t val;
3134 MemTxResult result = MEMTX_OK;
3135 bool release_lock = false;
3137 for (;;) {
3138 if (!memory_access_is_direct(mr, false)) {
3139 /* I/O case */
3140 release_lock |= prepare_mmio_access(mr);
3141 l = memory_access_size(mr, l, addr1);
3142 switch (l) {
3143 case 8:
3144 /* 64 bit read access */
3145 result |= memory_region_dispatch_read(mr, addr1, &val, 8,
3146 attrs);
3147 stq_p(buf, val);
3148 break;
3149 case 4:
3150 /* 32 bit read access */
3151 result |= memory_region_dispatch_read(mr, addr1, &val, 4,
3152 attrs);
3153 stl_p(buf, val);
3154 break;
3155 case 2:
3156 /* 16 bit read access */
3157 result |= memory_region_dispatch_read(mr, addr1, &val, 2,
3158 attrs);
3159 stw_p(buf, val);
3160 break;
3161 case 1:
3162 /* 8 bit read access */
3163 result |= memory_region_dispatch_read(mr, addr1, &val, 1,
3164 attrs);
3165 stb_p(buf, val);
3166 break;
3167 default:
3168 abort();
3170 } else {
3171 /* RAM case */
3172 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3173 memcpy(buf, ptr, l);
3176 if (release_lock) {
3177 qemu_mutex_unlock_iothread();
3178 release_lock = false;
3181 len -= l;
3182 buf += l;
3183 addr += l;
3185 if (!len) {
3186 break;
3189 l = len;
3190 mr = flatview_translate(fv, addr, &addr1, &l, false);
3193 return result;
3196 /* Called from RCU critical section. */
3197 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
3198 MemTxAttrs attrs, uint8_t *buf, int len)
3200 hwaddr l;
3201 hwaddr addr1;
3202 MemoryRegion *mr;
3204 l = len;
3205 mr = flatview_translate(fv, addr, &addr1, &l, false);
3206 return flatview_read_continue(fv, addr, attrs, buf, len,
3207 addr1, l, mr);
3210 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3211 MemTxAttrs attrs, uint8_t *buf, int len)
3213 MemTxResult result = MEMTX_OK;
3214 FlatView *fv;
3216 if (len > 0) {
3217 rcu_read_lock();
3218 fv = address_space_to_flatview(as);
3219 result = flatview_read(fv, addr, attrs, buf, len);
3220 rcu_read_unlock();
3223 return result;
3226 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
3227 MemTxAttrs attrs,
3228 const uint8_t *buf, int len)
3230 MemTxResult result = MEMTX_OK;
3231 FlatView *fv;
3233 if (len > 0) {
3234 rcu_read_lock();
3235 fv = address_space_to_flatview(as);
3236 result = flatview_write(fv, addr, attrs, buf, len);
3237 rcu_read_unlock();
3240 return result;
3243 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3244 uint8_t *buf, int len, bool is_write)
3246 if (is_write) {
3247 return address_space_write(as, addr, attrs, buf, len);
3248 } else {
3249 return address_space_read_full(as, addr, attrs, buf, len);
3253 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
3254 int len, int is_write)
3256 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3257 buf, len, is_write);
3260 enum write_rom_type {
3261 WRITE_DATA,
3262 FLUSH_CACHE,
3265 static inline void cpu_physical_memory_write_rom_internal(AddressSpace *as,
3266 hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
3268 hwaddr l;
3269 uint8_t *ptr;
3270 hwaddr addr1;
3271 MemoryRegion *mr;
3273 rcu_read_lock();
3274 while (len > 0) {
3275 l = len;
3276 mr = address_space_translate(as, addr, &addr1, &l, true);
3278 if (!(memory_region_is_ram(mr) ||
3279 memory_region_is_romd(mr))) {
3280 l = memory_access_size(mr, l, addr1);
3281 } else {
3282 /* ROM/RAM case */
3283 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3284 switch (type) {
3285 case WRITE_DATA:
3286 memcpy(ptr, buf, l);
3287 invalidate_and_set_dirty(mr, addr1, l);
3288 break;
3289 case FLUSH_CACHE:
3290 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
3291 break;
3294 len -= l;
3295 buf += l;
3296 addr += l;
3298 rcu_read_unlock();
3301 /* used for ROM loading : can write in RAM and ROM */
3302 void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
3303 const uint8_t *buf, int len)
3305 cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
3308 void cpu_flush_icache_range(hwaddr start, int len)
3311 * This function should do the same thing as an icache flush that was
3312 * triggered from within the guest. For TCG we are always cache coherent,
3313 * so there is no need to flush anything. For KVM / Xen we need to flush
3314 * the host's instruction cache at least.
3316 if (tcg_enabled()) {
3317 return;
3320 cpu_physical_memory_write_rom_internal(&address_space_memory,
3321 start, NULL, len, FLUSH_CACHE);
3324 typedef struct {
3325 MemoryRegion *mr;
3326 void *buffer;
3327 hwaddr addr;
3328 hwaddr len;
3329 bool in_use;
3330 } BounceBuffer;
3332 static BounceBuffer bounce;
3334 typedef struct MapClient {
3335 QEMUBH *bh;
3336 QLIST_ENTRY(MapClient) link;
3337 } MapClient;
3339 QemuMutex map_client_list_lock;
3340 static QLIST_HEAD(map_client_list, MapClient) map_client_list
3341 = QLIST_HEAD_INITIALIZER(map_client_list);
3343 static void cpu_unregister_map_client_do(MapClient *client)
3345 QLIST_REMOVE(client, link);
3346 g_free(client);
3349 static void cpu_notify_map_clients_locked(void)
3351 MapClient *client;
3353 while (!QLIST_EMPTY(&map_client_list)) {
3354 client = QLIST_FIRST(&map_client_list);
3355 qemu_bh_schedule(client->bh);
3356 cpu_unregister_map_client_do(client);
3360 void cpu_register_map_client(QEMUBH *bh)
3362 MapClient *client = g_malloc(sizeof(*client));
3364 qemu_mutex_lock(&map_client_list_lock);
3365 client->bh = bh;
3366 QLIST_INSERT_HEAD(&map_client_list, client, link);
3367 if (!atomic_read(&bounce.in_use)) {
3368 cpu_notify_map_clients_locked();
3370 qemu_mutex_unlock(&map_client_list_lock);
3373 void cpu_exec_init_all(void)
3375 qemu_mutex_init(&ram_list.mutex);
3376 /* The data structures we set up here depend on knowing the page size,
3377 * so no more changes can be made after this point.
3378 * In an ideal world, nothing we did before we had finished the
3379 * machine setup would care about the target page size, and we could
3380 * do this much later, rather than requiring board models to state
3381 * up front what their requirements are.
3383 finalize_target_page_bits();
3384 io_mem_init();
3385 memory_map_init();
3386 qemu_mutex_init(&map_client_list_lock);
3389 void cpu_unregister_map_client(QEMUBH *bh)
3391 MapClient *client;
3393 qemu_mutex_lock(&map_client_list_lock);
3394 QLIST_FOREACH(client, &map_client_list, link) {
3395 if (client->bh == bh) {
3396 cpu_unregister_map_client_do(client);
3397 break;
3400 qemu_mutex_unlock(&map_client_list_lock);
3403 static void cpu_notify_map_clients(void)
3405 qemu_mutex_lock(&map_client_list_lock);
3406 cpu_notify_map_clients_locked();
3407 qemu_mutex_unlock(&map_client_list_lock);
3410 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
3411 bool is_write)
3413 MemoryRegion *mr;
3414 hwaddr l, xlat;
3416 while (len > 0) {
3417 l = len;
3418 mr = flatview_translate(fv, addr, &xlat, &l, is_write);
3419 if (!memory_access_is_direct(mr, is_write)) {
3420 l = memory_access_size(mr, l, addr);
3421 if (!memory_region_access_valid(mr, xlat, l, is_write)) {
3422 return false;
3426 len -= l;
3427 addr += l;
3429 return true;
3432 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3433 int len, bool is_write)
3435 FlatView *fv;
3436 bool result;
3438 rcu_read_lock();
3439 fv = address_space_to_flatview(as);
3440 result = flatview_access_valid(fv, addr, len, is_write);
3441 rcu_read_unlock();
3442 return result;
3445 static hwaddr
3446 flatview_extend_translation(FlatView *fv, hwaddr addr,
3447 hwaddr target_len,
3448 MemoryRegion *mr, hwaddr base, hwaddr len,
3449 bool is_write)
3451 hwaddr done = 0;
3452 hwaddr xlat;
3453 MemoryRegion *this_mr;
3455 for (;;) {
3456 target_len -= len;
3457 addr += len;
3458 done += len;
3459 if (target_len == 0) {
3460 return done;
3463 len = target_len;
3464 this_mr = flatview_translate(fv, addr, &xlat,
3465 &len, is_write);
3466 if (this_mr != mr || xlat != base + done) {
3467 return done;
3472 /* Map a physical memory region into a host virtual address.
3473 * May map a subset of the requested range, given by and returned in *plen.
3474 * May return NULL if resources needed to perform the mapping are exhausted.
3475 * Use only for reads OR writes - not for read-modify-write operations.
3476 * Use cpu_register_map_client() to know when retrying the map operation is
3477 * likely to succeed.
3479 void *address_space_map(AddressSpace *as,
3480 hwaddr addr,
3481 hwaddr *plen,
3482 bool is_write)
3484 hwaddr len = *plen;
3485 hwaddr l, xlat;
3486 MemoryRegion *mr;
3487 void *ptr;
3488 FlatView *fv;
3490 if (len == 0) {
3491 return NULL;
3494 l = len;
3495 rcu_read_lock();
3496 fv = address_space_to_flatview(as);
3497 mr = flatview_translate(fv, addr, &xlat, &l, is_write);
3499 if (!memory_access_is_direct(mr, is_write)) {
3500 if (atomic_xchg(&bounce.in_use, true)) {
3501 rcu_read_unlock();
3502 return NULL;
3504 /* Avoid unbounded allocations */
3505 l = MIN(l, TARGET_PAGE_SIZE);
3506 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3507 bounce.addr = addr;
3508 bounce.len = l;
3510 memory_region_ref(mr);
3511 bounce.mr = mr;
3512 if (!is_write) {
3513 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3514 bounce.buffer, l);
3517 rcu_read_unlock();
3518 *plen = l;
3519 return bounce.buffer;
3523 memory_region_ref(mr);
3524 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3525 l, is_write);
3526 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3527 rcu_read_unlock();
3529 return ptr;
3532 /* Unmaps a memory region previously mapped by address_space_map().
3533 * Will also mark the memory as dirty if is_write == 1. access_len gives
3534 * the amount of memory that was actually read or written by the caller.
3536 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3537 int is_write, hwaddr access_len)
3539 if (buffer != bounce.buffer) {
3540 MemoryRegion *mr;
3541 ram_addr_t addr1;
3543 mr = memory_region_from_host(buffer, &addr1);
3544 assert(mr != NULL);
3545 if (is_write) {
3546 invalidate_and_set_dirty(mr, addr1, access_len);
3548 if (xen_enabled()) {
3549 xen_invalidate_map_cache_entry(buffer);
3551 memory_region_unref(mr);
3552 return;
3554 if (is_write) {
3555 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3556 bounce.buffer, access_len);
3558 qemu_vfree(bounce.buffer);
3559 bounce.buffer = NULL;
3560 memory_region_unref(bounce.mr);
3561 atomic_mb_set(&bounce.in_use, false);
3562 cpu_notify_map_clients();
3565 void *cpu_physical_memory_map(hwaddr addr,
3566 hwaddr *plen,
3567 int is_write)
3569 return address_space_map(&address_space_memory, addr, plen, is_write);
3572 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3573 int is_write, hwaddr access_len)
3575 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3578 #define ARG1_DECL AddressSpace *as
3579 #define ARG1 as
3580 #define SUFFIX
3581 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3582 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3583 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3584 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3585 #define RCU_READ_LOCK(...) rcu_read_lock()
3586 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3587 #include "memory_ldst.inc.c"
3589 int64_t address_space_cache_init(MemoryRegionCache *cache,
3590 AddressSpace *as,
3591 hwaddr addr,
3592 hwaddr len,
3593 bool is_write)
3595 cache->len = len;
3596 cache->as = as;
3597 cache->xlat = addr;
3598 return len;
3601 void address_space_cache_invalidate(MemoryRegionCache *cache,
3602 hwaddr addr,
3603 hwaddr access_len)
3607 void address_space_cache_destroy(MemoryRegionCache *cache)
3609 cache->as = NULL;
3612 #define ARG1_DECL MemoryRegionCache *cache
3613 #define ARG1 cache
3614 #define SUFFIX _cached
3615 #define TRANSLATE(addr, ...) \
3616 address_space_translate(cache->as, cache->xlat + (addr), __VA_ARGS__)
3617 #define IS_DIRECT(mr, is_write) true
3618 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3619 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3620 #define RCU_READ_LOCK() rcu_read_lock()
3621 #define RCU_READ_UNLOCK() rcu_read_unlock()
3622 #include "memory_ldst.inc.c"
3624 /* virtual memory access for debug (includes writing to ROM) */
3625 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3626 uint8_t *buf, int len, int is_write)
3628 int l;
3629 hwaddr phys_addr;
3630 target_ulong page;
3632 cpu_synchronize_state(cpu);
3633 while (len > 0) {
3634 int asidx;
3635 MemTxAttrs attrs;
3637 page = addr & TARGET_PAGE_MASK;
3638 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3639 asidx = cpu_asidx_from_attrs(cpu, attrs);
3640 /* if no physical page mapped, return an error */
3641 if (phys_addr == -1)
3642 return -1;
3643 l = (page + TARGET_PAGE_SIZE) - addr;
3644 if (l > len)
3645 l = len;
3646 phys_addr += (addr & ~TARGET_PAGE_MASK);
3647 if (is_write) {
3648 cpu_physical_memory_write_rom(cpu->cpu_ases[asidx].as,
3649 phys_addr, buf, l);
3650 } else {
3651 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3652 MEMTXATTRS_UNSPECIFIED,
3653 buf, l, 0);
3655 len -= l;
3656 buf += l;
3657 addr += l;
3659 return 0;
3663 * Allows code that needs to deal with migration bitmaps etc to still be built
3664 * target independent.
3666 size_t qemu_target_page_size(void)
3668 return TARGET_PAGE_SIZE;
3671 int qemu_target_page_bits(void)
3673 return TARGET_PAGE_BITS;
3676 int qemu_target_page_bits_min(void)
3678 return TARGET_PAGE_BITS_MIN;
3680 #endif
3683 * A helper function for the _utterly broken_ virtio device model to find out if
3684 * it's running on a big endian machine. Don't do this at home kids!
3686 bool target_words_bigendian(void);
3687 bool target_words_bigendian(void)
3689 #if defined(TARGET_WORDS_BIGENDIAN)
3690 return true;
3691 #else
3692 return false;
3693 #endif
3696 #ifndef CONFIG_USER_ONLY
3697 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3699 MemoryRegion*mr;
3700 hwaddr l = 1;
3701 bool res;
3703 rcu_read_lock();
3704 mr = address_space_translate(&address_space_memory,
3705 phys_addr, &phys_addr, &l, false);
3707 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3708 rcu_read_unlock();
3709 return res;
3712 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3714 RAMBlock *block;
3715 int ret = 0;
3717 rcu_read_lock();
3718 RAMBLOCK_FOREACH(block) {
3719 ret = func(block->idstr, block->host, block->offset,
3720 block->used_length, opaque);
3721 if (ret) {
3722 break;
3725 rcu_read_unlock();
3726 return ret;
3730 * Unmap pages of memory from start to start+length such that
3731 * they a) read as 0, b) Trigger whatever fault mechanism
3732 * the OS provides for postcopy.
3733 * The pages must be unmapped by the end of the function.
3734 * Returns: 0 on success, none-0 on failure
3737 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3739 int ret = -1;
3741 uint8_t *host_startaddr = rb->host + start;
3743 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
3744 error_report("ram_block_discard_range: Unaligned start address: %p",
3745 host_startaddr);
3746 goto err;
3749 if ((start + length) <= rb->used_length) {
3750 bool need_madvise, need_fallocate;
3751 uint8_t *host_endaddr = host_startaddr + length;
3752 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
3753 error_report("ram_block_discard_range: Unaligned end address: %p",
3754 host_endaddr);
3755 goto err;
3758 errno = ENOTSUP; /* If we are missing MADVISE etc */
3760 /* The logic here is messy;
3761 * madvise DONTNEED fails for hugepages
3762 * fallocate works on hugepages and shmem
3764 need_madvise = (rb->page_size == qemu_host_page_size);
3765 need_fallocate = rb->fd != -1;
3766 if (need_fallocate) {
3767 /* For a file, this causes the area of the file to be zero'd
3768 * if read, and for hugetlbfs also causes it to be unmapped
3769 * so a userfault will trigger.
3771 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3772 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3773 start, length);
3774 if (ret) {
3775 ret = -errno;
3776 error_report("ram_block_discard_range: Failed to fallocate "
3777 "%s:%" PRIx64 " +%zx (%d)",
3778 rb->idstr, start, length, ret);
3779 goto err;
3781 #else
3782 ret = -ENOSYS;
3783 error_report("ram_block_discard_range: fallocate not available/file"
3784 "%s:%" PRIx64 " +%zx (%d)",
3785 rb->idstr, start, length, ret);
3786 goto err;
3787 #endif
3789 if (need_madvise) {
3790 /* For normal RAM this causes it to be unmapped,
3791 * for shared memory it causes the local mapping to disappear
3792 * and to fall back on the file contents (which we just
3793 * fallocate'd away).
3795 #if defined(CONFIG_MADVISE)
3796 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3797 if (ret) {
3798 ret = -errno;
3799 error_report("ram_block_discard_range: Failed to discard range "
3800 "%s:%" PRIx64 " +%zx (%d)",
3801 rb->idstr, start, length, ret);
3802 goto err;
3804 #else
3805 ret = -ENOSYS;
3806 error_report("ram_block_discard_range: MADVISE not available"
3807 "%s:%" PRIx64 " +%zx (%d)",
3808 rb->idstr, start, length, ret);
3809 goto err;
3810 #endif
3812 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3813 need_madvise, need_fallocate, ret);
3814 } else {
3815 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3816 "/%zx/" RAM_ADDR_FMT")",
3817 rb->idstr, start, length, rb->used_length);
3820 err:
3821 return ret;
3824 #endif
3826 void page_size_init(void)
3828 /* NOTE: we can always suppose that qemu_host_page_size >=
3829 TARGET_PAGE_SIZE */
3830 if (qemu_host_page_size == 0) {
3831 qemu_host_page_size = qemu_real_host_page_size;
3833 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
3834 qemu_host_page_size = TARGET_PAGE_SIZE;
3836 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;
3839 #if !defined(CONFIG_USER_ONLY)
3841 static void mtree_print_phys_entries(fprintf_function mon, void *f,
3842 int start, int end, int skip, int ptr)
3844 if (start == end - 1) {
3845 mon(f, "\t%3d ", start);
3846 } else {
3847 mon(f, "\t%3d..%-3d ", start, end - 1);
3849 mon(f, " skip=%d ", skip);
3850 if (ptr == PHYS_MAP_NODE_NIL) {
3851 mon(f, " ptr=NIL");
3852 } else if (!skip) {
3853 mon(f, " ptr=#%d", ptr);
3854 } else {
3855 mon(f, " ptr=[%d]", ptr);
3857 mon(f, "\n");
3860 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3861 int128_sub((size), int128_one())) : 0)
3863 void mtree_print_dispatch(fprintf_function mon, void *f,
3864 AddressSpaceDispatch *d, MemoryRegion *root)
3866 int i;
3868 mon(f, " Dispatch\n");
3869 mon(f, " Physical sections\n");
3871 for (i = 0; i < d->map.sections_nb; ++i) {
3872 MemoryRegionSection *s = d->map.sections + i;
3873 const char *names[] = { " [unassigned]", " [not dirty]",
3874 " [ROM]", " [watch]" };
3876 mon(f, " #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx " %s%s%s%s%s",
3878 s->offset_within_address_space,
3879 s->offset_within_address_space + MR_SIZE(s->mr->size),
3880 s->mr->name ? s->mr->name : "(noname)",
3881 i < ARRAY_SIZE(names) ? names[i] : "",
3882 s->mr == root ? " [ROOT]" : "",
3883 s == d->mru_section ? " [MRU]" : "",
3884 s->mr->is_iommu ? " [iommu]" : "");
3886 if (s->mr->alias) {
3887 mon(f, " alias=%s", s->mr->alias->name ?
3888 s->mr->alias->name : "noname");
3890 mon(f, "\n");
3893 mon(f, " Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3894 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3895 for (i = 0; i < d->map.nodes_nb; ++i) {
3896 int j, jprev;
3897 PhysPageEntry prev;
3898 Node *n = d->map.nodes + i;
3900 mon(f, " [%d]\n", i);
3902 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3903 PhysPageEntry *pe = *n + j;
3905 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3906 continue;
3909 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
3911 jprev = j;
3912 prev = *pe;
3915 if (jprev != ARRAY_SIZE(*n)) {
3916 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
3921 #endif