target/arm: Add inline attribute to function in header file
[qemu/ar7.git] / exec.c
blob2cc88cfbe32fe3e73bd6255efe19276e3039c80d
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 #endif
104 #ifdef TARGET_PAGE_BITS_VARY
105 int target_page_bits;
106 bool target_page_bits_decided;
107 #endif
109 struct CPUTailQ cpus = QTAILQ_HEAD_INITIALIZER(cpus);
110 /* current CPU in the current thread. It is only valid inside
111 cpu_exec() */
112 __thread CPUState *current_cpu;
113 /* 0 = Do not count executed instructions.
114 1 = Precise instruction counting.
115 2 = Adaptive rate instruction counting. */
116 int use_icount;
118 uintptr_t qemu_host_page_size;
119 intptr_t qemu_host_page_mask;
121 bool set_preferred_target_page_bits(int bits)
123 /* The target page size is the lowest common denominator for all
124 * the CPUs in the system, so we can only make it smaller, never
125 * larger. And we can't make it smaller once we've committed to
126 * a particular size.
128 #ifdef TARGET_PAGE_BITS_VARY
129 assert(bits >= TARGET_PAGE_BITS_MIN);
130 if (target_page_bits == 0 || target_page_bits > bits) {
131 if (target_page_bits_decided) {
132 return false;
134 target_page_bits = bits;
136 #endif
137 return true;
140 #if !defined(CONFIG_USER_ONLY)
142 static void finalize_target_page_bits(void)
144 #ifdef TARGET_PAGE_BITS_VARY
145 if (target_page_bits == 0) {
146 target_page_bits = TARGET_PAGE_BITS_MIN;
148 target_page_bits_decided = true;
149 #endif
152 typedef struct PhysPageEntry PhysPageEntry;
154 struct PhysPageEntry {
155 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
156 uint32_t skip : 6;
157 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
158 uint32_t ptr : 26;
161 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
163 /* Size of the L2 (and L3, etc) page tables. */
164 #define ADDR_SPACE_BITS 64
166 #define P_L2_BITS 9
167 #define P_L2_SIZE (1 << P_L2_BITS)
169 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
171 typedef PhysPageEntry Node[P_L2_SIZE];
173 typedef struct PhysPageMap {
174 struct rcu_head rcu;
176 unsigned sections_nb;
177 unsigned sections_nb_alloc;
178 unsigned nodes_nb;
179 unsigned nodes_nb_alloc;
180 Node *nodes;
181 MemoryRegionSection *sections;
182 } PhysPageMap;
184 struct AddressSpaceDispatch {
185 MemoryRegionSection *mru_section;
186 /* This is a multi-level map on the physical address space.
187 * The bottom level has pointers to MemoryRegionSections.
189 PhysPageEntry phys_map;
190 PhysPageMap map;
193 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
194 typedef struct subpage_t {
195 MemoryRegion iomem;
196 FlatView *fv;
197 hwaddr base;
198 uint16_t sub_section[];
199 } subpage_t;
201 #define PHYS_SECTION_UNASSIGNED 0
202 #define PHYS_SECTION_NOTDIRTY 1
203 #define PHYS_SECTION_ROM 2
204 #define PHYS_SECTION_WATCH 3
206 static void io_mem_init(void);
207 static void memory_map_init(void);
208 static void tcg_commit(MemoryListener *listener);
210 static MemoryRegion io_mem_watch;
213 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
214 * @cpu: the CPU whose AddressSpace this is
215 * @as: the AddressSpace itself
216 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
217 * @tcg_as_listener: listener for tracking changes to the AddressSpace
219 struct CPUAddressSpace {
220 CPUState *cpu;
221 AddressSpace *as;
222 struct AddressSpaceDispatch *memory_dispatch;
223 MemoryListener tcg_as_listener;
226 struct DirtyBitmapSnapshot {
227 ram_addr_t start;
228 ram_addr_t end;
229 unsigned long dirty[];
232 #endif
234 #if !defined(CONFIG_USER_ONLY)
236 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
238 static unsigned alloc_hint = 16;
239 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
240 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, alloc_hint);
241 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, map->nodes_nb + nodes);
242 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
243 alloc_hint = map->nodes_nb_alloc;
247 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
249 unsigned i;
250 uint32_t ret;
251 PhysPageEntry e;
252 PhysPageEntry *p;
254 ret = map->nodes_nb++;
255 p = map->nodes[ret];
256 assert(ret != PHYS_MAP_NODE_NIL);
257 assert(ret != map->nodes_nb_alloc);
259 e.skip = leaf ? 0 : 1;
260 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
261 for (i = 0; i < P_L2_SIZE; ++i) {
262 memcpy(&p[i], &e, sizeof(e));
264 return ret;
267 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
268 hwaddr *index, hwaddr *nb, uint16_t leaf,
269 int level)
271 PhysPageEntry *p;
272 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
274 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
275 lp->ptr = phys_map_node_alloc(map, level == 0);
277 p = map->nodes[lp->ptr];
278 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
280 while (*nb && lp < &p[P_L2_SIZE]) {
281 if ((*index & (step - 1)) == 0 && *nb >= step) {
282 lp->skip = 0;
283 lp->ptr = leaf;
284 *index += step;
285 *nb -= step;
286 } else {
287 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
289 ++lp;
293 static void phys_page_set(AddressSpaceDispatch *d,
294 hwaddr index, hwaddr nb,
295 uint16_t leaf)
297 /* Wildly overreserve - it doesn't matter much. */
298 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
300 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
303 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
304 * and update our entry so we can skip it and go directly to the destination.
306 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
308 unsigned valid_ptr = P_L2_SIZE;
309 int valid = 0;
310 PhysPageEntry *p;
311 int i;
313 if (lp->ptr == PHYS_MAP_NODE_NIL) {
314 return;
317 p = nodes[lp->ptr];
318 for (i = 0; i < P_L2_SIZE; i++) {
319 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
320 continue;
323 valid_ptr = i;
324 valid++;
325 if (p[i].skip) {
326 phys_page_compact(&p[i], nodes);
330 /* We can only compress if there's only one child. */
331 if (valid != 1) {
332 return;
335 assert(valid_ptr < P_L2_SIZE);
337 /* Don't compress if it won't fit in the # of bits we have. */
338 if (lp->skip + p[valid_ptr].skip >= (1 << 3)) {
339 return;
342 lp->ptr = p[valid_ptr].ptr;
343 if (!p[valid_ptr].skip) {
344 /* If our only child is a leaf, make this a leaf. */
345 /* By design, we should have made this node a leaf to begin with so we
346 * should never reach here.
347 * But since it's so simple to handle this, let's do it just in case we
348 * change this rule.
350 lp->skip = 0;
351 } else {
352 lp->skip += p[valid_ptr].skip;
356 void address_space_dispatch_compact(AddressSpaceDispatch *d)
358 if (d->phys_map.skip) {
359 phys_page_compact(&d->phys_map, d->map.nodes);
363 static inline bool section_covers_addr(const MemoryRegionSection *section,
364 hwaddr addr)
366 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
367 * the section must cover the entire address space.
369 return int128_gethi(section->size) ||
370 range_covers_byte(section->offset_within_address_space,
371 int128_getlo(section->size), addr);
374 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
376 PhysPageEntry lp = d->phys_map, *p;
377 Node *nodes = d->map.nodes;
378 MemoryRegionSection *sections = d->map.sections;
379 hwaddr index = addr >> TARGET_PAGE_BITS;
380 int i;
382 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
383 if (lp.ptr == PHYS_MAP_NODE_NIL) {
384 return &sections[PHYS_SECTION_UNASSIGNED];
386 p = nodes[lp.ptr];
387 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
390 if (section_covers_addr(&sections[lp.ptr], addr)) {
391 return &sections[lp.ptr];
392 } else {
393 return &sections[PHYS_SECTION_UNASSIGNED];
397 bool memory_region_is_unassigned(MemoryRegion *mr)
399 return mr != &io_mem_rom && mr != &io_mem_notdirty && !mr->rom_device
400 && mr != &io_mem_watch;
403 /* Called from RCU critical section */
404 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
405 hwaddr addr,
406 bool resolve_subpage)
408 MemoryRegionSection *section = atomic_read(&d->mru_section);
409 subpage_t *subpage;
411 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
412 !section_covers_addr(section, addr)) {
413 section = phys_page_find(d, addr);
414 atomic_set(&d->mru_section, section);
416 if (resolve_subpage && section->mr->subpage) {
417 subpage = container_of(section->mr, subpage_t, iomem);
418 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
420 return section;
423 /* Called from RCU critical section */
424 static MemoryRegionSection *
425 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
426 hwaddr *plen, bool resolve_subpage)
428 MemoryRegionSection *section;
429 MemoryRegion *mr;
430 Int128 diff;
432 section = address_space_lookup_region(d, addr, resolve_subpage);
433 /* Compute offset within MemoryRegionSection */
434 addr -= section->offset_within_address_space;
436 /* Compute offset within MemoryRegion */
437 *xlat = addr + section->offset_within_region;
439 mr = section->mr;
441 /* MMIO registers can be expected to perform full-width accesses based only
442 * on their address, without considering adjacent registers that could
443 * decode to completely different MemoryRegions. When such registers
444 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
445 * regions overlap wildly. For this reason we cannot clamp the accesses
446 * here.
448 * If the length is small (as is the case for address_space_ldl/stl),
449 * everything works fine. If the incoming length is large, however,
450 * the caller really has to do the clamping through memory_access_size.
452 if (memory_region_is_ram(mr)) {
453 diff = int128_sub(section->size, int128_make64(addr));
454 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
456 return section;
460 * flatview_do_translate - translate an address in FlatView
462 * @fv: the flat view that we want to translate on
463 * @addr: the address to be translated in above address space
464 * @xlat: the translated address offset within memory region. It
465 * cannot be @NULL.
466 * @plen_out: valid read/write length of the translated address. It
467 * can be @NULL when we don't care about it.
468 * @page_mask_out: page mask for the translated address. This
469 * should only be meaningful for IOMMU translated
470 * addresses, since there may be huge pages that this bit
471 * would tell. It can be @NULL if we don't care about it.
472 * @is_write: whether the translation operation is for write
473 * @is_mmio: whether this can be MMIO, set true if it can
475 * This function is called from RCU critical section
477 static MemoryRegionSection flatview_do_translate(FlatView *fv,
478 hwaddr addr,
479 hwaddr *xlat,
480 hwaddr *plen_out,
481 hwaddr *page_mask_out,
482 bool is_write,
483 bool is_mmio,
484 AddressSpace **target_as)
486 IOMMUTLBEntry iotlb;
487 MemoryRegionSection *section;
488 IOMMUMemoryRegion *iommu_mr;
489 IOMMUMemoryRegionClass *imrc;
490 hwaddr page_mask = (hwaddr)(-1);
491 hwaddr plen = (hwaddr)(-1);
493 if (plen_out) {
494 plen = *plen_out;
497 for (;;) {
498 section = address_space_translate_internal(
499 flatview_to_dispatch(fv), addr, &addr,
500 &plen, is_mmio);
502 iommu_mr = memory_region_get_iommu(section->mr);
503 if (!iommu_mr) {
504 break;
506 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
508 iotlb = imrc->translate(iommu_mr, addr, is_write ?
509 IOMMU_WO : IOMMU_RO);
510 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
511 | (addr & iotlb.addr_mask));
512 page_mask &= iotlb.addr_mask;
513 plen = MIN(plen, (addr | iotlb.addr_mask) - addr + 1);
514 if (!(iotlb.perm & (1 << is_write))) {
515 goto translate_fail;
518 fv = address_space_to_flatview(iotlb.target_as);
519 *target_as = iotlb.target_as;
522 *xlat = addr;
524 if (page_mask == (hwaddr)(-1)) {
525 /* Not behind an IOMMU, use default page size. */
526 page_mask = ~TARGET_PAGE_MASK;
529 if (page_mask_out) {
530 *page_mask_out = page_mask;
533 if (plen_out) {
534 *plen_out = plen;
537 return *section;
539 translate_fail:
540 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
543 /* Called from RCU critical section */
544 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
545 bool is_write)
547 MemoryRegionSection section;
548 hwaddr xlat, page_mask;
551 * This can never be MMIO, and we don't really care about plen,
552 * but page mask.
554 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
555 NULL, &page_mask, is_write, false, &as);
557 /* Illegal translation */
558 if (section.mr == &io_mem_unassigned) {
559 goto iotlb_fail;
562 /* Convert memory region offset into address space offset */
563 xlat += section.offset_within_address_space -
564 section.offset_within_region;
566 return (IOMMUTLBEntry) {
567 .target_as = as,
568 .iova = addr & ~page_mask,
569 .translated_addr = xlat & ~page_mask,
570 .addr_mask = page_mask,
571 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
572 .perm = IOMMU_RW,
575 iotlb_fail:
576 return (IOMMUTLBEntry) {0};
579 /* Called from RCU critical section */
580 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
581 hwaddr *plen, bool is_write)
583 MemoryRegion *mr;
584 MemoryRegionSection section;
585 AddressSpace *as = NULL;
587 /* This can be MMIO, so setup MMIO bit. */
588 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
589 is_write, true, &as);
590 mr = section.mr;
592 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
593 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
594 *plen = MIN(page, *plen);
597 return mr;
600 /* Called from RCU critical section */
601 MemoryRegionSection *
602 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
603 hwaddr *xlat, hwaddr *plen)
605 MemoryRegionSection *section;
606 AddressSpaceDispatch *d = atomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
608 section = address_space_translate_internal(d, addr, xlat, plen, false);
610 assert(!memory_region_is_iommu(section->mr));
611 return section;
613 #endif
615 #if !defined(CONFIG_USER_ONLY)
617 static int cpu_common_post_load(void *opaque, int version_id)
619 CPUState *cpu = opaque;
621 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
622 version_id is increased. */
623 cpu->interrupt_request &= ~0x01;
624 tlb_flush(cpu);
626 /* loadvm has just updated the content of RAM, bypassing the
627 * usual mechanisms that ensure we flush TBs for writes to
628 * memory we've translated code from. So we must flush all TBs,
629 * which will now be stale.
631 tb_flush(cpu);
633 return 0;
636 static int cpu_common_pre_load(void *opaque)
638 CPUState *cpu = opaque;
640 cpu->exception_index = -1;
642 return 0;
645 static bool cpu_common_exception_index_needed(void *opaque)
647 CPUState *cpu = opaque;
649 return tcg_enabled() && cpu->exception_index != -1;
652 static const VMStateDescription vmstate_cpu_common_exception_index = {
653 .name = "cpu_common/exception_index",
654 .version_id = 1,
655 .minimum_version_id = 1,
656 .needed = cpu_common_exception_index_needed,
657 .fields = (VMStateField[]) {
658 VMSTATE_INT32(exception_index, CPUState),
659 VMSTATE_END_OF_LIST()
663 static bool cpu_common_crash_occurred_needed(void *opaque)
665 CPUState *cpu = opaque;
667 return cpu->crash_occurred;
670 static const VMStateDescription vmstate_cpu_common_crash_occurred = {
671 .name = "cpu_common/crash_occurred",
672 .version_id = 1,
673 .minimum_version_id = 1,
674 .needed = cpu_common_crash_occurred_needed,
675 .fields = (VMStateField[]) {
676 VMSTATE_BOOL(crash_occurred, CPUState),
677 VMSTATE_END_OF_LIST()
681 const VMStateDescription vmstate_cpu_common = {
682 .name = "cpu_common",
683 .version_id = 1,
684 .minimum_version_id = 1,
685 .pre_load = cpu_common_pre_load,
686 .post_load = cpu_common_post_load,
687 .fields = (VMStateField[]) {
688 VMSTATE_UINT32(halted, CPUState),
689 VMSTATE_UINT32(interrupt_request, CPUState),
690 VMSTATE_END_OF_LIST()
692 .subsections = (const VMStateDescription*[]) {
693 &vmstate_cpu_common_exception_index,
694 &vmstate_cpu_common_crash_occurred,
695 NULL
699 #endif
701 CPUState *qemu_get_cpu(int index)
703 CPUState *cpu;
705 CPU_FOREACH(cpu) {
706 if (cpu->cpu_index == index) {
707 return cpu;
711 return NULL;
714 #if !defined(CONFIG_USER_ONLY)
715 void cpu_address_space_init(CPUState *cpu, int asidx,
716 const char *prefix, MemoryRegion *mr)
718 CPUAddressSpace *newas;
719 AddressSpace *as = g_new0(AddressSpace, 1);
720 char *as_name;
722 assert(mr);
723 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
724 address_space_init(as, mr, as_name);
725 g_free(as_name);
727 /* Target code should have set num_ases before calling us */
728 assert(asidx < cpu->num_ases);
730 if (asidx == 0) {
731 /* address space 0 gets the convenience alias */
732 cpu->as = as;
735 /* KVM cannot currently support multiple address spaces. */
736 assert(asidx == 0 || !kvm_enabled());
738 if (!cpu->cpu_ases) {
739 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
742 newas = &cpu->cpu_ases[asidx];
743 newas->cpu = cpu;
744 newas->as = as;
745 if (tcg_enabled()) {
746 newas->tcg_as_listener.commit = tcg_commit;
747 memory_listener_register(&newas->tcg_as_listener, as);
751 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
753 /* Return the AddressSpace corresponding to the specified index */
754 return cpu->cpu_ases[asidx].as;
756 #endif
758 void cpu_exec_unrealizefn(CPUState *cpu)
760 CPUClass *cc = CPU_GET_CLASS(cpu);
762 cpu_list_remove(cpu);
764 if (cc->vmsd != NULL) {
765 vmstate_unregister(NULL, cc->vmsd, cpu);
767 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
768 vmstate_unregister(NULL, &vmstate_cpu_common, cpu);
772 Property cpu_common_props[] = {
773 #ifndef CONFIG_USER_ONLY
774 /* Create a memory property for softmmu CPU object,
775 * so users can wire up its memory. (This can't go in qom/cpu.c
776 * because that file is compiled only once for both user-mode
777 * and system builds.) The default if no link is set up is to use
778 * the system address space.
780 DEFINE_PROP_LINK("memory", CPUState, memory, TYPE_MEMORY_REGION,
781 MemoryRegion *),
782 #endif
783 DEFINE_PROP_END_OF_LIST(),
786 void cpu_exec_initfn(CPUState *cpu)
788 #ifdef TARGET_WORDS_BIGENDIAN
789 cpu->bigendian = true;
790 #else
791 cpu->bigendian = false;
792 #endif
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 QEMU_NORETURN 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) =
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))
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 /* Called with iothread lock held. */
1776 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1778 RAMBlock *block;
1780 assert(new_block);
1781 assert(!new_block->idstr[0]);
1783 if (dev) {
1784 char *id = qdev_get_dev_path(dev);
1785 if (id) {
1786 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1787 g_free(id);
1790 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1792 rcu_read_lock();
1793 RAMBLOCK_FOREACH(block) {
1794 if (block != new_block &&
1795 !strcmp(block->idstr, new_block->idstr)) {
1796 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1797 new_block->idstr);
1798 abort();
1801 rcu_read_unlock();
1804 /* Called with iothread lock held. */
1805 void qemu_ram_unset_idstr(RAMBlock *block)
1807 /* FIXME: arch_init.c assumes that this is not called throughout
1808 * migration. Ignore the problem since hot-unplug during migration
1809 * does not work anyway.
1811 if (block) {
1812 memset(block->idstr, 0, sizeof(block->idstr));
1816 size_t qemu_ram_pagesize(RAMBlock *rb)
1818 return rb->page_size;
1821 /* Returns the largest size of page in use */
1822 size_t qemu_ram_pagesize_largest(void)
1824 RAMBlock *block;
1825 size_t largest = 0;
1827 RAMBLOCK_FOREACH(block) {
1828 largest = MAX(largest, qemu_ram_pagesize(block));
1831 return largest;
1834 static int memory_try_enable_merging(void *addr, size_t len)
1836 if (!machine_mem_merge(current_machine)) {
1837 /* disabled by the user */
1838 return 0;
1841 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1844 /* Only legal before guest might have detected the memory size: e.g. on
1845 * incoming migration, or right after reset.
1847 * As memory core doesn't know how is memory accessed, it is up to
1848 * resize callback to update device state and/or add assertions to detect
1849 * misuse, if necessary.
1851 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1853 assert(block);
1855 newsize = HOST_PAGE_ALIGN(newsize);
1857 if (block->used_length == newsize) {
1858 return 0;
1861 if (!(block->flags & RAM_RESIZEABLE)) {
1862 error_setg_errno(errp, EINVAL,
1863 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1864 " in != 0x" RAM_ADDR_FMT, block->idstr,
1865 newsize, block->used_length);
1866 return -EINVAL;
1869 if (block->max_length < newsize) {
1870 error_setg_errno(errp, EINVAL,
1871 "Length too large: %s: 0x" RAM_ADDR_FMT
1872 " > 0x" RAM_ADDR_FMT, block->idstr,
1873 newsize, block->max_length);
1874 return -EINVAL;
1877 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1878 block->used_length = newsize;
1879 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1880 DIRTY_CLIENTS_ALL);
1881 memory_region_set_size(block->mr, newsize);
1882 if (block->resized) {
1883 block->resized(block->idstr, newsize, block->host);
1885 return 0;
1888 /* Called with ram_list.mutex held */
1889 static void dirty_memory_extend(ram_addr_t old_ram_size,
1890 ram_addr_t new_ram_size)
1892 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1893 DIRTY_MEMORY_BLOCK_SIZE);
1894 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1895 DIRTY_MEMORY_BLOCK_SIZE);
1896 int i;
1898 /* Only need to extend if block count increased */
1899 if (new_num_blocks <= old_num_blocks) {
1900 return;
1903 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1904 DirtyMemoryBlocks *old_blocks;
1905 DirtyMemoryBlocks *new_blocks;
1906 int j;
1908 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
1909 new_blocks = g_malloc(sizeof(*new_blocks) +
1910 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1912 if (old_num_blocks) {
1913 memcpy(new_blocks->blocks, old_blocks->blocks,
1914 old_num_blocks * sizeof(old_blocks->blocks[0]));
1917 for (j = old_num_blocks; j < new_num_blocks; j++) {
1918 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1921 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1923 if (old_blocks) {
1924 g_free_rcu(old_blocks, rcu);
1929 static void ram_block_add(RAMBlock *new_block, Error **errp)
1931 RAMBlock *block;
1932 RAMBlock *last_block = NULL;
1933 ram_addr_t old_ram_size, new_ram_size;
1934 Error *err = NULL;
1936 old_ram_size = last_ram_page();
1938 qemu_mutex_lock_ramlist();
1939 new_block->offset = find_ram_offset(new_block->max_length);
1941 if (!new_block->host) {
1942 if (xen_enabled()) {
1943 xen_ram_alloc(new_block->offset, new_block->max_length,
1944 new_block->mr, &err);
1945 if (err) {
1946 error_propagate(errp, err);
1947 qemu_mutex_unlock_ramlist();
1948 return;
1950 } else {
1951 new_block->host = phys_mem_alloc(new_block->max_length,
1952 &new_block->mr->align);
1953 if (!new_block->host) {
1954 error_setg_errno(errp, errno,
1955 "cannot set up guest memory '%s'",
1956 memory_region_name(new_block->mr));
1957 qemu_mutex_unlock_ramlist();
1958 return;
1960 memory_try_enable_merging(new_block->host, new_block->max_length);
1964 new_ram_size = MAX(old_ram_size,
1965 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1966 if (new_ram_size > old_ram_size) {
1967 dirty_memory_extend(old_ram_size, new_ram_size);
1969 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1970 * QLIST (which has an RCU-friendly variant) does not have insertion at
1971 * tail, so save the last element in last_block.
1973 RAMBLOCK_FOREACH(block) {
1974 last_block = block;
1975 if (block->max_length < new_block->max_length) {
1976 break;
1979 if (block) {
1980 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1981 } else if (last_block) {
1982 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
1983 } else { /* list is empty */
1984 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1986 ram_list.mru_block = NULL;
1988 /* Write list before version */
1989 smp_wmb();
1990 ram_list.version++;
1991 qemu_mutex_unlock_ramlist();
1993 cpu_physical_memory_set_dirty_range(new_block->offset,
1994 new_block->used_length,
1995 DIRTY_CLIENTS_ALL);
1997 if (new_block->host) {
1998 qemu_ram_setup_dump(new_block->host, new_block->max_length);
1999 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2000 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
2001 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
2002 ram_block_notify_add(new_block->host, new_block->max_length);
2006 #ifdef __linux__
2007 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2008 bool share, int fd,
2009 Error **errp)
2011 RAMBlock *new_block;
2012 Error *local_err = NULL;
2013 int64_t file_size;
2015 if (xen_enabled()) {
2016 error_setg(errp, "-mem-path not supported with Xen");
2017 return NULL;
2020 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2021 error_setg(errp,
2022 "host lacks kvm mmu notifiers, -mem-path unsupported");
2023 return NULL;
2026 if (phys_mem_alloc != qemu_anon_ram_alloc) {
2028 * file_ram_alloc() needs to allocate just like
2029 * phys_mem_alloc, but we haven't bothered to provide
2030 * a hook there.
2032 error_setg(errp,
2033 "-mem-path not supported with this accelerator");
2034 return NULL;
2037 size = HOST_PAGE_ALIGN(size);
2038 file_size = get_file_size(fd);
2039 if (file_size > 0 && file_size < size) {
2040 error_setg(errp, "backing store %s size 0x%" PRIx64
2041 " does not match 'size' option 0x" RAM_ADDR_FMT,
2042 mem_path, file_size, size);
2043 return NULL;
2046 new_block = g_malloc0(sizeof(*new_block));
2047 new_block->mr = mr;
2048 new_block->used_length = size;
2049 new_block->max_length = size;
2050 new_block->flags = share ? RAM_SHARED : 0;
2051 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
2052 if (!new_block->host) {
2053 g_free(new_block);
2054 return NULL;
2057 ram_block_add(new_block, &local_err);
2058 if (local_err) {
2059 g_free(new_block);
2060 error_propagate(errp, local_err);
2061 return NULL;
2063 return new_block;
2068 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2069 bool share, const char *mem_path,
2070 Error **errp)
2072 int fd;
2073 bool created;
2074 RAMBlock *block;
2076 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2077 if (fd < 0) {
2078 return NULL;
2081 block = qemu_ram_alloc_from_fd(size, mr, share, fd, errp);
2082 if (!block) {
2083 if (created) {
2084 unlink(mem_path);
2086 close(fd);
2087 return NULL;
2090 return block;
2092 #endif
2094 static
2095 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2096 void (*resized)(const char*,
2097 uint64_t length,
2098 void *host),
2099 void *host, bool resizeable,
2100 MemoryRegion *mr, Error **errp)
2102 RAMBlock *new_block;
2103 Error *local_err = NULL;
2105 size = HOST_PAGE_ALIGN(size);
2106 max_size = HOST_PAGE_ALIGN(max_size);
2107 new_block = g_malloc0(sizeof(*new_block));
2108 new_block->mr = mr;
2109 new_block->resized = resized;
2110 new_block->used_length = size;
2111 new_block->max_length = max_size;
2112 assert(max_size >= size);
2113 new_block->fd = -1;
2114 new_block->page_size = getpagesize();
2115 new_block->host = host;
2116 if (host) {
2117 new_block->flags |= RAM_PREALLOC;
2119 if (resizeable) {
2120 new_block->flags |= RAM_RESIZEABLE;
2122 ram_block_add(new_block, &local_err);
2123 if (local_err) {
2124 g_free(new_block);
2125 error_propagate(errp, local_err);
2126 return NULL;
2128 return new_block;
2131 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2132 MemoryRegion *mr, Error **errp)
2134 return qemu_ram_alloc_internal(size, size, NULL, host, false, mr, errp);
2137 RAMBlock *qemu_ram_alloc(ram_addr_t size, MemoryRegion *mr, Error **errp)
2139 return qemu_ram_alloc_internal(size, size, NULL, NULL, false, mr, errp);
2142 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2143 void (*resized)(const char*,
2144 uint64_t length,
2145 void *host),
2146 MemoryRegion *mr, Error **errp)
2148 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true, mr, errp);
2151 static void reclaim_ramblock(RAMBlock *block)
2153 if (block->flags & RAM_PREALLOC) {
2155 } else if (xen_enabled()) {
2156 xen_invalidate_map_cache_entry(block->host);
2157 #ifndef _WIN32
2158 } else if (block->fd >= 0) {
2159 qemu_ram_munmap(block->host, block->max_length);
2160 close(block->fd);
2161 #endif
2162 } else {
2163 qemu_anon_ram_free(block->host, block->max_length);
2165 g_free(block);
2168 void qemu_ram_free(RAMBlock *block)
2170 if (!block) {
2171 return;
2174 if (block->host) {
2175 ram_block_notify_remove(block->host, block->max_length);
2178 qemu_mutex_lock_ramlist();
2179 QLIST_REMOVE_RCU(block, next);
2180 ram_list.mru_block = NULL;
2181 /* Write list before version */
2182 smp_wmb();
2183 ram_list.version++;
2184 call_rcu(block, reclaim_ramblock, rcu);
2185 qemu_mutex_unlock_ramlist();
2188 #ifndef _WIN32
2189 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2191 RAMBlock *block;
2192 ram_addr_t offset;
2193 int flags;
2194 void *area, *vaddr;
2196 RAMBLOCK_FOREACH(block) {
2197 offset = addr - block->offset;
2198 if (offset < block->max_length) {
2199 vaddr = ramblock_ptr(block, offset);
2200 if (block->flags & RAM_PREALLOC) {
2202 } else if (xen_enabled()) {
2203 abort();
2204 } else {
2205 flags = MAP_FIXED;
2206 if (block->fd >= 0) {
2207 flags |= (block->flags & RAM_SHARED ?
2208 MAP_SHARED : MAP_PRIVATE);
2209 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2210 flags, block->fd, offset);
2211 } else {
2213 * Remap needs to match alloc. Accelerators that
2214 * set phys_mem_alloc never remap. If they did,
2215 * we'd need a remap hook here.
2217 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2219 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2220 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2221 flags, -1, 0);
2223 if (area != vaddr) {
2224 error_report("Could not remap addr: "
2225 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2226 length, addr);
2227 exit(1);
2229 memory_try_enable_merging(vaddr, length);
2230 qemu_ram_setup_dump(vaddr, length);
2235 #endif /* !_WIN32 */
2237 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2238 * This should not be used for general purpose DMA. Use address_space_map
2239 * or address_space_rw instead. For local memory (e.g. video ram) that the
2240 * device owns, use memory_region_get_ram_ptr.
2242 * Called within RCU critical section.
2244 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2246 RAMBlock *block = ram_block;
2248 if (block == NULL) {
2249 block = qemu_get_ram_block(addr);
2250 addr -= block->offset;
2253 if (xen_enabled() && block->host == NULL) {
2254 /* We need to check if the requested address is in the RAM
2255 * because we don't want to map the entire memory in QEMU.
2256 * In that case just map until the end of the page.
2258 if (block->offset == 0) {
2259 return xen_map_cache(addr, 0, 0, false);
2262 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2264 return ramblock_ptr(block, addr);
2267 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2268 * but takes a size argument.
2270 * Called within RCU critical section.
2272 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2273 hwaddr *size, bool lock)
2275 RAMBlock *block = ram_block;
2276 if (*size == 0) {
2277 return NULL;
2280 if (block == NULL) {
2281 block = qemu_get_ram_block(addr);
2282 addr -= block->offset;
2284 *size = MIN(*size, block->max_length - addr);
2286 if (xen_enabled() && block->host == NULL) {
2287 /* We need to check if the requested address is in the RAM
2288 * because we don't want to map the entire memory in QEMU.
2289 * In that case just map the requested area.
2291 if (block->offset == 0) {
2292 return xen_map_cache(addr, *size, lock, lock);
2295 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2298 return ramblock_ptr(block, addr);
2302 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2303 * in that RAMBlock.
2305 * ptr: Host pointer to look up
2306 * round_offset: If true round the result offset down to a page boundary
2307 * *ram_addr: set to result ram_addr
2308 * *offset: set to result offset within the RAMBlock
2310 * Returns: RAMBlock (or NULL if not found)
2312 * By the time this function returns, the returned pointer is not protected
2313 * by RCU anymore. If the caller is not within an RCU critical section and
2314 * does not hold the iothread lock, it must have other means of protecting the
2315 * pointer, such as a reference to the region that includes the incoming
2316 * ram_addr_t.
2318 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2319 ram_addr_t *offset)
2321 RAMBlock *block;
2322 uint8_t *host = ptr;
2324 if (xen_enabled()) {
2325 ram_addr_t ram_addr;
2326 rcu_read_lock();
2327 ram_addr = xen_ram_addr_from_mapcache(ptr);
2328 block = qemu_get_ram_block(ram_addr);
2329 if (block) {
2330 *offset = ram_addr - block->offset;
2332 rcu_read_unlock();
2333 return block;
2336 rcu_read_lock();
2337 block = atomic_rcu_read(&ram_list.mru_block);
2338 if (block && block->host && host - block->host < block->max_length) {
2339 goto found;
2342 RAMBLOCK_FOREACH(block) {
2343 /* This case append when the block is not mapped. */
2344 if (block->host == NULL) {
2345 continue;
2347 if (host - block->host < block->max_length) {
2348 goto found;
2352 rcu_read_unlock();
2353 return NULL;
2355 found:
2356 *offset = (host - block->host);
2357 if (round_offset) {
2358 *offset &= TARGET_PAGE_MASK;
2360 rcu_read_unlock();
2361 return block;
2365 * Finds the named RAMBlock
2367 * name: The name of RAMBlock to find
2369 * Returns: RAMBlock (or NULL if not found)
2371 RAMBlock *qemu_ram_block_by_name(const char *name)
2373 RAMBlock *block;
2375 RAMBLOCK_FOREACH(block) {
2376 if (!strcmp(name, block->idstr)) {
2377 return block;
2381 return NULL;
2384 /* Some of the softmmu routines need to translate from a host pointer
2385 (typically a TLB entry) back to a ram offset. */
2386 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2388 RAMBlock *block;
2389 ram_addr_t offset;
2391 block = qemu_ram_block_from_host(ptr, false, &offset);
2392 if (!block) {
2393 return RAM_ADDR_INVALID;
2396 return block->offset + offset;
2399 /* Called within RCU critical section. */
2400 void memory_notdirty_write_prepare(NotDirtyInfo *ndi,
2401 CPUState *cpu,
2402 vaddr mem_vaddr,
2403 ram_addr_t ram_addr,
2404 unsigned size)
2406 ndi->cpu = cpu;
2407 ndi->ram_addr = ram_addr;
2408 ndi->mem_vaddr = mem_vaddr;
2409 ndi->size = size;
2410 ndi->locked = false;
2412 assert(tcg_enabled());
2413 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
2414 ndi->locked = true;
2415 tb_lock();
2416 tb_invalidate_phys_page_fast(ram_addr, size);
2420 /* Called within RCU critical section. */
2421 void memory_notdirty_write_complete(NotDirtyInfo *ndi)
2423 if (ndi->locked) {
2424 tb_unlock();
2427 /* Set both VGA and migration bits for simplicity and to remove
2428 * the notdirty callback faster.
2430 cpu_physical_memory_set_dirty_range(ndi->ram_addr, ndi->size,
2431 DIRTY_CLIENTS_NOCODE);
2432 /* we remove the notdirty callback only if the code has been
2433 flushed */
2434 if (!cpu_physical_memory_is_clean(ndi->ram_addr)) {
2435 tlb_set_dirty(ndi->cpu, ndi->mem_vaddr);
2439 /* Called within RCU critical section. */
2440 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2441 uint64_t val, unsigned size)
2443 NotDirtyInfo ndi;
2445 memory_notdirty_write_prepare(&ndi, current_cpu, current_cpu->mem_io_vaddr,
2446 ram_addr, size);
2448 switch (size) {
2449 case 1:
2450 stb_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2451 break;
2452 case 2:
2453 stw_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2454 break;
2455 case 4:
2456 stl_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2457 break;
2458 case 8:
2459 stq_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2460 break;
2461 default:
2462 abort();
2464 memory_notdirty_write_complete(&ndi);
2467 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
2468 unsigned size, bool is_write)
2470 return is_write;
2473 static const MemoryRegionOps notdirty_mem_ops = {
2474 .write = notdirty_mem_write,
2475 .valid.accepts = notdirty_mem_accepts,
2476 .endianness = DEVICE_NATIVE_ENDIAN,
2477 .valid = {
2478 .min_access_size = 1,
2479 .max_access_size = 8,
2480 .unaligned = false,
2482 .impl = {
2483 .min_access_size = 1,
2484 .max_access_size = 8,
2485 .unaligned = false,
2489 /* Generate a debug exception if a watchpoint has been hit. */
2490 static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
2492 CPUState *cpu = current_cpu;
2493 CPUClass *cc = CPU_GET_CLASS(cpu);
2494 target_ulong vaddr;
2495 CPUWatchpoint *wp;
2497 assert(tcg_enabled());
2498 if (cpu->watchpoint_hit) {
2499 /* We re-entered the check after replacing the TB. Now raise
2500 * the debug interrupt so that is will trigger after the
2501 * current instruction. */
2502 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2503 return;
2505 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
2506 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
2507 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2508 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2509 && (wp->flags & flags)) {
2510 if (flags == BP_MEM_READ) {
2511 wp->flags |= BP_WATCHPOINT_HIT_READ;
2512 } else {
2513 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2515 wp->hitaddr = vaddr;
2516 wp->hitattrs = attrs;
2517 if (!cpu->watchpoint_hit) {
2518 if (wp->flags & BP_CPU &&
2519 !cc->debug_check_watchpoint(cpu, wp)) {
2520 wp->flags &= ~BP_WATCHPOINT_HIT;
2521 continue;
2523 cpu->watchpoint_hit = wp;
2525 /* Both tb_lock and iothread_mutex will be reset when
2526 * cpu_loop_exit or cpu_loop_exit_noexc longjmp
2527 * back into the cpu_exec main loop.
2529 tb_lock();
2530 tb_check_watchpoint(cpu);
2531 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2532 cpu->exception_index = EXCP_DEBUG;
2533 cpu_loop_exit(cpu);
2534 } else {
2535 /* Force execution of one insn next time. */
2536 cpu->cflags_next_tb = 1 | curr_cflags();
2537 cpu_loop_exit_noexc(cpu);
2540 } else {
2541 wp->flags &= ~BP_WATCHPOINT_HIT;
2546 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2547 so these check for a hit then pass through to the normal out-of-line
2548 phys routines. */
2549 static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2550 unsigned size, MemTxAttrs attrs)
2552 MemTxResult res;
2553 uint64_t data;
2554 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2555 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2557 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2558 switch (size) {
2559 case 1:
2560 data = address_space_ldub(as, addr, attrs, &res);
2561 break;
2562 case 2:
2563 data = address_space_lduw(as, addr, attrs, &res);
2564 break;
2565 case 4:
2566 data = address_space_ldl(as, addr, attrs, &res);
2567 break;
2568 case 8:
2569 data = address_space_ldq(as, addr, attrs, &res);
2570 break;
2571 default: abort();
2573 *pdata = data;
2574 return res;
2577 static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2578 uint64_t val, unsigned size,
2579 MemTxAttrs attrs)
2581 MemTxResult res;
2582 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2583 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2585 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2586 switch (size) {
2587 case 1:
2588 address_space_stb(as, addr, val, attrs, &res);
2589 break;
2590 case 2:
2591 address_space_stw(as, addr, val, attrs, &res);
2592 break;
2593 case 4:
2594 address_space_stl(as, addr, val, attrs, &res);
2595 break;
2596 case 8:
2597 address_space_stq(as, addr, val, attrs, &res);
2598 break;
2599 default: abort();
2601 return res;
2604 static const MemoryRegionOps watch_mem_ops = {
2605 .read_with_attrs = watch_mem_read,
2606 .write_with_attrs = watch_mem_write,
2607 .endianness = DEVICE_NATIVE_ENDIAN,
2608 .valid = {
2609 .min_access_size = 1,
2610 .max_access_size = 8,
2611 .unaligned = false,
2613 .impl = {
2614 .min_access_size = 1,
2615 .max_access_size = 8,
2616 .unaligned = false,
2620 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2621 const uint8_t *buf, int len);
2622 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
2623 bool is_write);
2625 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2626 unsigned len, MemTxAttrs attrs)
2628 subpage_t *subpage = opaque;
2629 uint8_t buf[8];
2630 MemTxResult res;
2632 #if defined(DEBUG_SUBPAGE)
2633 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2634 subpage, len, addr);
2635 #endif
2636 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2637 if (res) {
2638 return res;
2640 switch (len) {
2641 case 1:
2642 *data = ldub_p(buf);
2643 return MEMTX_OK;
2644 case 2:
2645 *data = lduw_p(buf);
2646 return MEMTX_OK;
2647 case 4:
2648 *data = ldl_p(buf);
2649 return MEMTX_OK;
2650 case 8:
2651 *data = ldq_p(buf);
2652 return MEMTX_OK;
2653 default:
2654 abort();
2658 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2659 uint64_t value, unsigned len, MemTxAttrs attrs)
2661 subpage_t *subpage = opaque;
2662 uint8_t buf[8];
2664 #if defined(DEBUG_SUBPAGE)
2665 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2666 " value %"PRIx64"\n",
2667 __func__, subpage, len, addr, value);
2668 #endif
2669 switch (len) {
2670 case 1:
2671 stb_p(buf, value);
2672 break;
2673 case 2:
2674 stw_p(buf, value);
2675 break;
2676 case 4:
2677 stl_p(buf, value);
2678 break;
2679 case 8:
2680 stq_p(buf, value);
2681 break;
2682 default:
2683 abort();
2685 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2688 static bool subpage_accepts(void *opaque, hwaddr addr,
2689 unsigned len, bool is_write)
2691 subpage_t *subpage = opaque;
2692 #if defined(DEBUG_SUBPAGE)
2693 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2694 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2695 #endif
2697 return flatview_access_valid(subpage->fv, addr + subpage->base,
2698 len, is_write);
2701 static const MemoryRegionOps subpage_ops = {
2702 .read_with_attrs = subpage_read,
2703 .write_with_attrs = subpage_write,
2704 .impl.min_access_size = 1,
2705 .impl.max_access_size = 8,
2706 .valid.min_access_size = 1,
2707 .valid.max_access_size = 8,
2708 .valid.accepts = subpage_accepts,
2709 .endianness = DEVICE_NATIVE_ENDIAN,
2712 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
2713 uint16_t section)
2715 int idx, eidx;
2717 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2718 return -1;
2719 idx = SUBPAGE_IDX(start);
2720 eidx = SUBPAGE_IDX(end);
2721 #if defined(DEBUG_SUBPAGE)
2722 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2723 __func__, mmio, start, end, idx, eidx, section);
2724 #endif
2725 for (; idx <= eidx; idx++) {
2726 mmio->sub_section[idx] = section;
2729 return 0;
2732 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2734 subpage_t *mmio;
2736 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2737 mmio->fv = fv;
2738 mmio->base = base;
2739 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2740 NULL, TARGET_PAGE_SIZE);
2741 mmio->iomem.subpage = true;
2742 #if defined(DEBUG_SUBPAGE)
2743 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2744 mmio, base, TARGET_PAGE_SIZE);
2745 #endif
2746 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
2748 return mmio;
2751 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2753 assert(fv);
2754 MemoryRegionSection section = {
2755 .fv = fv,
2756 .mr = mr,
2757 .offset_within_address_space = 0,
2758 .offset_within_region = 0,
2759 .size = int128_2_64(),
2762 return phys_section_add(map, &section);
2765 static void readonly_mem_write(void *opaque, hwaddr addr,
2766 uint64_t val, unsigned size)
2768 /* Ignore any write to ROM. */
2771 static bool readonly_mem_accepts(void *opaque, hwaddr addr,
2772 unsigned size, bool is_write)
2774 return is_write;
2777 /* This will only be used for writes, because reads are special cased
2778 * to directly access the underlying host ram.
2780 static const MemoryRegionOps readonly_mem_ops = {
2781 .write = readonly_mem_write,
2782 .valid.accepts = readonly_mem_accepts,
2783 .endianness = DEVICE_NATIVE_ENDIAN,
2784 .valid = {
2785 .min_access_size = 1,
2786 .max_access_size = 8,
2787 .unaligned = false,
2789 .impl = {
2790 .min_access_size = 1,
2791 .max_access_size = 8,
2792 .unaligned = false,
2796 MemoryRegion *iotlb_to_region(CPUState *cpu, hwaddr index, MemTxAttrs attrs)
2798 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2799 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2800 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
2801 MemoryRegionSection *sections = d->map.sections;
2803 return sections[index & ~TARGET_PAGE_MASK].mr;
2806 static void io_mem_init(void)
2808 memory_region_init_io(&io_mem_rom, NULL, &readonly_mem_ops,
2809 NULL, NULL, UINT64_MAX);
2810 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2811 NULL, UINT64_MAX);
2813 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
2814 * which can be called without the iothread mutex.
2816 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
2817 NULL, UINT64_MAX);
2818 memory_region_clear_global_locking(&io_mem_notdirty);
2820 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
2821 NULL, UINT64_MAX);
2824 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2826 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2827 uint16_t n;
2829 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2830 assert(n == PHYS_SECTION_UNASSIGNED);
2831 n = dummy_section(&d->map, fv, &io_mem_notdirty);
2832 assert(n == PHYS_SECTION_NOTDIRTY);
2833 n = dummy_section(&d->map, fv, &io_mem_rom);
2834 assert(n == PHYS_SECTION_ROM);
2835 n = dummy_section(&d->map, fv, &io_mem_watch);
2836 assert(n == PHYS_SECTION_WATCH);
2838 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2840 return d;
2843 void address_space_dispatch_free(AddressSpaceDispatch *d)
2845 phys_sections_free(&d->map);
2846 g_free(d);
2849 static void tcg_commit(MemoryListener *listener)
2851 CPUAddressSpace *cpuas;
2852 AddressSpaceDispatch *d;
2854 /* since each CPU stores ram addresses in its TLB cache, we must
2855 reset the modified entries */
2856 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2857 cpu_reloading_memory_map();
2858 /* The CPU and TLB are protected by the iothread lock.
2859 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2860 * may have split the RCU critical section.
2862 d = address_space_to_dispatch(cpuas->as);
2863 atomic_rcu_set(&cpuas->memory_dispatch, d);
2864 tlb_flush(cpuas->cpu);
2867 static void memory_map_init(void)
2869 system_memory = g_malloc(sizeof(*system_memory));
2871 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2872 address_space_init(&address_space_memory, system_memory, "memory");
2874 system_io = g_malloc(sizeof(*system_io));
2875 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2876 65536);
2877 address_space_init(&address_space_io, system_io, "I/O");
2880 MemoryRegion *get_system_memory(void)
2882 return system_memory;
2885 MemoryRegion *get_system_io(void)
2887 return system_io;
2890 #endif /* !defined(CONFIG_USER_ONLY) */
2892 /* physical memory access (slow version, mainly for debug) */
2893 #if defined(CONFIG_USER_ONLY)
2894 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
2895 uint8_t *buf, int len, int is_write)
2897 int l, flags;
2898 target_ulong page;
2899 void * p;
2901 while (len > 0) {
2902 page = addr & TARGET_PAGE_MASK;
2903 l = (page + TARGET_PAGE_SIZE) - addr;
2904 if (l > len)
2905 l = len;
2906 flags = page_get_flags(page);
2907 if (!(flags & PAGE_VALID))
2908 return -1;
2909 if (is_write) {
2910 if (!(flags & PAGE_WRITE))
2911 return -1;
2912 /* XXX: this code should not depend on lock_user */
2913 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
2914 return -1;
2915 memcpy(p, buf, l);
2916 unlock_user(p, addr, l);
2917 } else {
2918 if (!(flags & PAGE_READ))
2919 return -1;
2920 /* XXX: this code should not depend on lock_user */
2921 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
2922 return -1;
2923 memcpy(buf, p, l);
2924 unlock_user(p, addr, 0);
2926 len -= l;
2927 buf += l;
2928 addr += l;
2930 return 0;
2933 #else
2935 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2936 hwaddr length)
2938 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2939 addr += memory_region_get_ram_addr(mr);
2941 /* No early return if dirty_log_mask is or becomes 0, because
2942 * cpu_physical_memory_set_dirty_range will still call
2943 * xen_modified_memory.
2945 if (dirty_log_mask) {
2946 dirty_log_mask =
2947 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2949 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2950 assert(tcg_enabled());
2951 tb_lock();
2952 tb_invalidate_phys_range(addr, addr + length);
2953 tb_unlock();
2954 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2956 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2959 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2961 unsigned access_size_max = mr->ops->valid.max_access_size;
2963 /* Regions are assumed to support 1-4 byte accesses unless
2964 otherwise specified. */
2965 if (access_size_max == 0) {
2966 access_size_max = 4;
2969 /* Bound the maximum access by the alignment of the address. */
2970 if (!mr->ops->impl.unaligned) {
2971 unsigned align_size_max = addr & -addr;
2972 if (align_size_max != 0 && align_size_max < access_size_max) {
2973 access_size_max = align_size_max;
2977 /* Don't attempt accesses larger than the maximum. */
2978 if (l > access_size_max) {
2979 l = access_size_max;
2981 l = pow2floor(l);
2983 return l;
2986 static bool prepare_mmio_access(MemoryRegion *mr)
2988 bool unlocked = !qemu_mutex_iothread_locked();
2989 bool release_lock = false;
2991 if (unlocked && mr->global_locking) {
2992 qemu_mutex_lock_iothread();
2993 unlocked = false;
2994 release_lock = true;
2996 if (mr->flush_coalesced_mmio) {
2997 if (unlocked) {
2998 qemu_mutex_lock_iothread();
3000 qemu_flush_coalesced_mmio_buffer();
3001 if (unlocked) {
3002 qemu_mutex_unlock_iothread();
3006 return release_lock;
3009 /* Called within RCU critical section. */
3010 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
3011 MemTxAttrs attrs,
3012 const uint8_t *buf,
3013 int len, hwaddr addr1,
3014 hwaddr l, MemoryRegion *mr)
3016 uint8_t *ptr;
3017 uint64_t val;
3018 MemTxResult result = MEMTX_OK;
3019 bool release_lock = false;
3021 for (;;) {
3022 if (!memory_access_is_direct(mr, true)) {
3023 release_lock |= prepare_mmio_access(mr);
3024 l = memory_access_size(mr, l, addr1);
3025 /* XXX: could force current_cpu to NULL to avoid
3026 potential bugs */
3027 switch (l) {
3028 case 8:
3029 /* 64 bit write access */
3030 val = ldq_p(buf);
3031 result |= memory_region_dispatch_write(mr, addr1, val, 8,
3032 attrs);
3033 break;
3034 case 4:
3035 /* 32 bit write access */
3036 val = (uint32_t)ldl_p(buf);
3037 result |= memory_region_dispatch_write(mr, addr1, val, 4,
3038 attrs);
3039 break;
3040 case 2:
3041 /* 16 bit write access */
3042 val = lduw_p(buf);
3043 result |= memory_region_dispatch_write(mr, addr1, val, 2,
3044 attrs);
3045 break;
3046 case 1:
3047 /* 8 bit write access */
3048 val = ldub_p(buf);
3049 result |= memory_region_dispatch_write(mr, addr1, val, 1,
3050 attrs);
3051 break;
3052 default:
3053 abort();
3055 } else {
3056 /* RAM case */
3057 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3058 memcpy(ptr, buf, l);
3059 invalidate_and_set_dirty(mr, addr1, l);
3062 if (release_lock) {
3063 qemu_mutex_unlock_iothread();
3064 release_lock = false;
3067 len -= l;
3068 buf += l;
3069 addr += l;
3071 if (!len) {
3072 break;
3075 l = len;
3076 mr = flatview_translate(fv, addr, &addr1, &l, true);
3079 return result;
3082 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
3083 const uint8_t *buf, int len)
3085 hwaddr l;
3086 hwaddr addr1;
3087 MemoryRegion *mr;
3088 MemTxResult result = MEMTX_OK;
3090 if (len > 0) {
3091 rcu_read_lock();
3092 l = len;
3093 mr = flatview_translate(fv, addr, &addr1, &l, true);
3094 result = flatview_write_continue(fv, addr, attrs, buf, len,
3095 addr1, l, mr);
3096 rcu_read_unlock();
3099 return result;
3102 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
3103 MemTxAttrs attrs,
3104 const uint8_t *buf, int len)
3106 return flatview_write(address_space_to_flatview(as), addr, attrs, buf, len);
3109 /* Called within RCU critical section. */
3110 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
3111 MemTxAttrs attrs, uint8_t *buf,
3112 int len, hwaddr addr1, hwaddr l,
3113 MemoryRegion *mr)
3115 uint8_t *ptr;
3116 uint64_t val;
3117 MemTxResult result = MEMTX_OK;
3118 bool release_lock = false;
3120 for (;;) {
3121 if (!memory_access_is_direct(mr, false)) {
3122 /* I/O case */
3123 release_lock |= prepare_mmio_access(mr);
3124 l = memory_access_size(mr, l, addr1);
3125 switch (l) {
3126 case 8:
3127 /* 64 bit read access */
3128 result |= memory_region_dispatch_read(mr, addr1, &val, 8,
3129 attrs);
3130 stq_p(buf, val);
3131 break;
3132 case 4:
3133 /* 32 bit read access */
3134 result |= memory_region_dispatch_read(mr, addr1, &val, 4,
3135 attrs);
3136 stl_p(buf, val);
3137 break;
3138 case 2:
3139 /* 16 bit read access */
3140 result |= memory_region_dispatch_read(mr, addr1, &val, 2,
3141 attrs);
3142 stw_p(buf, val);
3143 break;
3144 case 1:
3145 /* 8 bit read access */
3146 result |= memory_region_dispatch_read(mr, addr1, &val, 1,
3147 attrs);
3148 stb_p(buf, val);
3149 break;
3150 default:
3151 abort();
3153 } else {
3154 /* RAM case */
3155 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3156 memcpy(buf, ptr, l);
3159 if (release_lock) {
3160 qemu_mutex_unlock_iothread();
3161 release_lock = false;
3164 len -= l;
3165 buf += l;
3166 addr += l;
3168 if (!len) {
3169 break;
3172 l = len;
3173 mr = flatview_translate(fv, addr, &addr1, &l, false);
3176 return result;
3179 MemTxResult flatview_read_full(FlatView *fv, hwaddr addr,
3180 MemTxAttrs attrs, uint8_t *buf, int len)
3182 hwaddr l;
3183 hwaddr addr1;
3184 MemoryRegion *mr;
3185 MemTxResult result = MEMTX_OK;
3187 if (len > 0) {
3188 rcu_read_lock();
3189 l = len;
3190 mr = flatview_translate(fv, addr, &addr1, &l, false);
3191 result = flatview_read_continue(fv, addr, attrs, buf, len,
3192 addr1, l, mr);
3193 rcu_read_unlock();
3196 return result;
3199 static MemTxResult flatview_rw(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
3200 uint8_t *buf, int len, bool is_write)
3202 if (is_write) {
3203 return flatview_write(fv, addr, attrs, (uint8_t *)buf, len);
3204 } else {
3205 return flatview_read(fv, addr, attrs, (uint8_t *)buf, len);
3209 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr,
3210 MemTxAttrs attrs, uint8_t *buf,
3211 int len, bool is_write)
3213 return flatview_rw(address_space_to_flatview(as),
3214 addr, attrs, buf, len, is_write);
3217 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
3218 int len, int is_write)
3220 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3221 buf, len, is_write);
3224 enum write_rom_type {
3225 WRITE_DATA,
3226 FLUSH_CACHE,
3229 static inline void cpu_physical_memory_write_rom_internal(AddressSpace *as,
3230 hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
3232 hwaddr l;
3233 uint8_t *ptr;
3234 hwaddr addr1;
3235 MemoryRegion *mr;
3237 rcu_read_lock();
3238 while (len > 0) {
3239 l = len;
3240 mr = address_space_translate(as, addr, &addr1, &l, true);
3242 if (!(memory_region_is_ram(mr) ||
3243 memory_region_is_romd(mr))) {
3244 l = memory_access_size(mr, l, addr1);
3245 } else {
3246 /* ROM/RAM case */
3247 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3248 switch (type) {
3249 case WRITE_DATA:
3250 memcpy(ptr, buf, l);
3251 invalidate_and_set_dirty(mr, addr1, l);
3252 break;
3253 case FLUSH_CACHE:
3254 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
3255 break;
3258 len -= l;
3259 buf += l;
3260 addr += l;
3262 rcu_read_unlock();
3265 /* used for ROM loading : can write in RAM and ROM */
3266 void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
3267 const uint8_t *buf, int len)
3269 cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
3272 void cpu_flush_icache_range(hwaddr start, int len)
3275 * This function should do the same thing as an icache flush that was
3276 * triggered from within the guest. For TCG we are always cache coherent,
3277 * so there is no need to flush anything. For KVM / Xen we need to flush
3278 * the host's instruction cache at least.
3280 if (tcg_enabled()) {
3281 return;
3284 cpu_physical_memory_write_rom_internal(&address_space_memory,
3285 start, NULL, len, FLUSH_CACHE);
3288 typedef struct {
3289 MemoryRegion *mr;
3290 void *buffer;
3291 hwaddr addr;
3292 hwaddr len;
3293 bool in_use;
3294 } BounceBuffer;
3296 static BounceBuffer bounce;
3298 typedef struct MapClient {
3299 QEMUBH *bh;
3300 QLIST_ENTRY(MapClient) link;
3301 } MapClient;
3303 QemuMutex map_client_list_lock;
3304 static QLIST_HEAD(map_client_list, MapClient) map_client_list
3305 = QLIST_HEAD_INITIALIZER(map_client_list);
3307 static void cpu_unregister_map_client_do(MapClient *client)
3309 QLIST_REMOVE(client, link);
3310 g_free(client);
3313 static void cpu_notify_map_clients_locked(void)
3315 MapClient *client;
3317 while (!QLIST_EMPTY(&map_client_list)) {
3318 client = QLIST_FIRST(&map_client_list);
3319 qemu_bh_schedule(client->bh);
3320 cpu_unregister_map_client_do(client);
3324 void cpu_register_map_client(QEMUBH *bh)
3326 MapClient *client = g_malloc(sizeof(*client));
3328 qemu_mutex_lock(&map_client_list_lock);
3329 client->bh = bh;
3330 QLIST_INSERT_HEAD(&map_client_list, client, link);
3331 if (!atomic_read(&bounce.in_use)) {
3332 cpu_notify_map_clients_locked();
3334 qemu_mutex_unlock(&map_client_list_lock);
3337 void cpu_exec_init_all(void)
3339 qemu_mutex_init(&ram_list.mutex);
3340 /* The data structures we set up here depend on knowing the page size,
3341 * so no more changes can be made after this point.
3342 * In an ideal world, nothing we did before we had finished the
3343 * machine setup would care about the target page size, and we could
3344 * do this much later, rather than requiring board models to state
3345 * up front what their requirements are.
3347 finalize_target_page_bits();
3348 io_mem_init();
3349 memory_map_init();
3350 qemu_mutex_init(&map_client_list_lock);
3353 void cpu_unregister_map_client(QEMUBH *bh)
3355 MapClient *client;
3357 qemu_mutex_lock(&map_client_list_lock);
3358 QLIST_FOREACH(client, &map_client_list, link) {
3359 if (client->bh == bh) {
3360 cpu_unregister_map_client_do(client);
3361 break;
3364 qemu_mutex_unlock(&map_client_list_lock);
3367 static void cpu_notify_map_clients(void)
3369 qemu_mutex_lock(&map_client_list_lock);
3370 cpu_notify_map_clients_locked();
3371 qemu_mutex_unlock(&map_client_list_lock);
3374 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
3375 bool is_write)
3377 MemoryRegion *mr;
3378 hwaddr l, xlat;
3380 rcu_read_lock();
3381 while (len > 0) {
3382 l = len;
3383 mr = flatview_translate(fv, addr, &xlat, &l, is_write);
3384 if (!memory_access_is_direct(mr, is_write)) {
3385 l = memory_access_size(mr, l, addr);
3386 if (!memory_region_access_valid(mr, xlat, l, is_write)) {
3387 rcu_read_unlock();
3388 return false;
3392 len -= l;
3393 addr += l;
3395 rcu_read_unlock();
3396 return true;
3399 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3400 int len, bool is_write)
3402 return flatview_access_valid(address_space_to_flatview(as),
3403 addr, len, is_write);
3406 static hwaddr
3407 flatview_extend_translation(FlatView *fv, hwaddr addr,
3408 hwaddr target_len,
3409 MemoryRegion *mr, hwaddr base, hwaddr len,
3410 bool is_write)
3412 hwaddr done = 0;
3413 hwaddr xlat;
3414 MemoryRegion *this_mr;
3416 for (;;) {
3417 target_len -= len;
3418 addr += len;
3419 done += len;
3420 if (target_len == 0) {
3421 return done;
3424 len = target_len;
3425 this_mr = flatview_translate(fv, addr, &xlat,
3426 &len, is_write);
3427 if (this_mr != mr || xlat != base + done) {
3428 return done;
3433 /* Map a physical memory region into a host virtual address.
3434 * May map a subset of the requested range, given by and returned in *plen.
3435 * May return NULL if resources needed to perform the mapping are exhausted.
3436 * Use only for reads OR writes - not for read-modify-write operations.
3437 * Use cpu_register_map_client() to know when retrying the map operation is
3438 * likely to succeed.
3440 void *address_space_map(AddressSpace *as,
3441 hwaddr addr,
3442 hwaddr *plen,
3443 bool is_write)
3445 hwaddr len = *plen;
3446 hwaddr l, xlat;
3447 MemoryRegion *mr;
3448 void *ptr;
3449 FlatView *fv = address_space_to_flatview(as);
3451 if (len == 0) {
3452 return NULL;
3455 l = len;
3456 rcu_read_lock();
3457 mr = flatview_translate(fv, addr, &xlat, &l, is_write);
3459 if (!memory_access_is_direct(mr, is_write)) {
3460 if (atomic_xchg(&bounce.in_use, true)) {
3461 rcu_read_unlock();
3462 return NULL;
3464 /* Avoid unbounded allocations */
3465 l = MIN(l, TARGET_PAGE_SIZE);
3466 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3467 bounce.addr = addr;
3468 bounce.len = l;
3470 memory_region_ref(mr);
3471 bounce.mr = mr;
3472 if (!is_write) {
3473 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3474 bounce.buffer, l);
3477 rcu_read_unlock();
3478 *plen = l;
3479 return bounce.buffer;
3483 memory_region_ref(mr);
3484 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3485 l, is_write);
3486 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3487 rcu_read_unlock();
3489 return ptr;
3492 /* Unmaps a memory region previously mapped by address_space_map().
3493 * Will also mark the memory as dirty if is_write == 1. access_len gives
3494 * the amount of memory that was actually read or written by the caller.
3496 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3497 int is_write, hwaddr access_len)
3499 if (buffer != bounce.buffer) {
3500 MemoryRegion *mr;
3501 ram_addr_t addr1;
3503 mr = memory_region_from_host(buffer, &addr1);
3504 assert(mr != NULL);
3505 if (is_write) {
3506 invalidate_and_set_dirty(mr, addr1, access_len);
3508 if (xen_enabled()) {
3509 xen_invalidate_map_cache_entry(buffer);
3511 memory_region_unref(mr);
3512 return;
3514 if (is_write) {
3515 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3516 bounce.buffer, access_len);
3518 qemu_vfree(bounce.buffer);
3519 bounce.buffer = NULL;
3520 memory_region_unref(bounce.mr);
3521 atomic_mb_set(&bounce.in_use, false);
3522 cpu_notify_map_clients();
3525 void *cpu_physical_memory_map(hwaddr addr,
3526 hwaddr *plen,
3527 int is_write)
3529 return address_space_map(&address_space_memory, addr, plen, is_write);
3532 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3533 int is_write, hwaddr access_len)
3535 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3538 #define ARG1_DECL AddressSpace *as
3539 #define ARG1 as
3540 #define SUFFIX
3541 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3542 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3543 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3544 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3545 #define RCU_READ_LOCK(...) rcu_read_lock()
3546 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3547 #include "memory_ldst.inc.c"
3549 int64_t address_space_cache_init(MemoryRegionCache *cache,
3550 AddressSpace *as,
3551 hwaddr addr,
3552 hwaddr len,
3553 bool is_write)
3555 cache->len = len;
3556 cache->as = as;
3557 cache->xlat = addr;
3558 return len;
3561 void address_space_cache_invalidate(MemoryRegionCache *cache,
3562 hwaddr addr,
3563 hwaddr access_len)
3567 void address_space_cache_destroy(MemoryRegionCache *cache)
3569 cache->as = NULL;
3572 #define ARG1_DECL MemoryRegionCache *cache
3573 #define ARG1 cache
3574 #define SUFFIX _cached
3575 #define TRANSLATE(addr, ...) \
3576 address_space_translate(cache->as, cache->xlat + (addr), __VA_ARGS__)
3577 #define IS_DIRECT(mr, is_write) true
3578 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3579 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3580 #define RCU_READ_LOCK() rcu_read_lock()
3581 #define RCU_READ_UNLOCK() rcu_read_unlock()
3582 #include "memory_ldst.inc.c"
3584 /* virtual memory access for debug (includes writing to ROM) */
3585 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3586 uint8_t *buf, int len, int is_write)
3588 int l;
3589 hwaddr phys_addr;
3590 target_ulong page;
3592 cpu_synchronize_state(cpu);
3593 while (len > 0) {
3594 int asidx;
3595 MemTxAttrs attrs;
3597 page = addr & TARGET_PAGE_MASK;
3598 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3599 asidx = cpu_asidx_from_attrs(cpu, attrs);
3600 /* if no physical page mapped, return an error */
3601 if (phys_addr == -1)
3602 return -1;
3603 l = (page + TARGET_PAGE_SIZE) - addr;
3604 if (l > len)
3605 l = len;
3606 phys_addr += (addr & ~TARGET_PAGE_MASK);
3607 if (is_write) {
3608 cpu_physical_memory_write_rom(cpu->cpu_ases[asidx].as,
3609 phys_addr, buf, l);
3610 } else {
3611 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3612 MEMTXATTRS_UNSPECIFIED,
3613 buf, l, 0);
3615 len -= l;
3616 buf += l;
3617 addr += l;
3619 return 0;
3623 * Allows code that needs to deal with migration bitmaps etc to still be built
3624 * target independent.
3626 size_t qemu_target_page_size(void)
3628 return TARGET_PAGE_SIZE;
3631 int qemu_target_page_bits(void)
3633 return TARGET_PAGE_BITS;
3636 int qemu_target_page_bits_min(void)
3638 return TARGET_PAGE_BITS_MIN;
3640 #endif
3643 * A helper function for the _utterly broken_ virtio device model to find out if
3644 * it's running on a big endian machine. Don't do this at home kids!
3646 bool target_words_bigendian(void);
3647 bool target_words_bigendian(void)
3649 #if defined(TARGET_WORDS_BIGENDIAN)
3650 return true;
3651 #else
3652 return false;
3653 #endif
3656 #ifndef CONFIG_USER_ONLY
3657 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3659 MemoryRegion*mr;
3660 hwaddr l = 1;
3661 bool res;
3663 rcu_read_lock();
3664 mr = address_space_translate(&address_space_memory,
3665 phys_addr, &phys_addr, &l, false);
3667 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3668 rcu_read_unlock();
3669 return res;
3672 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3674 RAMBlock *block;
3675 int ret = 0;
3677 rcu_read_lock();
3678 RAMBLOCK_FOREACH(block) {
3679 ret = func(block->idstr, block->host, block->offset,
3680 block->used_length, opaque);
3681 if (ret) {
3682 break;
3685 rcu_read_unlock();
3686 return ret;
3690 * Unmap pages of memory from start to start+length such that
3691 * they a) read as 0, b) Trigger whatever fault mechanism
3692 * the OS provides for postcopy.
3693 * The pages must be unmapped by the end of the function.
3694 * Returns: 0 on success, none-0 on failure
3697 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3699 int ret = -1;
3701 uint8_t *host_startaddr = rb->host + start;
3703 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
3704 error_report("ram_block_discard_range: Unaligned start address: %p",
3705 host_startaddr);
3706 goto err;
3709 if ((start + length) <= rb->used_length) {
3710 uint8_t *host_endaddr = host_startaddr + length;
3711 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
3712 error_report("ram_block_discard_range: Unaligned end address: %p",
3713 host_endaddr);
3714 goto err;
3717 errno = ENOTSUP; /* If we are missing MADVISE etc */
3719 if (rb->page_size == qemu_host_page_size) {
3720 #if defined(CONFIG_MADVISE)
3721 /* Note: We need the madvise MADV_DONTNEED behaviour of definitely
3722 * freeing the page.
3724 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3725 #endif
3726 } else {
3727 /* Huge page case - unfortunately it can't do DONTNEED, but
3728 * it can do the equivalent by FALLOC_FL_PUNCH_HOLE in the
3729 * huge page file.
3731 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3732 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3733 start, length);
3734 #endif
3736 if (ret) {
3737 ret = -errno;
3738 error_report("ram_block_discard_range: Failed to discard range "
3739 "%s:%" PRIx64 " +%zx (%d)",
3740 rb->idstr, start, length, ret);
3742 } else {
3743 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3744 "/%zx/" RAM_ADDR_FMT")",
3745 rb->idstr, start, length, rb->used_length);
3748 err:
3749 return ret;
3752 #endif
3754 void page_size_init(void)
3756 /* NOTE: we can always suppose that qemu_host_page_size >=
3757 TARGET_PAGE_SIZE */
3758 if (qemu_host_page_size == 0) {
3759 qemu_host_page_size = qemu_real_host_page_size;
3761 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
3762 qemu_host_page_size = TARGET_PAGE_SIZE;
3764 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;
3767 #if !defined(CONFIG_USER_ONLY)
3769 static void mtree_print_phys_entries(fprintf_function mon, void *f,
3770 int start, int end, int skip, int ptr)
3772 if (start == end - 1) {
3773 mon(f, "\t%3d ", start);
3774 } else {
3775 mon(f, "\t%3d..%-3d ", start, end - 1);
3777 mon(f, " skip=%d ", skip);
3778 if (ptr == PHYS_MAP_NODE_NIL) {
3779 mon(f, " ptr=NIL");
3780 } else if (!skip) {
3781 mon(f, " ptr=#%d", ptr);
3782 } else {
3783 mon(f, " ptr=[%d]", ptr);
3785 mon(f, "\n");
3788 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3789 int128_sub((size), int128_one())) : 0)
3791 void mtree_print_dispatch(fprintf_function mon, void *f,
3792 AddressSpaceDispatch *d, MemoryRegion *root)
3794 int i;
3796 mon(f, " Dispatch\n");
3797 mon(f, " Physical sections\n");
3799 for (i = 0; i < d->map.sections_nb; ++i) {
3800 MemoryRegionSection *s = d->map.sections + i;
3801 const char *names[] = { " [unassigned]", " [not dirty]",
3802 " [ROM]", " [watch]" };
3804 mon(f, " #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx " %s%s%s%s%s",
3806 s->offset_within_address_space,
3807 s->offset_within_address_space + MR_SIZE(s->mr->size),
3808 s->mr->name ? s->mr->name : "(noname)",
3809 i < ARRAY_SIZE(names) ? names[i] : "",
3810 s->mr == root ? " [ROOT]" : "",
3811 s == d->mru_section ? " [MRU]" : "",
3812 s->mr->is_iommu ? " [iommu]" : "");
3814 if (s->mr->alias) {
3815 mon(f, " alias=%s", s->mr->alias->name ?
3816 s->mr->alias->name : "noname");
3818 mon(f, "\n");
3821 mon(f, " Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3822 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3823 for (i = 0; i < d->map.nodes_nb; ++i) {
3824 int j, jprev;
3825 PhysPageEntry prev;
3826 Node *n = d->map.nodes + i;
3828 mon(f, " [%d]\n", i);
3830 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3831 PhysPageEntry *pe = *n + j;
3833 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3834 continue;
3837 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
3839 jprev = j;
3840 prev = *pe;
3843 if (jprev != ARRAY_SIZE(*n)) {
3844 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
3849 #endif