Make flatview_do_translate() take a MemTxAttrs argument
[qemu.git] / exec.c
blobe84e0d8c58a32777eaaa0e04daecc8c44923ecd1
1 /*
2 * Virtual page mapping
4 * Copyright (c) 2003 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 #include "qemu/osdep.h"
20 #include "qapi/error.h"
22 #include "qemu/cutils.h"
23 #include "cpu.h"
24 #include "exec/exec-all.h"
25 #include "exec/target_page.h"
26 #include "tcg.h"
27 #include "hw/qdev-core.h"
28 #include "hw/qdev-properties.h"
29 #if !defined(CONFIG_USER_ONLY)
30 #include "hw/boards.h"
31 #include "hw/xen/xen.h"
32 #endif
33 #include "sysemu/kvm.h"
34 #include "sysemu/sysemu.h"
35 #include "qemu/timer.h"
36 #include "qemu/config-file.h"
37 #include "qemu/error-report.h"
38 #if defined(CONFIG_USER_ONLY)
39 #include "qemu.h"
40 #else /* !CONFIG_USER_ONLY */
41 #include "hw/hw.h"
42 #include "exec/memory.h"
43 #include "exec/ioport.h"
44 #include "sysemu/dma.h"
45 #include "sysemu/numa.h"
46 #include "sysemu/hw_accel.h"
47 #include "exec/address-spaces.h"
48 #include "sysemu/xen-mapcache.h"
49 #include "trace-root.h"
51 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
52 #include <linux/falloc.h>
53 #endif
55 #endif
56 #include "qemu/rcu_queue.h"
57 #include "qemu/main-loop.h"
58 #include "translate-all.h"
59 #include "sysemu/replay.h"
61 #include "exec/memory-internal.h"
62 #include "exec/ram_addr.h"
63 #include "exec/log.h"
65 #include "migration/vmstate.h"
67 #include "qemu/range.h"
68 #ifndef _WIN32
69 #include "qemu/mmap-alloc.h"
70 #endif
72 #include "monitor/monitor.h"
74 //#define DEBUG_SUBPAGE
76 #if !defined(CONFIG_USER_ONLY)
77 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
78 * are protected by the ramlist lock.
80 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
82 static MemoryRegion *system_memory;
83 static MemoryRegion *system_io;
85 AddressSpace address_space_io;
86 AddressSpace address_space_memory;
88 MemoryRegion io_mem_rom, io_mem_notdirty;
89 static MemoryRegion io_mem_unassigned;
91 /* RAM is pre-allocated and passed into qemu_ram_alloc_from_ptr */
92 #define RAM_PREALLOC (1 << 0)
94 /* RAM is mmap-ed with MAP_SHARED */
95 #define RAM_SHARED (1 << 1)
97 /* Only a portion of RAM (used_length) is actually used, and migrated.
98 * This used_length size can change across reboots.
100 #define RAM_RESIZEABLE (1 << 2)
102 /* UFFDIO_ZEROPAGE is available on this RAMBlock to atomically
103 * zero the page and wake waiting processes.
104 * (Set during postcopy)
106 #define RAM_UF_ZEROPAGE (1 << 3)
107 #endif
109 #ifdef TARGET_PAGE_BITS_VARY
110 int target_page_bits;
111 bool target_page_bits_decided;
112 #endif
114 struct CPUTailQ cpus = QTAILQ_HEAD_INITIALIZER(cpus);
115 /* current CPU in the current thread. It is only valid inside
116 cpu_exec() */
117 __thread CPUState *current_cpu;
118 /* 0 = Do not count executed instructions.
119 1 = Precise instruction counting.
120 2 = Adaptive rate instruction counting. */
121 int use_icount;
123 uintptr_t qemu_host_page_size;
124 intptr_t qemu_host_page_mask;
126 bool set_preferred_target_page_bits(int bits)
128 /* The target page size is the lowest common denominator for all
129 * the CPUs in the system, so we can only make it smaller, never
130 * larger. And we can't make it smaller once we've committed to
131 * a particular size.
133 #ifdef TARGET_PAGE_BITS_VARY
134 assert(bits >= TARGET_PAGE_BITS_MIN);
135 if (target_page_bits == 0 || target_page_bits > bits) {
136 if (target_page_bits_decided) {
137 return false;
139 target_page_bits = bits;
141 #endif
142 return true;
145 #if !defined(CONFIG_USER_ONLY)
147 static void finalize_target_page_bits(void)
149 #ifdef TARGET_PAGE_BITS_VARY
150 if (target_page_bits == 0) {
151 target_page_bits = TARGET_PAGE_BITS_MIN;
153 target_page_bits_decided = true;
154 #endif
157 typedef struct PhysPageEntry PhysPageEntry;
159 struct PhysPageEntry {
160 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
161 uint32_t skip : 6;
162 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
163 uint32_t ptr : 26;
166 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
168 /* Size of the L2 (and L3, etc) page tables. */
169 #define ADDR_SPACE_BITS 64
171 #define P_L2_BITS 9
172 #define P_L2_SIZE (1 << P_L2_BITS)
174 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
176 typedef PhysPageEntry Node[P_L2_SIZE];
178 typedef struct PhysPageMap {
179 struct rcu_head rcu;
181 unsigned sections_nb;
182 unsigned sections_nb_alloc;
183 unsigned nodes_nb;
184 unsigned nodes_nb_alloc;
185 Node *nodes;
186 MemoryRegionSection *sections;
187 } PhysPageMap;
189 struct AddressSpaceDispatch {
190 MemoryRegionSection *mru_section;
191 /* This is a multi-level map on the physical address space.
192 * The bottom level has pointers to MemoryRegionSections.
194 PhysPageEntry phys_map;
195 PhysPageMap map;
198 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
199 typedef struct subpage_t {
200 MemoryRegion iomem;
201 FlatView *fv;
202 hwaddr base;
203 uint16_t sub_section[];
204 } subpage_t;
206 #define PHYS_SECTION_UNASSIGNED 0
207 #define PHYS_SECTION_NOTDIRTY 1
208 #define PHYS_SECTION_ROM 2
209 #define PHYS_SECTION_WATCH 3
211 static void io_mem_init(void);
212 static void memory_map_init(void);
213 static void tcg_commit(MemoryListener *listener);
215 static MemoryRegion io_mem_watch;
218 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
219 * @cpu: the CPU whose AddressSpace this is
220 * @as: the AddressSpace itself
221 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
222 * @tcg_as_listener: listener for tracking changes to the AddressSpace
224 struct CPUAddressSpace {
225 CPUState *cpu;
226 AddressSpace *as;
227 struct AddressSpaceDispatch *memory_dispatch;
228 MemoryListener tcg_as_listener;
231 struct DirtyBitmapSnapshot {
232 ram_addr_t start;
233 ram_addr_t end;
234 unsigned long dirty[];
237 #endif
239 #if !defined(CONFIG_USER_ONLY)
241 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
243 static unsigned alloc_hint = 16;
244 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
245 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, alloc_hint);
246 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, map->nodes_nb + nodes);
247 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
248 alloc_hint = map->nodes_nb_alloc;
252 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
254 unsigned i;
255 uint32_t ret;
256 PhysPageEntry e;
257 PhysPageEntry *p;
259 ret = map->nodes_nb++;
260 p = map->nodes[ret];
261 assert(ret != PHYS_MAP_NODE_NIL);
262 assert(ret != map->nodes_nb_alloc);
264 e.skip = leaf ? 0 : 1;
265 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
266 for (i = 0; i < P_L2_SIZE; ++i) {
267 memcpy(&p[i], &e, sizeof(e));
269 return ret;
272 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
273 hwaddr *index, hwaddr *nb, uint16_t leaf,
274 int level)
276 PhysPageEntry *p;
277 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
279 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
280 lp->ptr = phys_map_node_alloc(map, level == 0);
282 p = map->nodes[lp->ptr];
283 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
285 while (*nb && lp < &p[P_L2_SIZE]) {
286 if ((*index & (step - 1)) == 0 && *nb >= step) {
287 lp->skip = 0;
288 lp->ptr = leaf;
289 *index += step;
290 *nb -= step;
291 } else {
292 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
294 ++lp;
298 static void phys_page_set(AddressSpaceDispatch *d,
299 hwaddr index, hwaddr nb,
300 uint16_t leaf)
302 /* Wildly overreserve - it doesn't matter much. */
303 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
305 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
308 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
309 * and update our entry so we can skip it and go directly to the destination.
311 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
313 unsigned valid_ptr = P_L2_SIZE;
314 int valid = 0;
315 PhysPageEntry *p;
316 int i;
318 if (lp->ptr == PHYS_MAP_NODE_NIL) {
319 return;
322 p = nodes[lp->ptr];
323 for (i = 0; i < P_L2_SIZE; i++) {
324 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
325 continue;
328 valid_ptr = i;
329 valid++;
330 if (p[i].skip) {
331 phys_page_compact(&p[i], nodes);
335 /* We can only compress if there's only one child. */
336 if (valid != 1) {
337 return;
340 assert(valid_ptr < P_L2_SIZE);
342 /* Don't compress if it won't fit in the # of bits we have. */
343 if (lp->skip + p[valid_ptr].skip >= (1 << 3)) {
344 return;
347 lp->ptr = p[valid_ptr].ptr;
348 if (!p[valid_ptr].skip) {
349 /* If our only child is a leaf, make this a leaf. */
350 /* By design, we should have made this node a leaf to begin with so we
351 * should never reach here.
352 * But since it's so simple to handle this, let's do it just in case we
353 * change this rule.
355 lp->skip = 0;
356 } else {
357 lp->skip += p[valid_ptr].skip;
361 void address_space_dispatch_compact(AddressSpaceDispatch *d)
363 if (d->phys_map.skip) {
364 phys_page_compact(&d->phys_map, d->map.nodes);
368 static inline bool section_covers_addr(const MemoryRegionSection *section,
369 hwaddr addr)
371 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
372 * the section must cover the entire address space.
374 return int128_gethi(section->size) ||
375 range_covers_byte(section->offset_within_address_space,
376 int128_getlo(section->size), addr);
379 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
381 PhysPageEntry lp = d->phys_map, *p;
382 Node *nodes = d->map.nodes;
383 MemoryRegionSection *sections = d->map.sections;
384 hwaddr index = addr >> TARGET_PAGE_BITS;
385 int i;
387 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
388 if (lp.ptr == PHYS_MAP_NODE_NIL) {
389 return &sections[PHYS_SECTION_UNASSIGNED];
391 p = nodes[lp.ptr];
392 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
395 if (section_covers_addr(&sections[lp.ptr], addr)) {
396 return &sections[lp.ptr];
397 } else {
398 return &sections[PHYS_SECTION_UNASSIGNED];
402 bool memory_region_is_unassigned(MemoryRegion *mr)
404 return mr != &io_mem_rom && mr != &io_mem_notdirty && !mr->rom_device
405 && mr != &io_mem_watch;
408 /* Called from RCU critical section */
409 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
410 hwaddr addr,
411 bool resolve_subpage)
413 MemoryRegionSection *section = atomic_read(&d->mru_section);
414 subpage_t *subpage;
416 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
417 !section_covers_addr(section, addr)) {
418 section = phys_page_find(d, addr);
419 atomic_set(&d->mru_section, section);
421 if (resolve_subpage && section->mr->subpage) {
422 subpage = container_of(section->mr, subpage_t, iomem);
423 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
425 return section;
428 /* Called from RCU critical section */
429 static MemoryRegionSection *
430 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
431 hwaddr *plen, bool resolve_subpage)
433 MemoryRegionSection *section;
434 MemoryRegion *mr;
435 Int128 diff;
437 section = address_space_lookup_region(d, addr, resolve_subpage);
438 /* Compute offset within MemoryRegionSection */
439 addr -= section->offset_within_address_space;
441 /* Compute offset within MemoryRegion */
442 *xlat = addr + section->offset_within_region;
444 mr = section->mr;
446 /* MMIO registers can be expected to perform full-width accesses based only
447 * on their address, without considering adjacent registers that could
448 * decode to completely different MemoryRegions. When such registers
449 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
450 * regions overlap wildly. For this reason we cannot clamp the accesses
451 * here.
453 * If the length is small (as is the case for address_space_ldl/stl),
454 * everything works fine. If the incoming length is large, however,
455 * the caller really has to do the clamping through memory_access_size.
457 if (memory_region_is_ram(mr)) {
458 diff = int128_sub(section->size, int128_make64(addr));
459 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
461 return section;
465 * address_space_translate_iommu - translate an address through an IOMMU
466 * memory region and then through the target address space.
468 * @iommu_mr: the IOMMU memory region that we start the translation from
469 * @addr: the address to be translated through the MMU
470 * @xlat: the translated address offset within the destination memory region.
471 * It cannot be %NULL.
472 * @plen_out: valid read/write length of the translated address. It
473 * cannot be %NULL.
474 * @page_mask_out: page mask for the translated address. This
475 * should only be meaningful for IOMMU translated
476 * addresses, since there may be huge pages that this bit
477 * would tell. It can be %NULL if we don't care about it.
478 * @is_write: whether the translation operation is for write
479 * @is_mmio: whether this can be MMIO, set true if it can
480 * @target_as: the address space targeted by the IOMMU
482 * This function is called from RCU critical section. It is the common
483 * part of flatview_do_translate and address_space_translate_cached.
485 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
486 hwaddr *xlat,
487 hwaddr *plen_out,
488 hwaddr *page_mask_out,
489 bool is_write,
490 bool is_mmio,
491 AddressSpace **target_as)
493 MemoryRegionSection *section;
494 hwaddr page_mask = (hwaddr)-1;
496 do {
497 hwaddr addr = *xlat;
498 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
499 IOMMUTLBEntry iotlb = imrc->translate(iommu_mr, addr, is_write ?
500 IOMMU_WO : IOMMU_RO);
502 if (!(iotlb.perm & (1 << is_write))) {
503 goto unassigned;
506 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
507 | (addr & iotlb.addr_mask));
508 page_mask &= iotlb.addr_mask;
509 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
510 *target_as = iotlb.target_as;
512 section = address_space_translate_internal(
513 address_space_to_dispatch(iotlb.target_as), addr, xlat,
514 plen_out, is_mmio);
516 iommu_mr = memory_region_get_iommu(section->mr);
517 } while (unlikely(iommu_mr));
519 if (page_mask_out) {
520 *page_mask_out = page_mask;
522 return *section;
524 unassigned:
525 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
529 * flatview_do_translate - translate an address in FlatView
531 * @fv: the flat view that we want to translate on
532 * @addr: the address to be translated in above address space
533 * @xlat: the translated address offset within memory region. It
534 * cannot be @NULL.
535 * @plen_out: valid read/write length of the translated address. It
536 * can be @NULL when we don't care about it.
537 * @page_mask_out: page mask for the translated address. This
538 * should only be meaningful for IOMMU translated
539 * addresses, since there may be huge pages that this bit
540 * would tell. It can be @NULL if we don't care about it.
541 * @is_write: whether the translation operation is for write
542 * @is_mmio: whether this can be MMIO, set true if it can
543 * @target_as: the address space targeted by the IOMMU
544 * @attrs: memory transaction attributes
546 * This function is called from RCU critical section
548 static MemoryRegionSection flatview_do_translate(FlatView *fv,
549 hwaddr addr,
550 hwaddr *xlat,
551 hwaddr *plen_out,
552 hwaddr *page_mask_out,
553 bool is_write,
554 bool is_mmio,
555 AddressSpace **target_as,
556 MemTxAttrs attrs)
558 MemoryRegionSection *section;
559 IOMMUMemoryRegion *iommu_mr;
560 hwaddr plen = (hwaddr)(-1);
562 if (!plen_out) {
563 plen_out = &plen;
566 section = address_space_translate_internal(
567 flatview_to_dispatch(fv), addr, xlat,
568 plen_out, is_mmio);
570 iommu_mr = memory_region_get_iommu(section->mr);
571 if (unlikely(iommu_mr)) {
572 return address_space_translate_iommu(iommu_mr, xlat,
573 plen_out, page_mask_out,
574 is_write, is_mmio,
575 target_as);
577 if (page_mask_out) {
578 /* Not behind an IOMMU, use default page size. */
579 *page_mask_out = ~TARGET_PAGE_MASK;
582 return *section;
585 /* Called from RCU critical section */
586 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
587 bool is_write, MemTxAttrs attrs)
589 MemoryRegionSection section;
590 hwaddr xlat, page_mask;
593 * This can never be MMIO, and we don't really care about plen,
594 * but page mask.
596 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
597 NULL, &page_mask, is_write, false, &as,
598 attrs);
600 /* Illegal translation */
601 if (section.mr == &io_mem_unassigned) {
602 goto iotlb_fail;
605 /* Convert memory region offset into address space offset */
606 xlat += section.offset_within_address_space -
607 section.offset_within_region;
609 return (IOMMUTLBEntry) {
610 .target_as = as,
611 .iova = addr & ~page_mask,
612 .translated_addr = xlat & ~page_mask,
613 .addr_mask = page_mask,
614 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
615 .perm = IOMMU_RW,
618 iotlb_fail:
619 return (IOMMUTLBEntry) {0};
622 /* Called from RCU critical section */
623 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
624 hwaddr *plen, bool is_write,
625 MemTxAttrs attrs)
627 MemoryRegion *mr;
628 MemoryRegionSection section;
629 AddressSpace *as = NULL;
631 /* This can be MMIO, so setup MMIO bit. */
632 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
633 is_write, true, &as, attrs);
634 mr = section.mr;
636 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
637 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
638 *plen = MIN(page, *plen);
641 return mr;
644 /* Called from RCU critical section */
645 MemoryRegionSection *
646 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
647 hwaddr *xlat, hwaddr *plen)
649 MemoryRegionSection *section;
650 AddressSpaceDispatch *d = atomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
652 section = address_space_translate_internal(d, addr, xlat, plen, false);
654 assert(!memory_region_is_iommu(section->mr));
655 return section;
657 #endif
659 #if !defined(CONFIG_USER_ONLY)
661 static int cpu_common_post_load(void *opaque, int version_id)
663 CPUState *cpu = opaque;
665 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
666 version_id is increased. */
667 cpu->interrupt_request &= ~0x01;
668 tlb_flush(cpu);
670 /* loadvm has just updated the content of RAM, bypassing the
671 * usual mechanisms that ensure we flush TBs for writes to
672 * memory we've translated code from. So we must flush all TBs,
673 * which will now be stale.
675 tb_flush(cpu);
677 return 0;
680 static int cpu_common_pre_load(void *opaque)
682 CPUState *cpu = opaque;
684 cpu->exception_index = -1;
686 return 0;
689 static bool cpu_common_exception_index_needed(void *opaque)
691 CPUState *cpu = opaque;
693 return tcg_enabled() && cpu->exception_index != -1;
696 static const VMStateDescription vmstate_cpu_common_exception_index = {
697 .name = "cpu_common/exception_index",
698 .version_id = 1,
699 .minimum_version_id = 1,
700 .needed = cpu_common_exception_index_needed,
701 .fields = (VMStateField[]) {
702 VMSTATE_INT32(exception_index, CPUState),
703 VMSTATE_END_OF_LIST()
707 static bool cpu_common_crash_occurred_needed(void *opaque)
709 CPUState *cpu = opaque;
711 return cpu->crash_occurred;
714 static const VMStateDescription vmstate_cpu_common_crash_occurred = {
715 .name = "cpu_common/crash_occurred",
716 .version_id = 1,
717 .minimum_version_id = 1,
718 .needed = cpu_common_crash_occurred_needed,
719 .fields = (VMStateField[]) {
720 VMSTATE_BOOL(crash_occurred, CPUState),
721 VMSTATE_END_OF_LIST()
725 const VMStateDescription vmstate_cpu_common = {
726 .name = "cpu_common",
727 .version_id = 1,
728 .minimum_version_id = 1,
729 .pre_load = cpu_common_pre_load,
730 .post_load = cpu_common_post_load,
731 .fields = (VMStateField[]) {
732 VMSTATE_UINT32(halted, CPUState),
733 VMSTATE_UINT32(interrupt_request, CPUState),
734 VMSTATE_END_OF_LIST()
736 .subsections = (const VMStateDescription*[]) {
737 &vmstate_cpu_common_exception_index,
738 &vmstate_cpu_common_crash_occurred,
739 NULL
743 #endif
745 CPUState *qemu_get_cpu(int index)
747 CPUState *cpu;
749 CPU_FOREACH(cpu) {
750 if (cpu->cpu_index == index) {
751 return cpu;
755 return NULL;
758 #if !defined(CONFIG_USER_ONLY)
759 void cpu_address_space_init(CPUState *cpu, int asidx,
760 const char *prefix, MemoryRegion *mr)
762 CPUAddressSpace *newas;
763 AddressSpace *as = g_new0(AddressSpace, 1);
764 char *as_name;
766 assert(mr);
767 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
768 address_space_init(as, mr, as_name);
769 g_free(as_name);
771 /* Target code should have set num_ases before calling us */
772 assert(asidx < cpu->num_ases);
774 if (asidx == 0) {
775 /* address space 0 gets the convenience alias */
776 cpu->as = as;
779 /* KVM cannot currently support multiple address spaces. */
780 assert(asidx == 0 || !kvm_enabled());
782 if (!cpu->cpu_ases) {
783 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
786 newas = &cpu->cpu_ases[asidx];
787 newas->cpu = cpu;
788 newas->as = as;
789 if (tcg_enabled()) {
790 newas->tcg_as_listener.commit = tcg_commit;
791 memory_listener_register(&newas->tcg_as_listener, as);
795 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
797 /* Return the AddressSpace corresponding to the specified index */
798 return cpu->cpu_ases[asidx].as;
800 #endif
802 void cpu_exec_unrealizefn(CPUState *cpu)
804 CPUClass *cc = CPU_GET_CLASS(cpu);
806 cpu_list_remove(cpu);
808 if (cc->vmsd != NULL) {
809 vmstate_unregister(NULL, cc->vmsd, cpu);
811 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
812 vmstate_unregister(NULL, &vmstate_cpu_common, cpu);
816 Property cpu_common_props[] = {
817 #ifndef CONFIG_USER_ONLY
818 /* Create a memory property for softmmu CPU object,
819 * so users can wire up its memory. (This can't go in qom/cpu.c
820 * because that file is compiled only once for both user-mode
821 * and system builds.) The default if no link is set up is to use
822 * the system address space.
824 DEFINE_PROP_LINK("memory", CPUState, memory, TYPE_MEMORY_REGION,
825 MemoryRegion *),
826 #endif
827 DEFINE_PROP_END_OF_LIST(),
830 void cpu_exec_initfn(CPUState *cpu)
832 cpu->as = NULL;
833 cpu->num_ases = 0;
835 #ifndef CONFIG_USER_ONLY
836 cpu->thread_id = qemu_get_thread_id();
837 cpu->memory = system_memory;
838 object_ref(OBJECT(cpu->memory));
839 #endif
842 void cpu_exec_realizefn(CPUState *cpu, Error **errp)
844 CPUClass *cc = CPU_GET_CLASS(cpu);
845 static bool tcg_target_initialized;
847 cpu_list_add(cpu);
849 if (tcg_enabled() && !tcg_target_initialized) {
850 tcg_target_initialized = true;
851 cc->tcg_initialize();
854 #ifndef CONFIG_USER_ONLY
855 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
856 vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
858 if (cc->vmsd != NULL) {
859 vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);
861 #endif
864 const char *parse_cpu_model(const char *cpu_model)
866 ObjectClass *oc;
867 CPUClass *cc;
868 gchar **model_pieces;
869 const char *cpu_type;
871 model_pieces = g_strsplit(cpu_model, ",", 2);
873 oc = cpu_class_by_name(CPU_RESOLVING_TYPE, model_pieces[0]);
874 if (oc == NULL) {
875 error_report("unable to find CPU model '%s'", model_pieces[0]);
876 g_strfreev(model_pieces);
877 exit(EXIT_FAILURE);
880 cpu_type = object_class_get_name(oc);
881 cc = CPU_CLASS(oc);
882 cc->parse_features(cpu_type, model_pieces[1], &error_fatal);
883 g_strfreev(model_pieces);
884 return cpu_type;
887 #if defined(CONFIG_USER_ONLY)
888 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
890 mmap_lock();
891 tb_lock();
892 tb_invalidate_phys_page_range(pc, pc + 1, 0);
893 tb_unlock();
894 mmap_unlock();
896 #else
897 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
899 MemTxAttrs attrs;
900 hwaddr phys = cpu_get_phys_page_attrs_debug(cpu, pc, &attrs);
901 int asidx = cpu_asidx_from_attrs(cpu, attrs);
902 if (phys != -1) {
903 /* Locks grabbed by tb_invalidate_phys_addr */
904 tb_invalidate_phys_addr(cpu->cpu_ases[asidx].as,
905 phys | (pc & ~TARGET_PAGE_MASK), attrs);
908 #endif
910 #if defined(CONFIG_USER_ONLY)
911 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
916 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
917 int flags)
919 return -ENOSYS;
922 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
926 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
927 int flags, CPUWatchpoint **watchpoint)
929 return -ENOSYS;
931 #else
932 /* Add a watchpoint. */
933 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
934 int flags, CPUWatchpoint **watchpoint)
936 CPUWatchpoint *wp;
938 /* forbid ranges which are empty or run off the end of the address space */
939 if (len == 0 || (addr + len - 1) < addr) {
940 error_report("tried to set invalid watchpoint at %"
941 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
942 return -EINVAL;
944 wp = g_malloc(sizeof(*wp));
946 wp->vaddr = addr;
947 wp->len = len;
948 wp->flags = flags;
950 /* keep all GDB-injected watchpoints in front */
951 if (flags & BP_GDB) {
952 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
953 } else {
954 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
957 tlb_flush_page(cpu, addr);
959 if (watchpoint)
960 *watchpoint = wp;
961 return 0;
964 /* Remove a specific watchpoint. */
965 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
966 int flags)
968 CPUWatchpoint *wp;
970 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
971 if (addr == wp->vaddr && len == wp->len
972 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
973 cpu_watchpoint_remove_by_ref(cpu, wp);
974 return 0;
977 return -ENOENT;
980 /* Remove a specific watchpoint by reference. */
981 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
983 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
985 tlb_flush_page(cpu, watchpoint->vaddr);
987 g_free(watchpoint);
990 /* Remove all matching watchpoints. */
991 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
993 CPUWatchpoint *wp, *next;
995 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
996 if (wp->flags & mask) {
997 cpu_watchpoint_remove_by_ref(cpu, wp);
1002 /* Return true if this watchpoint address matches the specified
1003 * access (ie the address range covered by the watchpoint overlaps
1004 * partially or completely with the address range covered by the
1005 * access).
1007 static inline bool cpu_watchpoint_address_matches(CPUWatchpoint *wp,
1008 vaddr addr,
1009 vaddr len)
1011 /* We know the lengths are non-zero, but a little caution is
1012 * required to avoid errors in the case where the range ends
1013 * exactly at the top of the address space and so addr + len
1014 * wraps round to zero.
1016 vaddr wpend = wp->vaddr + wp->len - 1;
1017 vaddr addrend = addr + len - 1;
1019 return !(addr > wpend || wp->vaddr > addrend);
1022 #endif
1024 /* Add a breakpoint. */
1025 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
1026 CPUBreakpoint **breakpoint)
1028 CPUBreakpoint *bp;
1030 bp = g_malloc(sizeof(*bp));
1032 bp->pc = pc;
1033 bp->flags = flags;
1035 /* keep all GDB-injected breakpoints in front */
1036 if (flags & BP_GDB) {
1037 QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
1038 } else {
1039 QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
1042 breakpoint_invalidate(cpu, pc);
1044 if (breakpoint) {
1045 *breakpoint = bp;
1047 return 0;
1050 /* Remove a specific breakpoint. */
1051 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
1053 CPUBreakpoint *bp;
1055 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
1056 if (bp->pc == pc && bp->flags == flags) {
1057 cpu_breakpoint_remove_by_ref(cpu, bp);
1058 return 0;
1061 return -ENOENT;
1064 /* Remove a specific breakpoint by reference. */
1065 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
1067 QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);
1069 breakpoint_invalidate(cpu, breakpoint->pc);
1071 g_free(breakpoint);
1074 /* Remove all matching breakpoints. */
1075 void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
1077 CPUBreakpoint *bp, *next;
1079 QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
1080 if (bp->flags & mask) {
1081 cpu_breakpoint_remove_by_ref(cpu, bp);
1086 /* enable or disable single step mode. EXCP_DEBUG is returned by the
1087 CPU loop after each instruction */
1088 void cpu_single_step(CPUState *cpu, int enabled)
1090 if (cpu->singlestep_enabled != enabled) {
1091 cpu->singlestep_enabled = enabled;
1092 if (kvm_enabled()) {
1093 kvm_update_guest_debug(cpu, 0);
1094 } else {
1095 /* must flush all the translated code to avoid inconsistencies */
1096 /* XXX: only flush what is necessary */
1097 tb_flush(cpu);
1102 void cpu_abort(CPUState *cpu, const char *fmt, ...)
1104 va_list ap;
1105 va_list ap2;
1107 va_start(ap, fmt);
1108 va_copy(ap2, ap);
1109 fprintf(stderr, "qemu: fatal: ");
1110 vfprintf(stderr, fmt, ap);
1111 fprintf(stderr, "\n");
1112 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1113 if (qemu_log_separate()) {
1114 qemu_log_lock();
1115 qemu_log("qemu: fatal: ");
1116 qemu_log_vprintf(fmt, ap2);
1117 qemu_log("\n");
1118 log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1119 qemu_log_flush();
1120 qemu_log_unlock();
1121 qemu_log_close();
1123 va_end(ap2);
1124 va_end(ap);
1125 replay_finish();
1126 #if defined(CONFIG_USER_ONLY)
1128 struct sigaction act;
1129 sigfillset(&act.sa_mask);
1130 act.sa_handler = SIG_DFL;
1131 sigaction(SIGABRT, &act, NULL);
1133 #endif
1134 abort();
1137 #if !defined(CONFIG_USER_ONLY)
1138 /* Called from RCU critical section */
1139 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
1141 RAMBlock *block;
1143 block = atomic_rcu_read(&ram_list.mru_block);
1144 if (block && addr - block->offset < block->max_length) {
1145 return block;
1147 RAMBLOCK_FOREACH(block) {
1148 if (addr - block->offset < block->max_length) {
1149 goto found;
1153 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1154 abort();
1156 found:
1157 /* It is safe to write mru_block outside the iothread lock. This
1158 * is what happens:
1160 * mru_block = xxx
1161 * rcu_read_unlock()
1162 * xxx removed from list
1163 * rcu_read_lock()
1164 * read mru_block
1165 * mru_block = NULL;
1166 * call_rcu(reclaim_ramblock, xxx);
1167 * rcu_read_unlock()
1169 * atomic_rcu_set is not needed here. The block was already published
1170 * when it was placed into the list. Here we're just making an extra
1171 * copy of the pointer.
1173 ram_list.mru_block = block;
1174 return block;
1177 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1179 CPUState *cpu;
1180 ram_addr_t start1;
1181 RAMBlock *block;
1182 ram_addr_t end;
1184 end = TARGET_PAGE_ALIGN(start + length);
1185 start &= TARGET_PAGE_MASK;
1187 rcu_read_lock();
1188 block = qemu_get_ram_block(start);
1189 assert(block == qemu_get_ram_block(end - 1));
1190 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1191 CPU_FOREACH(cpu) {
1192 tlb_reset_dirty(cpu, start1, length);
1194 rcu_read_unlock();
1197 /* Note: start and end must be within the same ram block. */
1198 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1199 ram_addr_t length,
1200 unsigned client)
1202 DirtyMemoryBlocks *blocks;
1203 unsigned long end, page;
1204 bool dirty = false;
1206 if (length == 0) {
1207 return false;
1210 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1211 page = start >> TARGET_PAGE_BITS;
1213 rcu_read_lock();
1215 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1217 while (page < end) {
1218 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1219 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1220 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1222 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1223 offset, num);
1224 page += num;
1227 rcu_read_unlock();
1229 if (dirty && tcg_enabled()) {
1230 tlb_reset_dirty_range_all(start, length);
1233 return dirty;
1236 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1237 (ram_addr_t start, ram_addr_t length, unsigned client)
1239 DirtyMemoryBlocks *blocks;
1240 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1241 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1242 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1243 DirtyBitmapSnapshot *snap;
1244 unsigned long page, end, dest;
1246 snap = g_malloc0(sizeof(*snap) +
1247 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1248 snap->start = first;
1249 snap->end = last;
1251 page = first >> TARGET_PAGE_BITS;
1252 end = last >> TARGET_PAGE_BITS;
1253 dest = 0;
1255 rcu_read_lock();
1257 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1259 while (page < end) {
1260 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1261 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1262 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1264 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1265 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1266 offset >>= BITS_PER_LEVEL;
1268 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1269 blocks->blocks[idx] + offset,
1270 num);
1271 page += num;
1272 dest += num >> BITS_PER_LEVEL;
1275 rcu_read_unlock();
1277 if (tcg_enabled()) {
1278 tlb_reset_dirty_range_all(start, length);
1281 return snap;
1284 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1285 ram_addr_t start,
1286 ram_addr_t length)
1288 unsigned long page, end;
1290 assert(start >= snap->start);
1291 assert(start + length <= snap->end);
1293 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1294 page = (start - snap->start) >> TARGET_PAGE_BITS;
1296 while (page < end) {
1297 if (test_bit(page, snap->dirty)) {
1298 return true;
1300 page++;
1302 return false;
1305 /* Called from RCU critical section */
1306 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1307 MemoryRegionSection *section,
1308 target_ulong vaddr,
1309 hwaddr paddr, hwaddr xlat,
1310 int prot,
1311 target_ulong *address)
1313 hwaddr iotlb;
1314 CPUWatchpoint *wp;
1316 if (memory_region_is_ram(section->mr)) {
1317 /* Normal RAM. */
1318 iotlb = memory_region_get_ram_addr(section->mr) + xlat;
1319 if (!section->readonly) {
1320 iotlb |= PHYS_SECTION_NOTDIRTY;
1321 } else {
1322 iotlb |= PHYS_SECTION_ROM;
1324 } else {
1325 AddressSpaceDispatch *d;
1327 d = flatview_to_dispatch(section->fv);
1328 iotlb = section - d->map.sections;
1329 iotlb += xlat;
1332 /* Make accesses to pages with watchpoints go via the
1333 watchpoint trap routines. */
1334 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1335 if (cpu_watchpoint_address_matches(wp, vaddr, TARGET_PAGE_SIZE)) {
1336 /* Avoid trapping reads of pages with a write breakpoint. */
1337 if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
1338 iotlb = PHYS_SECTION_WATCH + paddr;
1339 *address |= TLB_MMIO;
1340 break;
1345 return iotlb;
1347 #endif /* defined(CONFIG_USER_ONLY) */
1349 #if !defined(CONFIG_USER_ONLY)
1351 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
1352 uint16_t section);
1353 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1355 static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
1356 qemu_anon_ram_alloc;
1359 * Set a custom physical guest memory alloator.
1360 * Accelerators with unusual needs may need this. Hopefully, we can
1361 * get rid of it eventually.
1363 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
1365 phys_mem_alloc = alloc;
1368 static uint16_t phys_section_add(PhysPageMap *map,
1369 MemoryRegionSection *section)
1371 /* The physical section number is ORed with a page-aligned
1372 * pointer to produce the iotlb entries. Thus it should
1373 * never overflow into the page-aligned value.
1375 assert(map->sections_nb < TARGET_PAGE_SIZE);
1377 if (map->sections_nb == map->sections_nb_alloc) {
1378 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1379 map->sections = g_renew(MemoryRegionSection, map->sections,
1380 map->sections_nb_alloc);
1382 map->sections[map->sections_nb] = *section;
1383 memory_region_ref(section->mr);
1384 return map->sections_nb++;
1387 static void phys_section_destroy(MemoryRegion *mr)
1389 bool have_sub_page = mr->subpage;
1391 memory_region_unref(mr);
1393 if (have_sub_page) {
1394 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1395 object_unref(OBJECT(&subpage->iomem));
1396 g_free(subpage);
1400 static void phys_sections_free(PhysPageMap *map)
1402 while (map->sections_nb > 0) {
1403 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1404 phys_section_destroy(section->mr);
1406 g_free(map->sections);
1407 g_free(map->nodes);
1410 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1412 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1413 subpage_t *subpage;
1414 hwaddr base = section->offset_within_address_space
1415 & TARGET_PAGE_MASK;
1416 MemoryRegionSection *existing = phys_page_find(d, base);
1417 MemoryRegionSection subsection = {
1418 .offset_within_address_space = base,
1419 .size = int128_make64(TARGET_PAGE_SIZE),
1421 hwaddr start, end;
1423 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1425 if (!(existing->mr->subpage)) {
1426 subpage = subpage_init(fv, base);
1427 subsection.fv = fv;
1428 subsection.mr = &subpage->iomem;
1429 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1430 phys_section_add(&d->map, &subsection));
1431 } else {
1432 subpage = container_of(existing->mr, subpage_t, iomem);
1434 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1435 end = start + int128_get64(section->size) - 1;
1436 subpage_register(subpage, start, end,
1437 phys_section_add(&d->map, section));
1441 static void register_multipage(FlatView *fv,
1442 MemoryRegionSection *section)
1444 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1445 hwaddr start_addr = section->offset_within_address_space;
1446 uint16_t section_index = phys_section_add(&d->map, section);
1447 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1448 TARGET_PAGE_BITS));
1450 assert(num_pages);
1451 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1454 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1456 MemoryRegionSection now = *section, remain = *section;
1457 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1459 if (now.offset_within_address_space & ~TARGET_PAGE_MASK) {
1460 uint64_t left = TARGET_PAGE_ALIGN(now.offset_within_address_space)
1461 - now.offset_within_address_space;
1463 now.size = int128_min(int128_make64(left), now.size);
1464 register_subpage(fv, &now);
1465 } else {
1466 now.size = int128_zero();
1468 while (int128_ne(remain.size, now.size)) {
1469 remain.size = int128_sub(remain.size, now.size);
1470 remain.offset_within_address_space += int128_get64(now.size);
1471 remain.offset_within_region += int128_get64(now.size);
1472 now = remain;
1473 if (int128_lt(remain.size, page_size)) {
1474 register_subpage(fv, &now);
1475 } else if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1476 now.size = page_size;
1477 register_subpage(fv, &now);
1478 } else {
1479 now.size = int128_and(now.size, int128_neg(page_size));
1480 register_multipage(fv, &now);
1485 void qemu_flush_coalesced_mmio_buffer(void)
1487 if (kvm_enabled())
1488 kvm_flush_coalesced_mmio_buffer();
1491 void qemu_mutex_lock_ramlist(void)
1493 qemu_mutex_lock(&ram_list.mutex);
1496 void qemu_mutex_unlock_ramlist(void)
1498 qemu_mutex_unlock(&ram_list.mutex);
1501 void ram_block_dump(Monitor *mon)
1503 RAMBlock *block;
1504 char *psize;
1506 rcu_read_lock();
1507 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1508 "Block Name", "PSize", "Offset", "Used", "Total");
1509 RAMBLOCK_FOREACH(block) {
1510 psize = size_to_str(block->page_size);
1511 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1512 " 0x%016" PRIx64 "\n", block->idstr, psize,
1513 (uint64_t)block->offset,
1514 (uint64_t)block->used_length,
1515 (uint64_t)block->max_length);
1516 g_free(psize);
1518 rcu_read_unlock();
1521 #ifdef __linux__
1523 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1524 * may or may not name the same files / on the same filesystem now as
1525 * when we actually open and map them. Iterate over the file
1526 * descriptors instead, and use qemu_fd_getpagesize().
1528 static int find_max_supported_pagesize(Object *obj, void *opaque)
1530 long *hpsize_min = opaque;
1532 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1533 long hpsize = host_memory_backend_pagesize(MEMORY_BACKEND(obj));
1535 if (hpsize < *hpsize_min) {
1536 *hpsize_min = hpsize;
1540 return 0;
1543 long qemu_getrampagesize(void)
1545 long hpsize = LONG_MAX;
1546 long mainrampagesize;
1547 Object *memdev_root;
1549 mainrampagesize = qemu_mempath_getpagesize(mem_path);
1551 /* it's possible we have memory-backend objects with
1552 * hugepage-backed RAM. these may get mapped into system
1553 * address space via -numa parameters or memory hotplug
1554 * hooks. we want to take these into account, but we
1555 * also want to make sure these supported hugepage
1556 * sizes are applicable across the entire range of memory
1557 * we may boot from, so we take the min across all
1558 * backends, and assume normal pages in cases where a
1559 * backend isn't backed by hugepages.
1561 memdev_root = object_resolve_path("/objects", NULL);
1562 if (memdev_root) {
1563 object_child_foreach(memdev_root, find_max_supported_pagesize, &hpsize);
1565 if (hpsize == LONG_MAX) {
1566 /* No additional memory regions found ==> Report main RAM page size */
1567 return mainrampagesize;
1570 /* If NUMA is disabled or the NUMA nodes are not backed with a
1571 * memory-backend, then there is at least one node using "normal" RAM,
1572 * so if its page size is smaller we have got to report that size instead.
1574 if (hpsize > mainrampagesize &&
1575 (nb_numa_nodes == 0 || numa_info[0].node_memdev == NULL)) {
1576 static bool warned;
1577 if (!warned) {
1578 error_report("Huge page support disabled (n/a for main memory).");
1579 warned = true;
1581 return mainrampagesize;
1584 return hpsize;
1586 #else
1587 long qemu_getrampagesize(void)
1589 return getpagesize();
1591 #endif
1593 #ifdef __linux__
1594 static int64_t get_file_size(int fd)
1596 int64_t size = lseek(fd, 0, SEEK_END);
1597 if (size < 0) {
1598 return -errno;
1600 return size;
1603 static int file_ram_open(const char *path,
1604 const char *region_name,
1605 bool *created,
1606 Error **errp)
1608 char *filename;
1609 char *sanitized_name;
1610 char *c;
1611 int fd = -1;
1613 *created = false;
1614 for (;;) {
1615 fd = open(path, O_RDWR);
1616 if (fd >= 0) {
1617 /* @path names an existing file, use it */
1618 break;
1620 if (errno == ENOENT) {
1621 /* @path names a file that doesn't exist, create it */
1622 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1623 if (fd >= 0) {
1624 *created = true;
1625 break;
1627 } else if (errno == EISDIR) {
1628 /* @path names a directory, create a file there */
1629 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1630 sanitized_name = g_strdup(region_name);
1631 for (c = sanitized_name; *c != '\0'; c++) {
1632 if (*c == '/') {
1633 *c = '_';
1637 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1638 sanitized_name);
1639 g_free(sanitized_name);
1641 fd = mkstemp(filename);
1642 if (fd >= 0) {
1643 unlink(filename);
1644 g_free(filename);
1645 break;
1647 g_free(filename);
1649 if (errno != EEXIST && errno != EINTR) {
1650 error_setg_errno(errp, errno,
1651 "can't open backing store %s for guest RAM",
1652 path);
1653 return -1;
1656 * Try again on EINTR and EEXIST. The latter happens when
1657 * something else creates the file between our two open().
1661 return fd;
1664 static void *file_ram_alloc(RAMBlock *block,
1665 ram_addr_t memory,
1666 int fd,
1667 bool truncate,
1668 Error **errp)
1670 void *area;
1672 block->page_size = qemu_fd_getpagesize(fd);
1673 if (block->mr->align % block->page_size) {
1674 error_setg(errp, "alignment 0x%" PRIx64
1675 " must be multiples of page size 0x%zx",
1676 block->mr->align, block->page_size);
1677 return NULL;
1679 block->mr->align = MAX(block->page_size, block->mr->align);
1680 #if defined(__s390x__)
1681 if (kvm_enabled()) {
1682 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1684 #endif
1686 if (memory < block->page_size) {
1687 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1688 "or larger than page size 0x%zx",
1689 memory, block->page_size);
1690 return NULL;
1693 memory = ROUND_UP(memory, block->page_size);
1696 * ftruncate is not supported by hugetlbfs in older
1697 * hosts, so don't bother bailing out on errors.
1698 * If anything goes wrong with it under other filesystems,
1699 * mmap will fail.
1701 * Do not truncate the non-empty backend file to avoid corrupting
1702 * the existing data in the file. Disabling shrinking is not
1703 * enough. For example, the current vNVDIMM implementation stores
1704 * the guest NVDIMM labels at the end of the backend file. If the
1705 * backend file is later extended, QEMU will not be able to find
1706 * those labels. Therefore, extending the non-empty backend file
1707 * is disabled as well.
1709 if (truncate && ftruncate(fd, memory)) {
1710 perror("ftruncate");
1713 area = qemu_ram_mmap(fd, memory, block->mr->align,
1714 block->flags & RAM_SHARED);
1715 if (area == MAP_FAILED) {
1716 error_setg_errno(errp, errno,
1717 "unable to map backing store for guest RAM");
1718 return NULL;
1721 if (mem_prealloc) {
1722 os_mem_prealloc(fd, area, memory, smp_cpus, errp);
1723 if (errp && *errp) {
1724 qemu_ram_munmap(area, memory);
1725 return NULL;
1729 block->fd = fd;
1730 return area;
1732 #endif
1734 /* Allocate space within the ram_addr_t space that governs the
1735 * dirty bitmaps.
1736 * Called with the ramlist lock held.
1738 static ram_addr_t find_ram_offset(ram_addr_t size)
1740 RAMBlock *block, *next_block;
1741 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1743 assert(size != 0); /* it would hand out same offset multiple times */
1745 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1746 return 0;
1749 RAMBLOCK_FOREACH(block) {
1750 ram_addr_t candidate, next = RAM_ADDR_MAX;
1752 /* Align blocks to start on a 'long' in the bitmap
1753 * which makes the bitmap sync'ing take the fast path.
1755 candidate = block->offset + block->max_length;
1756 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1758 /* Search for the closest following block
1759 * and find the gap.
1761 RAMBLOCK_FOREACH(next_block) {
1762 if (next_block->offset >= candidate) {
1763 next = MIN(next, next_block->offset);
1767 /* If it fits remember our place and remember the size
1768 * of gap, but keep going so that we might find a smaller
1769 * gap to fill so avoiding fragmentation.
1771 if (next - candidate >= size && next - candidate < mingap) {
1772 offset = candidate;
1773 mingap = next - candidate;
1776 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1779 if (offset == RAM_ADDR_MAX) {
1780 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1781 (uint64_t)size);
1782 abort();
1785 trace_find_ram_offset(size, offset);
1787 return offset;
1790 unsigned long last_ram_page(void)
1792 RAMBlock *block;
1793 ram_addr_t last = 0;
1795 rcu_read_lock();
1796 RAMBLOCK_FOREACH(block) {
1797 last = MAX(last, block->offset + block->max_length);
1799 rcu_read_unlock();
1800 return last >> TARGET_PAGE_BITS;
1803 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1805 int ret;
1807 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1808 if (!machine_dump_guest_core(current_machine)) {
1809 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1810 if (ret) {
1811 perror("qemu_madvise");
1812 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1813 "but dump_guest_core=off specified\n");
1818 const char *qemu_ram_get_idstr(RAMBlock *rb)
1820 return rb->idstr;
1823 bool qemu_ram_is_shared(RAMBlock *rb)
1825 return rb->flags & RAM_SHARED;
1828 /* Note: Only set at the start of postcopy */
1829 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1831 return rb->flags & RAM_UF_ZEROPAGE;
1834 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1836 rb->flags |= RAM_UF_ZEROPAGE;
1839 /* Called with iothread lock held. */
1840 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1842 RAMBlock *block;
1844 assert(new_block);
1845 assert(!new_block->idstr[0]);
1847 if (dev) {
1848 char *id = qdev_get_dev_path(dev);
1849 if (id) {
1850 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1851 g_free(id);
1854 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1856 rcu_read_lock();
1857 RAMBLOCK_FOREACH(block) {
1858 if (block != new_block &&
1859 !strcmp(block->idstr, new_block->idstr)) {
1860 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1861 new_block->idstr);
1862 abort();
1865 rcu_read_unlock();
1868 /* Called with iothread lock held. */
1869 void qemu_ram_unset_idstr(RAMBlock *block)
1871 /* FIXME: arch_init.c assumes that this is not called throughout
1872 * migration. Ignore the problem since hot-unplug during migration
1873 * does not work anyway.
1875 if (block) {
1876 memset(block->idstr, 0, sizeof(block->idstr));
1880 size_t qemu_ram_pagesize(RAMBlock *rb)
1882 return rb->page_size;
1885 /* Returns the largest size of page in use */
1886 size_t qemu_ram_pagesize_largest(void)
1888 RAMBlock *block;
1889 size_t largest = 0;
1891 RAMBLOCK_FOREACH(block) {
1892 largest = MAX(largest, qemu_ram_pagesize(block));
1895 return largest;
1898 static int memory_try_enable_merging(void *addr, size_t len)
1900 if (!machine_mem_merge(current_machine)) {
1901 /* disabled by the user */
1902 return 0;
1905 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1908 /* Only legal before guest might have detected the memory size: e.g. on
1909 * incoming migration, or right after reset.
1911 * As memory core doesn't know how is memory accessed, it is up to
1912 * resize callback to update device state and/or add assertions to detect
1913 * misuse, if necessary.
1915 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1917 assert(block);
1919 newsize = HOST_PAGE_ALIGN(newsize);
1921 if (block->used_length == newsize) {
1922 return 0;
1925 if (!(block->flags & RAM_RESIZEABLE)) {
1926 error_setg_errno(errp, EINVAL,
1927 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1928 " in != 0x" RAM_ADDR_FMT, block->idstr,
1929 newsize, block->used_length);
1930 return -EINVAL;
1933 if (block->max_length < newsize) {
1934 error_setg_errno(errp, EINVAL,
1935 "Length too large: %s: 0x" RAM_ADDR_FMT
1936 " > 0x" RAM_ADDR_FMT, block->idstr,
1937 newsize, block->max_length);
1938 return -EINVAL;
1941 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1942 block->used_length = newsize;
1943 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1944 DIRTY_CLIENTS_ALL);
1945 memory_region_set_size(block->mr, newsize);
1946 if (block->resized) {
1947 block->resized(block->idstr, newsize, block->host);
1949 return 0;
1952 /* Called with ram_list.mutex held */
1953 static void dirty_memory_extend(ram_addr_t old_ram_size,
1954 ram_addr_t new_ram_size)
1956 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1957 DIRTY_MEMORY_BLOCK_SIZE);
1958 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1959 DIRTY_MEMORY_BLOCK_SIZE);
1960 int i;
1962 /* Only need to extend if block count increased */
1963 if (new_num_blocks <= old_num_blocks) {
1964 return;
1967 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1968 DirtyMemoryBlocks *old_blocks;
1969 DirtyMemoryBlocks *new_blocks;
1970 int j;
1972 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
1973 new_blocks = g_malloc(sizeof(*new_blocks) +
1974 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1976 if (old_num_blocks) {
1977 memcpy(new_blocks->blocks, old_blocks->blocks,
1978 old_num_blocks * sizeof(old_blocks->blocks[0]));
1981 for (j = old_num_blocks; j < new_num_blocks; j++) {
1982 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1985 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1987 if (old_blocks) {
1988 g_free_rcu(old_blocks, rcu);
1993 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
1995 RAMBlock *block;
1996 RAMBlock *last_block = NULL;
1997 ram_addr_t old_ram_size, new_ram_size;
1998 Error *err = NULL;
2000 old_ram_size = last_ram_page();
2002 qemu_mutex_lock_ramlist();
2003 new_block->offset = find_ram_offset(new_block->max_length);
2005 if (!new_block->host) {
2006 if (xen_enabled()) {
2007 xen_ram_alloc(new_block->offset, new_block->max_length,
2008 new_block->mr, &err);
2009 if (err) {
2010 error_propagate(errp, err);
2011 qemu_mutex_unlock_ramlist();
2012 return;
2014 } else {
2015 new_block->host = phys_mem_alloc(new_block->max_length,
2016 &new_block->mr->align, shared);
2017 if (!new_block->host) {
2018 error_setg_errno(errp, errno,
2019 "cannot set up guest memory '%s'",
2020 memory_region_name(new_block->mr));
2021 qemu_mutex_unlock_ramlist();
2022 return;
2024 memory_try_enable_merging(new_block->host, new_block->max_length);
2028 new_ram_size = MAX(old_ram_size,
2029 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
2030 if (new_ram_size > old_ram_size) {
2031 dirty_memory_extend(old_ram_size, new_ram_size);
2033 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2034 * QLIST (which has an RCU-friendly variant) does not have insertion at
2035 * tail, so save the last element in last_block.
2037 RAMBLOCK_FOREACH(block) {
2038 last_block = block;
2039 if (block->max_length < new_block->max_length) {
2040 break;
2043 if (block) {
2044 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
2045 } else if (last_block) {
2046 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
2047 } else { /* list is empty */
2048 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
2050 ram_list.mru_block = NULL;
2052 /* Write list before version */
2053 smp_wmb();
2054 ram_list.version++;
2055 qemu_mutex_unlock_ramlist();
2057 cpu_physical_memory_set_dirty_range(new_block->offset,
2058 new_block->used_length,
2059 DIRTY_CLIENTS_ALL);
2061 if (new_block->host) {
2062 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2063 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2064 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
2065 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
2066 ram_block_notify_add(new_block->host, new_block->max_length);
2070 #ifdef __linux__
2071 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2072 bool share, int fd,
2073 Error **errp)
2075 RAMBlock *new_block;
2076 Error *local_err = NULL;
2077 int64_t file_size;
2079 if (xen_enabled()) {
2080 error_setg(errp, "-mem-path not supported with Xen");
2081 return NULL;
2084 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2085 error_setg(errp,
2086 "host lacks kvm mmu notifiers, -mem-path unsupported");
2087 return NULL;
2090 if (phys_mem_alloc != qemu_anon_ram_alloc) {
2092 * file_ram_alloc() needs to allocate just like
2093 * phys_mem_alloc, but we haven't bothered to provide
2094 * a hook there.
2096 error_setg(errp,
2097 "-mem-path not supported with this accelerator");
2098 return NULL;
2101 size = HOST_PAGE_ALIGN(size);
2102 file_size = get_file_size(fd);
2103 if (file_size > 0 && file_size < size) {
2104 error_setg(errp, "backing store %s size 0x%" PRIx64
2105 " does not match 'size' option 0x" RAM_ADDR_FMT,
2106 mem_path, file_size, size);
2107 return NULL;
2110 new_block = g_malloc0(sizeof(*new_block));
2111 new_block->mr = mr;
2112 new_block->used_length = size;
2113 new_block->max_length = size;
2114 new_block->flags = share ? RAM_SHARED : 0;
2115 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
2116 if (!new_block->host) {
2117 g_free(new_block);
2118 return NULL;
2121 ram_block_add(new_block, &local_err, share);
2122 if (local_err) {
2123 g_free(new_block);
2124 error_propagate(errp, local_err);
2125 return NULL;
2127 return new_block;
2132 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2133 bool share, const char *mem_path,
2134 Error **errp)
2136 int fd;
2137 bool created;
2138 RAMBlock *block;
2140 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2141 if (fd < 0) {
2142 return NULL;
2145 block = qemu_ram_alloc_from_fd(size, mr, share, fd, errp);
2146 if (!block) {
2147 if (created) {
2148 unlink(mem_path);
2150 close(fd);
2151 return NULL;
2154 return block;
2156 #endif
2158 static
2159 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2160 void (*resized)(const char*,
2161 uint64_t length,
2162 void *host),
2163 void *host, bool resizeable, bool share,
2164 MemoryRegion *mr, Error **errp)
2166 RAMBlock *new_block;
2167 Error *local_err = NULL;
2169 size = HOST_PAGE_ALIGN(size);
2170 max_size = HOST_PAGE_ALIGN(max_size);
2171 new_block = g_malloc0(sizeof(*new_block));
2172 new_block->mr = mr;
2173 new_block->resized = resized;
2174 new_block->used_length = size;
2175 new_block->max_length = max_size;
2176 assert(max_size >= size);
2177 new_block->fd = -1;
2178 new_block->page_size = getpagesize();
2179 new_block->host = host;
2180 if (host) {
2181 new_block->flags |= RAM_PREALLOC;
2183 if (resizeable) {
2184 new_block->flags |= RAM_RESIZEABLE;
2186 ram_block_add(new_block, &local_err, share);
2187 if (local_err) {
2188 g_free(new_block);
2189 error_propagate(errp, local_err);
2190 return NULL;
2192 return new_block;
2195 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2196 MemoryRegion *mr, Error **errp)
2198 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2199 false, mr, errp);
2202 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2203 MemoryRegion *mr, Error **errp)
2205 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2206 share, mr, errp);
2209 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2210 void (*resized)(const char*,
2211 uint64_t length,
2212 void *host),
2213 MemoryRegion *mr, Error **errp)
2215 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2216 false, mr, errp);
2219 static void reclaim_ramblock(RAMBlock *block)
2221 if (block->flags & RAM_PREALLOC) {
2223 } else if (xen_enabled()) {
2224 xen_invalidate_map_cache_entry(block->host);
2225 #ifndef _WIN32
2226 } else if (block->fd >= 0) {
2227 qemu_ram_munmap(block->host, block->max_length);
2228 close(block->fd);
2229 #endif
2230 } else {
2231 qemu_anon_ram_free(block->host, block->max_length);
2233 g_free(block);
2236 void qemu_ram_free(RAMBlock *block)
2238 if (!block) {
2239 return;
2242 if (block->host) {
2243 ram_block_notify_remove(block->host, block->max_length);
2246 qemu_mutex_lock_ramlist();
2247 QLIST_REMOVE_RCU(block, next);
2248 ram_list.mru_block = NULL;
2249 /* Write list before version */
2250 smp_wmb();
2251 ram_list.version++;
2252 call_rcu(block, reclaim_ramblock, rcu);
2253 qemu_mutex_unlock_ramlist();
2256 #ifndef _WIN32
2257 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2259 RAMBlock *block;
2260 ram_addr_t offset;
2261 int flags;
2262 void *area, *vaddr;
2264 RAMBLOCK_FOREACH(block) {
2265 offset = addr - block->offset;
2266 if (offset < block->max_length) {
2267 vaddr = ramblock_ptr(block, offset);
2268 if (block->flags & RAM_PREALLOC) {
2270 } else if (xen_enabled()) {
2271 abort();
2272 } else {
2273 flags = MAP_FIXED;
2274 if (block->fd >= 0) {
2275 flags |= (block->flags & RAM_SHARED ?
2276 MAP_SHARED : MAP_PRIVATE);
2277 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2278 flags, block->fd, offset);
2279 } else {
2281 * Remap needs to match alloc. Accelerators that
2282 * set phys_mem_alloc never remap. If they did,
2283 * we'd need a remap hook here.
2285 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2287 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2288 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2289 flags, -1, 0);
2291 if (area != vaddr) {
2292 error_report("Could not remap addr: "
2293 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2294 length, addr);
2295 exit(1);
2297 memory_try_enable_merging(vaddr, length);
2298 qemu_ram_setup_dump(vaddr, length);
2303 #endif /* !_WIN32 */
2305 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2306 * This should not be used for general purpose DMA. Use address_space_map
2307 * or address_space_rw instead. For local memory (e.g. video ram) that the
2308 * device owns, use memory_region_get_ram_ptr.
2310 * Called within RCU critical section.
2312 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2314 RAMBlock *block = ram_block;
2316 if (block == NULL) {
2317 block = qemu_get_ram_block(addr);
2318 addr -= block->offset;
2321 if (xen_enabled() && block->host == NULL) {
2322 /* We need to check if the requested address is in the RAM
2323 * because we don't want to map the entire memory in QEMU.
2324 * In that case just map until the end of the page.
2326 if (block->offset == 0) {
2327 return xen_map_cache(addr, 0, 0, false);
2330 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2332 return ramblock_ptr(block, addr);
2335 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2336 * but takes a size argument.
2338 * Called within RCU critical section.
2340 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2341 hwaddr *size, bool lock)
2343 RAMBlock *block = ram_block;
2344 if (*size == 0) {
2345 return NULL;
2348 if (block == NULL) {
2349 block = qemu_get_ram_block(addr);
2350 addr -= block->offset;
2352 *size = MIN(*size, block->max_length - addr);
2354 if (xen_enabled() && block->host == NULL) {
2355 /* We need to check if the requested address is in the RAM
2356 * because we don't want to map the entire memory in QEMU.
2357 * In that case just map the requested area.
2359 if (block->offset == 0) {
2360 return xen_map_cache(addr, *size, lock, lock);
2363 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2366 return ramblock_ptr(block, addr);
2369 /* Return the offset of a hostpointer within a ramblock */
2370 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2372 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2373 assert((uintptr_t)host >= (uintptr_t)rb->host);
2374 assert(res < rb->max_length);
2376 return res;
2380 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2381 * in that RAMBlock.
2383 * ptr: Host pointer to look up
2384 * round_offset: If true round the result offset down to a page boundary
2385 * *ram_addr: set to result ram_addr
2386 * *offset: set to result offset within the RAMBlock
2388 * Returns: RAMBlock (or NULL if not found)
2390 * By the time this function returns, the returned pointer is not protected
2391 * by RCU anymore. If the caller is not within an RCU critical section and
2392 * does not hold the iothread lock, it must have other means of protecting the
2393 * pointer, such as a reference to the region that includes the incoming
2394 * ram_addr_t.
2396 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2397 ram_addr_t *offset)
2399 RAMBlock *block;
2400 uint8_t *host = ptr;
2402 if (xen_enabled()) {
2403 ram_addr_t ram_addr;
2404 rcu_read_lock();
2405 ram_addr = xen_ram_addr_from_mapcache(ptr);
2406 block = qemu_get_ram_block(ram_addr);
2407 if (block) {
2408 *offset = ram_addr - block->offset;
2410 rcu_read_unlock();
2411 return block;
2414 rcu_read_lock();
2415 block = atomic_rcu_read(&ram_list.mru_block);
2416 if (block && block->host && host - block->host < block->max_length) {
2417 goto found;
2420 RAMBLOCK_FOREACH(block) {
2421 /* This case append when the block is not mapped. */
2422 if (block->host == NULL) {
2423 continue;
2425 if (host - block->host < block->max_length) {
2426 goto found;
2430 rcu_read_unlock();
2431 return NULL;
2433 found:
2434 *offset = (host - block->host);
2435 if (round_offset) {
2436 *offset &= TARGET_PAGE_MASK;
2438 rcu_read_unlock();
2439 return block;
2443 * Finds the named RAMBlock
2445 * name: The name of RAMBlock to find
2447 * Returns: RAMBlock (or NULL if not found)
2449 RAMBlock *qemu_ram_block_by_name(const char *name)
2451 RAMBlock *block;
2453 RAMBLOCK_FOREACH(block) {
2454 if (!strcmp(name, block->idstr)) {
2455 return block;
2459 return NULL;
2462 /* Some of the softmmu routines need to translate from a host pointer
2463 (typically a TLB entry) back to a ram offset. */
2464 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2466 RAMBlock *block;
2467 ram_addr_t offset;
2469 block = qemu_ram_block_from_host(ptr, false, &offset);
2470 if (!block) {
2471 return RAM_ADDR_INVALID;
2474 return block->offset + offset;
2477 /* Called within RCU critical section. */
2478 void memory_notdirty_write_prepare(NotDirtyInfo *ndi,
2479 CPUState *cpu,
2480 vaddr mem_vaddr,
2481 ram_addr_t ram_addr,
2482 unsigned size)
2484 ndi->cpu = cpu;
2485 ndi->ram_addr = ram_addr;
2486 ndi->mem_vaddr = mem_vaddr;
2487 ndi->size = size;
2488 ndi->locked = false;
2490 assert(tcg_enabled());
2491 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
2492 ndi->locked = true;
2493 tb_lock();
2494 tb_invalidate_phys_page_fast(ram_addr, size);
2498 /* Called within RCU critical section. */
2499 void memory_notdirty_write_complete(NotDirtyInfo *ndi)
2501 if (ndi->locked) {
2502 tb_unlock();
2505 /* Set both VGA and migration bits for simplicity and to remove
2506 * the notdirty callback faster.
2508 cpu_physical_memory_set_dirty_range(ndi->ram_addr, ndi->size,
2509 DIRTY_CLIENTS_NOCODE);
2510 /* we remove the notdirty callback only if the code has been
2511 flushed */
2512 if (!cpu_physical_memory_is_clean(ndi->ram_addr)) {
2513 tlb_set_dirty(ndi->cpu, ndi->mem_vaddr);
2517 /* Called within RCU critical section. */
2518 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2519 uint64_t val, unsigned size)
2521 NotDirtyInfo ndi;
2523 memory_notdirty_write_prepare(&ndi, current_cpu, current_cpu->mem_io_vaddr,
2524 ram_addr, size);
2526 switch (size) {
2527 case 1:
2528 stb_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2529 break;
2530 case 2:
2531 stw_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2532 break;
2533 case 4:
2534 stl_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2535 break;
2536 case 8:
2537 stq_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2538 break;
2539 default:
2540 abort();
2542 memory_notdirty_write_complete(&ndi);
2545 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
2546 unsigned size, bool is_write,
2547 MemTxAttrs attrs)
2549 return is_write;
2552 static const MemoryRegionOps notdirty_mem_ops = {
2553 .write = notdirty_mem_write,
2554 .valid.accepts = notdirty_mem_accepts,
2555 .endianness = DEVICE_NATIVE_ENDIAN,
2556 .valid = {
2557 .min_access_size = 1,
2558 .max_access_size = 8,
2559 .unaligned = false,
2561 .impl = {
2562 .min_access_size = 1,
2563 .max_access_size = 8,
2564 .unaligned = false,
2568 /* Generate a debug exception if a watchpoint has been hit. */
2569 static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
2571 CPUState *cpu = current_cpu;
2572 CPUClass *cc = CPU_GET_CLASS(cpu);
2573 target_ulong vaddr;
2574 CPUWatchpoint *wp;
2576 assert(tcg_enabled());
2577 if (cpu->watchpoint_hit) {
2578 /* We re-entered the check after replacing the TB. Now raise
2579 * the debug interrupt so that is will trigger after the
2580 * current instruction. */
2581 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2582 return;
2584 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
2585 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
2586 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2587 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2588 && (wp->flags & flags)) {
2589 if (flags == BP_MEM_READ) {
2590 wp->flags |= BP_WATCHPOINT_HIT_READ;
2591 } else {
2592 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2594 wp->hitaddr = vaddr;
2595 wp->hitattrs = attrs;
2596 if (!cpu->watchpoint_hit) {
2597 if (wp->flags & BP_CPU &&
2598 !cc->debug_check_watchpoint(cpu, wp)) {
2599 wp->flags &= ~BP_WATCHPOINT_HIT;
2600 continue;
2602 cpu->watchpoint_hit = wp;
2604 /* Both tb_lock and iothread_mutex will be reset when
2605 * cpu_loop_exit or cpu_loop_exit_noexc longjmp
2606 * back into the cpu_exec main loop.
2608 tb_lock();
2609 tb_check_watchpoint(cpu);
2610 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2611 cpu->exception_index = EXCP_DEBUG;
2612 cpu_loop_exit(cpu);
2613 } else {
2614 /* Force execution of one insn next time. */
2615 cpu->cflags_next_tb = 1 | curr_cflags();
2616 cpu_loop_exit_noexc(cpu);
2619 } else {
2620 wp->flags &= ~BP_WATCHPOINT_HIT;
2625 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2626 so these check for a hit then pass through to the normal out-of-line
2627 phys routines. */
2628 static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2629 unsigned size, MemTxAttrs attrs)
2631 MemTxResult res;
2632 uint64_t data;
2633 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2634 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2636 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2637 switch (size) {
2638 case 1:
2639 data = address_space_ldub(as, addr, attrs, &res);
2640 break;
2641 case 2:
2642 data = address_space_lduw(as, addr, attrs, &res);
2643 break;
2644 case 4:
2645 data = address_space_ldl(as, addr, attrs, &res);
2646 break;
2647 case 8:
2648 data = address_space_ldq(as, addr, attrs, &res);
2649 break;
2650 default: abort();
2652 *pdata = data;
2653 return res;
2656 static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2657 uint64_t val, unsigned size,
2658 MemTxAttrs attrs)
2660 MemTxResult res;
2661 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2662 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2664 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2665 switch (size) {
2666 case 1:
2667 address_space_stb(as, addr, val, attrs, &res);
2668 break;
2669 case 2:
2670 address_space_stw(as, addr, val, attrs, &res);
2671 break;
2672 case 4:
2673 address_space_stl(as, addr, val, attrs, &res);
2674 break;
2675 case 8:
2676 address_space_stq(as, addr, val, attrs, &res);
2677 break;
2678 default: abort();
2680 return res;
2683 static const MemoryRegionOps watch_mem_ops = {
2684 .read_with_attrs = watch_mem_read,
2685 .write_with_attrs = watch_mem_write,
2686 .endianness = DEVICE_NATIVE_ENDIAN,
2687 .valid = {
2688 .min_access_size = 1,
2689 .max_access_size = 8,
2690 .unaligned = false,
2692 .impl = {
2693 .min_access_size = 1,
2694 .max_access_size = 8,
2695 .unaligned = false,
2699 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2700 MemTxAttrs attrs, uint8_t *buf, int len);
2701 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2702 const uint8_t *buf, int len);
2703 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
2704 bool is_write, MemTxAttrs attrs);
2706 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2707 unsigned len, MemTxAttrs attrs)
2709 subpage_t *subpage = opaque;
2710 uint8_t buf[8];
2711 MemTxResult res;
2713 #if defined(DEBUG_SUBPAGE)
2714 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2715 subpage, len, addr);
2716 #endif
2717 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2718 if (res) {
2719 return res;
2721 switch (len) {
2722 case 1:
2723 *data = ldub_p(buf);
2724 return MEMTX_OK;
2725 case 2:
2726 *data = lduw_p(buf);
2727 return MEMTX_OK;
2728 case 4:
2729 *data = ldl_p(buf);
2730 return MEMTX_OK;
2731 case 8:
2732 *data = ldq_p(buf);
2733 return MEMTX_OK;
2734 default:
2735 abort();
2739 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2740 uint64_t value, unsigned len, MemTxAttrs attrs)
2742 subpage_t *subpage = opaque;
2743 uint8_t buf[8];
2745 #if defined(DEBUG_SUBPAGE)
2746 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2747 " value %"PRIx64"\n",
2748 __func__, subpage, len, addr, value);
2749 #endif
2750 switch (len) {
2751 case 1:
2752 stb_p(buf, value);
2753 break;
2754 case 2:
2755 stw_p(buf, value);
2756 break;
2757 case 4:
2758 stl_p(buf, value);
2759 break;
2760 case 8:
2761 stq_p(buf, value);
2762 break;
2763 default:
2764 abort();
2766 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2769 static bool subpage_accepts(void *opaque, hwaddr addr,
2770 unsigned len, bool is_write,
2771 MemTxAttrs attrs)
2773 subpage_t *subpage = opaque;
2774 #if defined(DEBUG_SUBPAGE)
2775 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2776 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2777 #endif
2779 return flatview_access_valid(subpage->fv, addr + subpage->base,
2780 len, is_write, attrs);
2783 static const MemoryRegionOps subpage_ops = {
2784 .read_with_attrs = subpage_read,
2785 .write_with_attrs = subpage_write,
2786 .impl.min_access_size = 1,
2787 .impl.max_access_size = 8,
2788 .valid.min_access_size = 1,
2789 .valid.max_access_size = 8,
2790 .valid.accepts = subpage_accepts,
2791 .endianness = DEVICE_NATIVE_ENDIAN,
2794 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
2795 uint16_t section)
2797 int idx, eidx;
2799 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2800 return -1;
2801 idx = SUBPAGE_IDX(start);
2802 eidx = SUBPAGE_IDX(end);
2803 #if defined(DEBUG_SUBPAGE)
2804 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2805 __func__, mmio, start, end, idx, eidx, section);
2806 #endif
2807 for (; idx <= eidx; idx++) {
2808 mmio->sub_section[idx] = section;
2811 return 0;
2814 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2816 subpage_t *mmio;
2818 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2819 mmio->fv = fv;
2820 mmio->base = base;
2821 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2822 NULL, TARGET_PAGE_SIZE);
2823 mmio->iomem.subpage = true;
2824 #if defined(DEBUG_SUBPAGE)
2825 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2826 mmio, base, TARGET_PAGE_SIZE);
2827 #endif
2828 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
2830 return mmio;
2833 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2835 assert(fv);
2836 MemoryRegionSection section = {
2837 .fv = fv,
2838 .mr = mr,
2839 .offset_within_address_space = 0,
2840 .offset_within_region = 0,
2841 .size = int128_2_64(),
2844 return phys_section_add(map, &section);
2847 static void readonly_mem_write(void *opaque, hwaddr addr,
2848 uint64_t val, unsigned size)
2850 /* Ignore any write to ROM. */
2853 static bool readonly_mem_accepts(void *opaque, hwaddr addr,
2854 unsigned size, bool is_write,
2855 MemTxAttrs attrs)
2857 return is_write;
2860 /* This will only be used for writes, because reads are special cased
2861 * to directly access the underlying host ram.
2863 static const MemoryRegionOps readonly_mem_ops = {
2864 .write = readonly_mem_write,
2865 .valid.accepts = readonly_mem_accepts,
2866 .endianness = DEVICE_NATIVE_ENDIAN,
2867 .valid = {
2868 .min_access_size = 1,
2869 .max_access_size = 8,
2870 .unaligned = false,
2872 .impl = {
2873 .min_access_size = 1,
2874 .max_access_size = 8,
2875 .unaligned = false,
2879 MemoryRegion *iotlb_to_region(CPUState *cpu, hwaddr index, MemTxAttrs attrs)
2881 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2882 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2883 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
2884 MemoryRegionSection *sections = d->map.sections;
2886 return sections[index & ~TARGET_PAGE_MASK].mr;
2889 static void io_mem_init(void)
2891 memory_region_init_io(&io_mem_rom, NULL, &readonly_mem_ops,
2892 NULL, NULL, UINT64_MAX);
2893 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2894 NULL, UINT64_MAX);
2896 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
2897 * which can be called without the iothread mutex.
2899 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
2900 NULL, UINT64_MAX);
2901 memory_region_clear_global_locking(&io_mem_notdirty);
2903 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
2904 NULL, UINT64_MAX);
2907 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2909 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2910 uint16_t n;
2912 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2913 assert(n == PHYS_SECTION_UNASSIGNED);
2914 n = dummy_section(&d->map, fv, &io_mem_notdirty);
2915 assert(n == PHYS_SECTION_NOTDIRTY);
2916 n = dummy_section(&d->map, fv, &io_mem_rom);
2917 assert(n == PHYS_SECTION_ROM);
2918 n = dummy_section(&d->map, fv, &io_mem_watch);
2919 assert(n == PHYS_SECTION_WATCH);
2921 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2923 return d;
2926 void address_space_dispatch_free(AddressSpaceDispatch *d)
2928 phys_sections_free(&d->map);
2929 g_free(d);
2932 static void tcg_commit(MemoryListener *listener)
2934 CPUAddressSpace *cpuas;
2935 AddressSpaceDispatch *d;
2937 /* since each CPU stores ram addresses in its TLB cache, we must
2938 reset the modified entries */
2939 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2940 cpu_reloading_memory_map();
2941 /* The CPU and TLB are protected by the iothread lock.
2942 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2943 * may have split the RCU critical section.
2945 d = address_space_to_dispatch(cpuas->as);
2946 atomic_rcu_set(&cpuas->memory_dispatch, d);
2947 tlb_flush(cpuas->cpu);
2950 static void memory_map_init(void)
2952 system_memory = g_malloc(sizeof(*system_memory));
2954 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2955 address_space_init(&address_space_memory, system_memory, "memory");
2957 system_io = g_malloc(sizeof(*system_io));
2958 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2959 65536);
2960 address_space_init(&address_space_io, system_io, "I/O");
2963 MemoryRegion *get_system_memory(void)
2965 return system_memory;
2968 MemoryRegion *get_system_io(void)
2970 return system_io;
2973 #endif /* !defined(CONFIG_USER_ONLY) */
2975 /* physical memory access (slow version, mainly for debug) */
2976 #if defined(CONFIG_USER_ONLY)
2977 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
2978 uint8_t *buf, int len, int is_write)
2980 int l, flags;
2981 target_ulong page;
2982 void * p;
2984 while (len > 0) {
2985 page = addr & TARGET_PAGE_MASK;
2986 l = (page + TARGET_PAGE_SIZE) - addr;
2987 if (l > len)
2988 l = len;
2989 flags = page_get_flags(page);
2990 if (!(flags & PAGE_VALID))
2991 return -1;
2992 if (is_write) {
2993 if (!(flags & PAGE_WRITE))
2994 return -1;
2995 /* XXX: this code should not depend on lock_user */
2996 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
2997 return -1;
2998 memcpy(p, buf, l);
2999 unlock_user(p, addr, l);
3000 } else {
3001 if (!(flags & PAGE_READ))
3002 return -1;
3003 /* XXX: this code should not depend on lock_user */
3004 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
3005 return -1;
3006 memcpy(buf, p, l);
3007 unlock_user(p, addr, 0);
3009 len -= l;
3010 buf += l;
3011 addr += l;
3013 return 0;
3016 #else
3018 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
3019 hwaddr length)
3021 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
3022 addr += memory_region_get_ram_addr(mr);
3024 /* No early return if dirty_log_mask is or becomes 0, because
3025 * cpu_physical_memory_set_dirty_range will still call
3026 * xen_modified_memory.
3028 if (dirty_log_mask) {
3029 dirty_log_mask =
3030 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
3032 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
3033 assert(tcg_enabled());
3034 tb_lock();
3035 tb_invalidate_phys_range(addr, addr + length);
3036 tb_unlock();
3037 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
3039 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
3042 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
3044 unsigned access_size_max = mr->ops->valid.max_access_size;
3046 /* Regions are assumed to support 1-4 byte accesses unless
3047 otherwise specified. */
3048 if (access_size_max == 0) {
3049 access_size_max = 4;
3052 /* Bound the maximum access by the alignment of the address. */
3053 if (!mr->ops->impl.unaligned) {
3054 unsigned align_size_max = addr & -addr;
3055 if (align_size_max != 0 && align_size_max < access_size_max) {
3056 access_size_max = align_size_max;
3060 /* Don't attempt accesses larger than the maximum. */
3061 if (l > access_size_max) {
3062 l = access_size_max;
3064 l = pow2floor(l);
3066 return l;
3069 static bool prepare_mmio_access(MemoryRegion *mr)
3071 bool unlocked = !qemu_mutex_iothread_locked();
3072 bool release_lock = false;
3074 if (unlocked && mr->global_locking) {
3075 qemu_mutex_lock_iothread();
3076 unlocked = false;
3077 release_lock = true;
3079 if (mr->flush_coalesced_mmio) {
3080 if (unlocked) {
3081 qemu_mutex_lock_iothread();
3083 qemu_flush_coalesced_mmio_buffer();
3084 if (unlocked) {
3085 qemu_mutex_unlock_iothread();
3089 return release_lock;
3092 /* Called within RCU critical section. */
3093 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
3094 MemTxAttrs attrs,
3095 const uint8_t *buf,
3096 int len, hwaddr addr1,
3097 hwaddr l, MemoryRegion *mr)
3099 uint8_t *ptr;
3100 uint64_t val;
3101 MemTxResult result = MEMTX_OK;
3102 bool release_lock = false;
3104 for (;;) {
3105 if (!memory_access_is_direct(mr, true)) {
3106 release_lock |= prepare_mmio_access(mr);
3107 l = memory_access_size(mr, l, addr1);
3108 /* XXX: could force current_cpu to NULL to avoid
3109 potential bugs */
3110 switch (l) {
3111 case 8:
3112 /* 64 bit write access */
3113 val = ldq_p(buf);
3114 result |= memory_region_dispatch_write(mr, addr1, val, 8,
3115 attrs);
3116 break;
3117 case 4:
3118 /* 32 bit write access */
3119 val = (uint32_t)ldl_p(buf);
3120 result |= memory_region_dispatch_write(mr, addr1, val, 4,
3121 attrs);
3122 break;
3123 case 2:
3124 /* 16 bit write access */
3125 val = lduw_p(buf);
3126 result |= memory_region_dispatch_write(mr, addr1, val, 2,
3127 attrs);
3128 break;
3129 case 1:
3130 /* 8 bit write access */
3131 val = ldub_p(buf);
3132 result |= memory_region_dispatch_write(mr, addr1, val, 1,
3133 attrs);
3134 break;
3135 default:
3136 abort();
3138 } else {
3139 /* RAM case */
3140 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3141 memcpy(ptr, buf, l);
3142 invalidate_and_set_dirty(mr, addr1, l);
3145 if (release_lock) {
3146 qemu_mutex_unlock_iothread();
3147 release_lock = false;
3150 len -= l;
3151 buf += l;
3152 addr += l;
3154 if (!len) {
3155 break;
3158 l = len;
3159 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
3162 return result;
3165 /* Called from RCU critical section. */
3166 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
3167 const uint8_t *buf, int len)
3169 hwaddr l;
3170 hwaddr addr1;
3171 MemoryRegion *mr;
3172 MemTxResult result = MEMTX_OK;
3174 l = len;
3175 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
3176 result = flatview_write_continue(fv, addr, attrs, buf, len,
3177 addr1, l, mr);
3179 return result;
3182 /* Called within RCU critical section. */
3183 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
3184 MemTxAttrs attrs, uint8_t *buf,
3185 int len, hwaddr addr1, hwaddr l,
3186 MemoryRegion *mr)
3188 uint8_t *ptr;
3189 uint64_t val;
3190 MemTxResult result = MEMTX_OK;
3191 bool release_lock = false;
3193 for (;;) {
3194 if (!memory_access_is_direct(mr, false)) {
3195 /* I/O case */
3196 release_lock |= prepare_mmio_access(mr);
3197 l = memory_access_size(mr, l, addr1);
3198 switch (l) {
3199 case 8:
3200 /* 64 bit read access */
3201 result |= memory_region_dispatch_read(mr, addr1, &val, 8,
3202 attrs);
3203 stq_p(buf, val);
3204 break;
3205 case 4:
3206 /* 32 bit read access */
3207 result |= memory_region_dispatch_read(mr, addr1, &val, 4,
3208 attrs);
3209 stl_p(buf, val);
3210 break;
3211 case 2:
3212 /* 16 bit read access */
3213 result |= memory_region_dispatch_read(mr, addr1, &val, 2,
3214 attrs);
3215 stw_p(buf, val);
3216 break;
3217 case 1:
3218 /* 8 bit read access */
3219 result |= memory_region_dispatch_read(mr, addr1, &val, 1,
3220 attrs);
3221 stb_p(buf, val);
3222 break;
3223 default:
3224 abort();
3226 } else {
3227 /* RAM case */
3228 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3229 memcpy(buf, ptr, l);
3232 if (release_lock) {
3233 qemu_mutex_unlock_iothread();
3234 release_lock = false;
3237 len -= l;
3238 buf += l;
3239 addr += l;
3241 if (!len) {
3242 break;
3245 l = len;
3246 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3249 return result;
3252 /* Called from RCU critical section. */
3253 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
3254 MemTxAttrs attrs, uint8_t *buf, int len)
3256 hwaddr l;
3257 hwaddr addr1;
3258 MemoryRegion *mr;
3260 l = len;
3261 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3262 return flatview_read_continue(fv, addr, attrs, buf, len,
3263 addr1, l, mr);
3266 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3267 MemTxAttrs attrs, uint8_t *buf, int len)
3269 MemTxResult result = MEMTX_OK;
3270 FlatView *fv;
3272 if (len > 0) {
3273 rcu_read_lock();
3274 fv = address_space_to_flatview(as);
3275 result = flatview_read(fv, addr, attrs, buf, len);
3276 rcu_read_unlock();
3279 return result;
3282 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
3283 MemTxAttrs attrs,
3284 const uint8_t *buf, int len)
3286 MemTxResult result = MEMTX_OK;
3287 FlatView *fv;
3289 if (len > 0) {
3290 rcu_read_lock();
3291 fv = address_space_to_flatview(as);
3292 result = flatview_write(fv, addr, attrs, buf, len);
3293 rcu_read_unlock();
3296 return result;
3299 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3300 uint8_t *buf, int len, bool is_write)
3302 if (is_write) {
3303 return address_space_write(as, addr, attrs, buf, len);
3304 } else {
3305 return address_space_read_full(as, addr, attrs, buf, len);
3309 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
3310 int len, int is_write)
3312 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3313 buf, len, is_write);
3316 enum write_rom_type {
3317 WRITE_DATA,
3318 FLUSH_CACHE,
3321 static inline void cpu_physical_memory_write_rom_internal(AddressSpace *as,
3322 hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
3324 hwaddr l;
3325 uint8_t *ptr;
3326 hwaddr addr1;
3327 MemoryRegion *mr;
3329 rcu_read_lock();
3330 while (len > 0) {
3331 l = len;
3332 mr = address_space_translate(as, addr, &addr1, &l, true,
3333 MEMTXATTRS_UNSPECIFIED);
3335 if (!(memory_region_is_ram(mr) ||
3336 memory_region_is_romd(mr))) {
3337 l = memory_access_size(mr, l, addr1);
3338 } else {
3339 /* ROM/RAM case */
3340 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3341 switch (type) {
3342 case WRITE_DATA:
3343 memcpy(ptr, buf, l);
3344 invalidate_and_set_dirty(mr, addr1, l);
3345 break;
3346 case FLUSH_CACHE:
3347 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
3348 break;
3351 len -= l;
3352 buf += l;
3353 addr += l;
3355 rcu_read_unlock();
3358 /* used for ROM loading : can write in RAM and ROM */
3359 void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
3360 const uint8_t *buf, int len)
3362 cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
3365 void cpu_flush_icache_range(hwaddr start, int len)
3368 * This function should do the same thing as an icache flush that was
3369 * triggered from within the guest. For TCG we are always cache coherent,
3370 * so there is no need to flush anything. For KVM / Xen we need to flush
3371 * the host's instruction cache at least.
3373 if (tcg_enabled()) {
3374 return;
3377 cpu_physical_memory_write_rom_internal(&address_space_memory,
3378 start, NULL, len, FLUSH_CACHE);
3381 typedef struct {
3382 MemoryRegion *mr;
3383 void *buffer;
3384 hwaddr addr;
3385 hwaddr len;
3386 bool in_use;
3387 } BounceBuffer;
3389 static BounceBuffer bounce;
3391 typedef struct MapClient {
3392 QEMUBH *bh;
3393 QLIST_ENTRY(MapClient) link;
3394 } MapClient;
3396 QemuMutex map_client_list_lock;
3397 static QLIST_HEAD(map_client_list, MapClient) map_client_list
3398 = QLIST_HEAD_INITIALIZER(map_client_list);
3400 static void cpu_unregister_map_client_do(MapClient *client)
3402 QLIST_REMOVE(client, link);
3403 g_free(client);
3406 static void cpu_notify_map_clients_locked(void)
3408 MapClient *client;
3410 while (!QLIST_EMPTY(&map_client_list)) {
3411 client = QLIST_FIRST(&map_client_list);
3412 qemu_bh_schedule(client->bh);
3413 cpu_unregister_map_client_do(client);
3417 void cpu_register_map_client(QEMUBH *bh)
3419 MapClient *client = g_malloc(sizeof(*client));
3421 qemu_mutex_lock(&map_client_list_lock);
3422 client->bh = bh;
3423 QLIST_INSERT_HEAD(&map_client_list, client, link);
3424 if (!atomic_read(&bounce.in_use)) {
3425 cpu_notify_map_clients_locked();
3427 qemu_mutex_unlock(&map_client_list_lock);
3430 void cpu_exec_init_all(void)
3432 qemu_mutex_init(&ram_list.mutex);
3433 /* The data structures we set up here depend on knowing the page size,
3434 * so no more changes can be made after this point.
3435 * In an ideal world, nothing we did before we had finished the
3436 * machine setup would care about the target page size, and we could
3437 * do this much later, rather than requiring board models to state
3438 * up front what their requirements are.
3440 finalize_target_page_bits();
3441 io_mem_init();
3442 memory_map_init();
3443 qemu_mutex_init(&map_client_list_lock);
3446 void cpu_unregister_map_client(QEMUBH *bh)
3448 MapClient *client;
3450 qemu_mutex_lock(&map_client_list_lock);
3451 QLIST_FOREACH(client, &map_client_list, link) {
3452 if (client->bh == bh) {
3453 cpu_unregister_map_client_do(client);
3454 break;
3457 qemu_mutex_unlock(&map_client_list_lock);
3460 static void cpu_notify_map_clients(void)
3462 qemu_mutex_lock(&map_client_list_lock);
3463 cpu_notify_map_clients_locked();
3464 qemu_mutex_unlock(&map_client_list_lock);
3467 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
3468 bool is_write, MemTxAttrs attrs)
3470 MemoryRegion *mr;
3471 hwaddr l, xlat;
3473 while (len > 0) {
3474 l = len;
3475 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3476 if (!memory_access_is_direct(mr, is_write)) {
3477 l = memory_access_size(mr, l, addr);
3478 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3479 return false;
3483 len -= l;
3484 addr += l;
3486 return true;
3489 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3490 int len, bool is_write,
3491 MemTxAttrs attrs)
3493 FlatView *fv;
3494 bool result;
3496 rcu_read_lock();
3497 fv = address_space_to_flatview(as);
3498 result = flatview_access_valid(fv, addr, len, is_write, attrs);
3499 rcu_read_unlock();
3500 return result;
3503 static hwaddr
3504 flatview_extend_translation(FlatView *fv, hwaddr addr,
3505 hwaddr target_len,
3506 MemoryRegion *mr, hwaddr base, hwaddr len,
3507 bool is_write, MemTxAttrs attrs)
3509 hwaddr done = 0;
3510 hwaddr xlat;
3511 MemoryRegion *this_mr;
3513 for (;;) {
3514 target_len -= len;
3515 addr += len;
3516 done += len;
3517 if (target_len == 0) {
3518 return done;
3521 len = target_len;
3522 this_mr = flatview_translate(fv, addr, &xlat,
3523 &len, is_write, attrs);
3524 if (this_mr != mr || xlat != base + done) {
3525 return done;
3530 /* Map a physical memory region into a host virtual address.
3531 * May map a subset of the requested range, given by and returned in *plen.
3532 * May return NULL if resources needed to perform the mapping are exhausted.
3533 * Use only for reads OR writes - not for read-modify-write operations.
3534 * Use cpu_register_map_client() to know when retrying the map operation is
3535 * likely to succeed.
3537 void *address_space_map(AddressSpace *as,
3538 hwaddr addr,
3539 hwaddr *plen,
3540 bool is_write,
3541 MemTxAttrs attrs)
3543 hwaddr len = *plen;
3544 hwaddr l, xlat;
3545 MemoryRegion *mr;
3546 void *ptr;
3547 FlatView *fv;
3549 if (len == 0) {
3550 return NULL;
3553 l = len;
3554 rcu_read_lock();
3555 fv = address_space_to_flatview(as);
3556 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3558 if (!memory_access_is_direct(mr, is_write)) {
3559 if (atomic_xchg(&bounce.in_use, true)) {
3560 rcu_read_unlock();
3561 return NULL;
3563 /* Avoid unbounded allocations */
3564 l = MIN(l, TARGET_PAGE_SIZE);
3565 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3566 bounce.addr = addr;
3567 bounce.len = l;
3569 memory_region_ref(mr);
3570 bounce.mr = mr;
3571 if (!is_write) {
3572 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3573 bounce.buffer, l);
3576 rcu_read_unlock();
3577 *plen = l;
3578 return bounce.buffer;
3582 memory_region_ref(mr);
3583 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3584 l, is_write, attrs);
3585 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3586 rcu_read_unlock();
3588 return ptr;
3591 /* Unmaps a memory region previously mapped by address_space_map().
3592 * Will also mark the memory as dirty if is_write == 1. access_len gives
3593 * the amount of memory that was actually read or written by the caller.
3595 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3596 int is_write, hwaddr access_len)
3598 if (buffer != bounce.buffer) {
3599 MemoryRegion *mr;
3600 ram_addr_t addr1;
3602 mr = memory_region_from_host(buffer, &addr1);
3603 assert(mr != NULL);
3604 if (is_write) {
3605 invalidate_and_set_dirty(mr, addr1, access_len);
3607 if (xen_enabled()) {
3608 xen_invalidate_map_cache_entry(buffer);
3610 memory_region_unref(mr);
3611 return;
3613 if (is_write) {
3614 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3615 bounce.buffer, access_len);
3617 qemu_vfree(bounce.buffer);
3618 bounce.buffer = NULL;
3619 memory_region_unref(bounce.mr);
3620 atomic_mb_set(&bounce.in_use, false);
3621 cpu_notify_map_clients();
3624 void *cpu_physical_memory_map(hwaddr addr,
3625 hwaddr *plen,
3626 int is_write)
3628 return address_space_map(&address_space_memory, addr, plen, is_write,
3629 MEMTXATTRS_UNSPECIFIED);
3632 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3633 int is_write, hwaddr access_len)
3635 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3638 #define ARG1_DECL AddressSpace *as
3639 #define ARG1 as
3640 #define SUFFIX
3641 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3642 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3643 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3644 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3645 #define RCU_READ_LOCK(...) rcu_read_lock()
3646 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3647 #include "memory_ldst.inc.c"
3649 int64_t address_space_cache_init(MemoryRegionCache *cache,
3650 AddressSpace *as,
3651 hwaddr addr,
3652 hwaddr len,
3653 bool is_write)
3655 AddressSpaceDispatch *d;
3656 hwaddr l;
3657 MemoryRegion *mr;
3659 assert(len > 0);
3661 l = len;
3662 cache->fv = address_space_get_flatview(as);
3663 d = flatview_to_dispatch(cache->fv);
3664 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3666 mr = cache->mrs.mr;
3667 memory_region_ref(mr);
3668 if (memory_access_is_direct(mr, is_write)) {
3669 /* We don't care about the memory attributes here as we're only
3670 * doing this if we found actual RAM, which behaves the same
3671 * regardless of attributes; so UNSPECIFIED is fine.
3673 l = flatview_extend_translation(cache->fv, addr, len, mr,
3674 cache->xlat, l, is_write,
3675 MEMTXATTRS_UNSPECIFIED);
3676 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3677 } else {
3678 cache->ptr = NULL;
3681 cache->len = l;
3682 cache->is_write = is_write;
3683 return l;
3686 void address_space_cache_invalidate(MemoryRegionCache *cache,
3687 hwaddr addr,
3688 hwaddr access_len)
3690 assert(cache->is_write);
3691 if (likely(cache->ptr)) {
3692 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3696 void address_space_cache_destroy(MemoryRegionCache *cache)
3698 if (!cache->mrs.mr) {
3699 return;
3702 if (xen_enabled()) {
3703 xen_invalidate_map_cache_entry(cache->ptr);
3705 memory_region_unref(cache->mrs.mr);
3706 flatview_unref(cache->fv);
3707 cache->mrs.mr = NULL;
3708 cache->fv = NULL;
3711 /* Called from RCU critical section. This function has the same
3712 * semantics as address_space_translate, but it only works on a
3713 * predefined range of a MemoryRegion that was mapped with
3714 * address_space_cache_init.
3716 static inline MemoryRegion *address_space_translate_cached(
3717 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3718 hwaddr *plen, bool is_write, MemTxAttrs attrs)
3720 MemoryRegionSection section;
3721 MemoryRegion *mr;
3722 IOMMUMemoryRegion *iommu_mr;
3723 AddressSpace *target_as;
3725 assert(!cache->ptr);
3726 *xlat = addr + cache->xlat;
3728 mr = cache->mrs.mr;
3729 iommu_mr = memory_region_get_iommu(mr);
3730 if (!iommu_mr) {
3731 /* MMIO region. */
3732 return mr;
3735 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3736 NULL, is_write, true,
3737 &target_as);
3738 return section.mr;
3741 /* Called from RCU critical section. address_space_read_cached uses this
3742 * out of line function when the target is an MMIO or IOMMU region.
3744 void
3745 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3746 void *buf, int len)
3748 hwaddr addr1, l;
3749 MemoryRegion *mr;
3751 l = len;
3752 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3753 MEMTXATTRS_UNSPECIFIED);
3754 flatview_read_continue(cache->fv,
3755 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3756 addr1, l, mr);
3759 /* Called from RCU critical section. address_space_write_cached uses this
3760 * out of line function when the target is an MMIO or IOMMU region.
3762 void
3763 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3764 const void *buf, int len)
3766 hwaddr addr1, l;
3767 MemoryRegion *mr;
3769 l = len;
3770 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3771 MEMTXATTRS_UNSPECIFIED);
3772 flatview_write_continue(cache->fv,
3773 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3774 addr1, l, mr);
3777 #define ARG1_DECL MemoryRegionCache *cache
3778 #define ARG1 cache
3779 #define SUFFIX _cached_slow
3780 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3781 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3782 #define MAP_RAM(mr, ofs) (cache->ptr + (ofs - cache->xlat))
3783 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3784 #define RCU_READ_LOCK() ((void)0)
3785 #define RCU_READ_UNLOCK() ((void)0)
3786 #include "memory_ldst.inc.c"
3788 /* virtual memory access for debug (includes writing to ROM) */
3789 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3790 uint8_t *buf, int len, int is_write)
3792 int l;
3793 hwaddr phys_addr;
3794 target_ulong page;
3796 cpu_synchronize_state(cpu);
3797 while (len > 0) {
3798 int asidx;
3799 MemTxAttrs attrs;
3801 page = addr & TARGET_PAGE_MASK;
3802 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3803 asidx = cpu_asidx_from_attrs(cpu, attrs);
3804 /* if no physical page mapped, return an error */
3805 if (phys_addr == -1)
3806 return -1;
3807 l = (page + TARGET_PAGE_SIZE) - addr;
3808 if (l > len)
3809 l = len;
3810 phys_addr += (addr & ~TARGET_PAGE_MASK);
3811 if (is_write) {
3812 cpu_physical_memory_write_rom(cpu->cpu_ases[asidx].as,
3813 phys_addr, buf, l);
3814 } else {
3815 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3816 MEMTXATTRS_UNSPECIFIED,
3817 buf, l, 0);
3819 len -= l;
3820 buf += l;
3821 addr += l;
3823 return 0;
3827 * Allows code that needs to deal with migration bitmaps etc to still be built
3828 * target independent.
3830 size_t qemu_target_page_size(void)
3832 return TARGET_PAGE_SIZE;
3835 int qemu_target_page_bits(void)
3837 return TARGET_PAGE_BITS;
3840 int qemu_target_page_bits_min(void)
3842 return TARGET_PAGE_BITS_MIN;
3844 #endif
3847 * A helper function for the _utterly broken_ virtio device model to find out if
3848 * it's running on a big endian machine. Don't do this at home kids!
3850 bool target_words_bigendian(void);
3851 bool target_words_bigendian(void)
3853 #if defined(TARGET_WORDS_BIGENDIAN)
3854 return true;
3855 #else
3856 return false;
3857 #endif
3860 #ifndef CONFIG_USER_ONLY
3861 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3863 MemoryRegion*mr;
3864 hwaddr l = 1;
3865 bool res;
3867 rcu_read_lock();
3868 mr = address_space_translate(&address_space_memory,
3869 phys_addr, &phys_addr, &l, false,
3870 MEMTXATTRS_UNSPECIFIED);
3872 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3873 rcu_read_unlock();
3874 return res;
3877 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3879 RAMBlock *block;
3880 int ret = 0;
3882 rcu_read_lock();
3883 RAMBLOCK_FOREACH(block) {
3884 ret = func(block->idstr, block->host, block->offset,
3885 block->used_length, opaque);
3886 if (ret) {
3887 break;
3890 rcu_read_unlock();
3891 return ret;
3895 * Unmap pages of memory from start to start+length such that
3896 * they a) read as 0, b) Trigger whatever fault mechanism
3897 * the OS provides for postcopy.
3898 * The pages must be unmapped by the end of the function.
3899 * Returns: 0 on success, none-0 on failure
3902 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3904 int ret = -1;
3906 uint8_t *host_startaddr = rb->host + start;
3908 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
3909 error_report("ram_block_discard_range: Unaligned start address: %p",
3910 host_startaddr);
3911 goto err;
3914 if ((start + length) <= rb->used_length) {
3915 bool need_madvise, need_fallocate;
3916 uint8_t *host_endaddr = host_startaddr + length;
3917 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
3918 error_report("ram_block_discard_range: Unaligned end address: %p",
3919 host_endaddr);
3920 goto err;
3923 errno = ENOTSUP; /* If we are missing MADVISE etc */
3925 /* The logic here is messy;
3926 * madvise DONTNEED fails for hugepages
3927 * fallocate works on hugepages and shmem
3929 need_madvise = (rb->page_size == qemu_host_page_size);
3930 need_fallocate = rb->fd != -1;
3931 if (need_fallocate) {
3932 /* For a file, this causes the area of the file to be zero'd
3933 * if read, and for hugetlbfs also causes it to be unmapped
3934 * so a userfault will trigger.
3936 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3937 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3938 start, length);
3939 if (ret) {
3940 ret = -errno;
3941 error_report("ram_block_discard_range: Failed to fallocate "
3942 "%s:%" PRIx64 " +%zx (%d)",
3943 rb->idstr, start, length, ret);
3944 goto err;
3946 #else
3947 ret = -ENOSYS;
3948 error_report("ram_block_discard_range: fallocate not available/file"
3949 "%s:%" PRIx64 " +%zx (%d)",
3950 rb->idstr, start, length, ret);
3951 goto err;
3952 #endif
3954 if (need_madvise) {
3955 /* For normal RAM this causes it to be unmapped,
3956 * for shared memory it causes the local mapping to disappear
3957 * and to fall back on the file contents (which we just
3958 * fallocate'd away).
3960 #if defined(CONFIG_MADVISE)
3961 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3962 if (ret) {
3963 ret = -errno;
3964 error_report("ram_block_discard_range: Failed to discard range "
3965 "%s:%" PRIx64 " +%zx (%d)",
3966 rb->idstr, start, length, ret);
3967 goto err;
3969 #else
3970 ret = -ENOSYS;
3971 error_report("ram_block_discard_range: MADVISE not available"
3972 "%s:%" PRIx64 " +%zx (%d)",
3973 rb->idstr, start, length, ret);
3974 goto err;
3975 #endif
3977 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3978 need_madvise, need_fallocate, ret);
3979 } else {
3980 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3981 "/%zx/" RAM_ADDR_FMT")",
3982 rb->idstr, start, length, rb->used_length);
3985 err:
3986 return ret;
3989 #endif
3991 void page_size_init(void)
3993 /* NOTE: we can always suppose that qemu_host_page_size >=
3994 TARGET_PAGE_SIZE */
3995 if (qemu_host_page_size == 0) {
3996 qemu_host_page_size = qemu_real_host_page_size;
3998 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
3999 qemu_host_page_size = TARGET_PAGE_SIZE;
4001 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;
4004 #if !defined(CONFIG_USER_ONLY)
4006 static void mtree_print_phys_entries(fprintf_function mon, void *f,
4007 int start, int end, int skip, int ptr)
4009 if (start == end - 1) {
4010 mon(f, "\t%3d ", start);
4011 } else {
4012 mon(f, "\t%3d..%-3d ", start, end - 1);
4014 mon(f, " skip=%d ", skip);
4015 if (ptr == PHYS_MAP_NODE_NIL) {
4016 mon(f, " ptr=NIL");
4017 } else if (!skip) {
4018 mon(f, " ptr=#%d", ptr);
4019 } else {
4020 mon(f, " ptr=[%d]", ptr);
4022 mon(f, "\n");
4025 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
4026 int128_sub((size), int128_one())) : 0)
4028 void mtree_print_dispatch(fprintf_function mon, void *f,
4029 AddressSpaceDispatch *d, MemoryRegion *root)
4031 int i;
4033 mon(f, " Dispatch\n");
4034 mon(f, " Physical sections\n");
4036 for (i = 0; i < d->map.sections_nb; ++i) {
4037 MemoryRegionSection *s = d->map.sections + i;
4038 const char *names[] = { " [unassigned]", " [not dirty]",
4039 " [ROM]", " [watch]" };
4041 mon(f, " #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx " %s%s%s%s%s",
4043 s->offset_within_address_space,
4044 s->offset_within_address_space + MR_SIZE(s->mr->size),
4045 s->mr->name ? s->mr->name : "(noname)",
4046 i < ARRAY_SIZE(names) ? names[i] : "",
4047 s->mr == root ? " [ROOT]" : "",
4048 s == d->mru_section ? " [MRU]" : "",
4049 s->mr->is_iommu ? " [iommu]" : "");
4051 if (s->mr->alias) {
4052 mon(f, " alias=%s", s->mr->alias->name ?
4053 s->mr->alias->name : "noname");
4055 mon(f, "\n");
4058 mon(f, " Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
4059 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
4060 for (i = 0; i < d->map.nodes_nb; ++i) {
4061 int j, jprev;
4062 PhysPageEntry prev;
4063 Node *n = d->map.nodes + i;
4065 mon(f, " [%d]\n", i);
4067 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
4068 PhysPageEntry *pe = *n + j;
4070 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
4071 continue;
4074 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
4076 jprev = j;
4077 prev = *pe;
4080 if (jprev != ARRAY_SIZE(*n)) {
4081 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
4086 #endif