target/arm: Mask virtual interrupts if HCR_EL2.TGE is set
[qemu/ar7.git] / exec.c
blobe7be0761c28a3b9574711007aedf573de11b253e
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)
108 /* RAM can be migrated */
109 #define RAM_MIGRATABLE (1 << 4)
110 #endif
112 #ifdef TARGET_PAGE_BITS_VARY
113 int target_page_bits;
114 bool target_page_bits_decided;
115 #endif
117 struct CPUTailQ cpus = QTAILQ_HEAD_INITIALIZER(cpus);
118 /* current CPU in the current thread. It is only valid inside
119 cpu_exec() */
120 __thread CPUState *current_cpu;
121 /* 0 = Do not count executed instructions.
122 1 = Precise instruction counting.
123 2 = Adaptive rate instruction counting. */
124 int use_icount;
126 uintptr_t qemu_host_page_size;
127 intptr_t qemu_host_page_mask;
129 bool set_preferred_target_page_bits(int bits)
131 /* The target page size is the lowest common denominator for all
132 * the CPUs in the system, so we can only make it smaller, never
133 * larger. And we can't make it smaller once we've committed to
134 * a particular size.
136 #ifdef TARGET_PAGE_BITS_VARY
137 assert(bits >= TARGET_PAGE_BITS_MIN);
138 if (target_page_bits == 0 || target_page_bits > bits) {
139 if (target_page_bits_decided) {
140 return false;
142 target_page_bits = bits;
144 #endif
145 return true;
148 #if !defined(CONFIG_USER_ONLY)
150 static void finalize_target_page_bits(void)
152 #ifdef TARGET_PAGE_BITS_VARY
153 if (target_page_bits == 0) {
154 target_page_bits = TARGET_PAGE_BITS_MIN;
156 target_page_bits_decided = true;
157 #endif
160 typedef struct PhysPageEntry PhysPageEntry;
162 struct PhysPageEntry {
163 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
164 uint32_t skip : 6;
165 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
166 uint32_t ptr : 26;
169 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
171 /* Size of the L2 (and L3, etc) page tables. */
172 #define ADDR_SPACE_BITS 64
174 #define P_L2_BITS 9
175 #define P_L2_SIZE (1 << P_L2_BITS)
177 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
179 typedef PhysPageEntry Node[P_L2_SIZE];
181 typedef struct PhysPageMap {
182 struct rcu_head rcu;
184 unsigned sections_nb;
185 unsigned sections_nb_alloc;
186 unsigned nodes_nb;
187 unsigned nodes_nb_alloc;
188 Node *nodes;
189 MemoryRegionSection *sections;
190 } PhysPageMap;
192 struct AddressSpaceDispatch {
193 MemoryRegionSection *mru_section;
194 /* This is a multi-level map on the physical address space.
195 * The bottom level has pointers to MemoryRegionSections.
197 PhysPageEntry phys_map;
198 PhysPageMap map;
201 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
202 typedef struct subpage_t {
203 MemoryRegion iomem;
204 FlatView *fv;
205 hwaddr base;
206 uint16_t sub_section[];
207 } subpage_t;
209 #define PHYS_SECTION_UNASSIGNED 0
210 #define PHYS_SECTION_NOTDIRTY 1
211 #define PHYS_SECTION_ROM 2
212 #define PHYS_SECTION_WATCH 3
214 static void io_mem_init(void);
215 static void memory_map_init(void);
216 static void tcg_commit(MemoryListener *listener);
218 static MemoryRegion io_mem_watch;
221 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
222 * @cpu: the CPU whose AddressSpace this is
223 * @as: the AddressSpace itself
224 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
225 * @tcg_as_listener: listener for tracking changes to the AddressSpace
227 struct CPUAddressSpace {
228 CPUState *cpu;
229 AddressSpace *as;
230 struct AddressSpaceDispatch *memory_dispatch;
231 MemoryListener tcg_as_listener;
234 struct DirtyBitmapSnapshot {
235 ram_addr_t start;
236 ram_addr_t end;
237 unsigned long dirty[];
240 #endif
242 #if !defined(CONFIG_USER_ONLY)
244 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
246 static unsigned alloc_hint = 16;
247 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
248 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, alloc_hint);
249 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, map->nodes_nb + nodes);
250 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
251 alloc_hint = map->nodes_nb_alloc;
255 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
257 unsigned i;
258 uint32_t ret;
259 PhysPageEntry e;
260 PhysPageEntry *p;
262 ret = map->nodes_nb++;
263 p = map->nodes[ret];
264 assert(ret != PHYS_MAP_NODE_NIL);
265 assert(ret != map->nodes_nb_alloc);
267 e.skip = leaf ? 0 : 1;
268 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
269 for (i = 0; i < P_L2_SIZE; ++i) {
270 memcpy(&p[i], &e, sizeof(e));
272 return ret;
275 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
276 hwaddr *index, hwaddr *nb, uint16_t leaf,
277 int level)
279 PhysPageEntry *p;
280 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
282 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
283 lp->ptr = phys_map_node_alloc(map, level == 0);
285 p = map->nodes[lp->ptr];
286 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
288 while (*nb && lp < &p[P_L2_SIZE]) {
289 if ((*index & (step - 1)) == 0 && *nb >= step) {
290 lp->skip = 0;
291 lp->ptr = leaf;
292 *index += step;
293 *nb -= step;
294 } else {
295 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
297 ++lp;
301 static void phys_page_set(AddressSpaceDispatch *d,
302 hwaddr index, hwaddr nb,
303 uint16_t leaf)
305 /* Wildly overreserve - it doesn't matter much. */
306 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
308 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
311 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
312 * and update our entry so we can skip it and go directly to the destination.
314 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
316 unsigned valid_ptr = P_L2_SIZE;
317 int valid = 0;
318 PhysPageEntry *p;
319 int i;
321 if (lp->ptr == PHYS_MAP_NODE_NIL) {
322 return;
325 p = nodes[lp->ptr];
326 for (i = 0; i < P_L2_SIZE; i++) {
327 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
328 continue;
331 valid_ptr = i;
332 valid++;
333 if (p[i].skip) {
334 phys_page_compact(&p[i], nodes);
338 /* We can only compress if there's only one child. */
339 if (valid != 1) {
340 return;
343 assert(valid_ptr < P_L2_SIZE);
345 /* Don't compress if it won't fit in the # of bits we have. */
346 if (lp->skip + p[valid_ptr].skip >= (1 << 3)) {
347 return;
350 lp->ptr = p[valid_ptr].ptr;
351 if (!p[valid_ptr].skip) {
352 /* If our only child is a leaf, make this a leaf. */
353 /* By design, we should have made this node a leaf to begin with so we
354 * should never reach here.
355 * But since it's so simple to handle this, let's do it just in case we
356 * change this rule.
358 lp->skip = 0;
359 } else {
360 lp->skip += p[valid_ptr].skip;
364 void address_space_dispatch_compact(AddressSpaceDispatch *d)
366 if (d->phys_map.skip) {
367 phys_page_compact(&d->phys_map, d->map.nodes);
371 static inline bool section_covers_addr(const MemoryRegionSection *section,
372 hwaddr addr)
374 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
375 * the section must cover the entire address space.
377 return int128_gethi(section->size) ||
378 range_covers_byte(section->offset_within_address_space,
379 int128_getlo(section->size), addr);
382 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
384 PhysPageEntry lp = d->phys_map, *p;
385 Node *nodes = d->map.nodes;
386 MemoryRegionSection *sections = d->map.sections;
387 hwaddr index = addr >> TARGET_PAGE_BITS;
388 int i;
390 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
391 if (lp.ptr == PHYS_MAP_NODE_NIL) {
392 return &sections[PHYS_SECTION_UNASSIGNED];
394 p = nodes[lp.ptr];
395 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
398 if (section_covers_addr(&sections[lp.ptr], addr)) {
399 return &sections[lp.ptr];
400 } else {
401 return &sections[PHYS_SECTION_UNASSIGNED];
405 /* Called from RCU critical section */
406 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
407 hwaddr addr,
408 bool resolve_subpage)
410 MemoryRegionSection *section = atomic_read(&d->mru_section);
411 subpage_t *subpage;
413 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
414 !section_covers_addr(section, addr)) {
415 section = phys_page_find(d, addr);
416 atomic_set(&d->mru_section, section);
418 if (resolve_subpage && section->mr->subpage) {
419 subpage = container_of(section->mr, subpage_t, iomem);
420 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
422 return section;
425 /* Called from RCU critical section */
426 static MemoryRegionSection *
427 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
428 hwaddr *plen, bool resolve_subpage)
430 MemoryRegionSection *section;
431 MemoryRegion *mr;
432 Int128 diff;
434 section = address_space_lookup_region(d, addr, resolve_subpage);
435 /* Compute offset within MemoryRegionSection */
436 addr -= section->offset_within_address_space;
438 /* Compute offset within MemoryRegion */
439 *xlat = addr + section->offset_within_region;
441 mr = section->mr;
443 /* MMIO registers can be expected to perform full-width accesses based only
444 * on their address, without considering adjacent registers that could
445 * decode to completely different MemoryRegions. When such registers
446 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
447 * regions overlap wildly. For this reason we cannot clamp the accesses
448 * here.
450 * If the length is small (as is the case for address_space_ldl/stl),
451 * everything works fine. If the incoming length is large, however,
452 * the caller really has to do the clamping through memory_access_size.
454 if (memory_region_is_ram(mr)) {
455 diff = int128_sub(section->size, int128_make64(addr));
456 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
458 return section;
462 * address_space_translate_iommu - translate an address through an IOMMU
463 * memory region and then through the target address space.
465 * @iommu_mr: the IOMMU memory region that we start the translation from
466 * @addr: the address to be translated through the MMU
467 * @xlat: the translated address offset within the destination memory region.
468 * It cannot be %NULL.
469 * @plen_out: valid read/write length of the translated address. It
470 * cannot be %NULL.
471 * @page_mask_out: page mask for the translated address. This
472 * should only be meaningful for IOMMU translated
473 * addresses, since there may be huge pages that this bit
474 * would tell. It can be %NULL if we don't care about it.
475 * @is_write: whether the translation operation is for write
476 * @is_mmio: whether this can be MMIO, set true if it can
477 * @target_as: the address space targeted by the IOMMU
478 * @attrs: transaction attributes
480 * This function is called from RCU critical section. It is the common
481 * part of flatview_do_translate and address_space_translate_cached.
483 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
484 hwaddr *xlat,
485 hwaddr *plen_out,
486 hwaddr *page_mask_out,
487 bool is_write,
488 bool is_mmio,
489 AddressSpace **target_as,
490 MemTxAttrs attrs)
492 MemoryRegionSection *section;
493 hwaddr page_mask = (hwaddr)-1;
495 do {
496 hwaddr addr = *xlat;
497 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
498 int iommu_idx = 0;
499 IOMMUTLBEntry iotlb;
501 if (imrc->attrs_to_index) {
502 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
505 iotlb = imrc->translate(iommu_mr, addr, is_write ?
506 IOMMU_WO : IOMMU_RO, iommu_idx);
508 if (!(iotlb.perm & (1 << is_write))) {
509 goto unassigned;
512 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
513 | (addr & iotlb.addr_mask));
514 page_mask &= iotlb.addr_mask;
515 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
516 *target_as = iotlb.target_as;
518 section = address_space_translate_internal(
519 address_space_to_dispatch(iotlb.target_as), addr, xlat,
520 plen_out, is_mmio);
522 iommu_mr = memory_region_get_iommu(section->mr);
523 } while (unlikely(iommu_mr));
525 if (page_mask_out) {
526 *page_mask_out = page_mask;
528 return *section;
530 unassigned:
531 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
535 * flatview_do_translate - translate an address in FlatView
537 * @fv: the flat view that we want to translate on
538 * @addr: the address to be translated in above address space
539 * @xlat: the translated address offset within memory region. It
540 * cannot be @NULL.
541 * @plen_out: valid read/write length of the translated address. It
542 * can be @NULL when we don't care about it.
543 * @page_mask_out: page mask for the translated address. This
544 * should only be meaningful for IOMMU translated
545 * addresses, since there may be huge pages that this bit
546 * would tell. It can be @NULL if we don't care about it.
547 * @is_write: whether the translation operation is for write
548 * @is_mmio: whether this can be MMIO, set true if it can
549 * @target_as: the address space targeted by the IOMMU
550 * @attrs: memory transaction attributes
552 * This function is called from RCU critical section
554 static MemoryRegionSection flatview_do_translate(FlatView *fv,
555 hwaddr addr,
556 hwaddr *xlat,
557 hwaddr *plen_out,
558 hwaddr *page_mask_out,
559 bool is_write,
560 bool is_mmio,
561 AddressSpace **target_as,
562 MemTxAttrs attrs)
564 MemoryRegionSection *section;
565 IOMMUMemoryRegion *iommu_mr;
566 hwaddr plen = (hwaddr)(-1);
568 if (!plen_out) {
569 plen_out = &plen;
572 section = address_space_translate_internal(
573 flatview_to_dispatch(fv), addr, xlat,
574 plen_out, is_mmio);
576 iommu_mr = memory_region_get_iommu(section->mr);
577 if (unlikely(iommu_mr)) {
578 return address_space_translate_iommu(iommu_mr, xlat,
579 plen_out, page_mask_out,
580 is_write, is_mmio,
581 target_as, attrs);
583 if (page_mask_out) {
584 /* Not behind an IOMMU, use default page size. */
585 *page_mask_out = ~TARGET_PAGE_MASK;
588 return *section;
591 /* Called from RCU critical section */
592 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
593 bool is_write, MemTxAttrs attrs)
595 MemoryRegionSection section;
596 hwaddr xlat, page_mask;
599 * This can never be MMIO, and we don't really care about plen,
600 * but page mask.
602 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
603 NULL, &page_mask, is_write, false, &as,
604 attrs);
606 /* Illegal translation */
607 if (section.mr == &io_mem_unassigned) {
608 goto iotlb_fail;
611 /* Convert memory region offset into address space offset */
612 xlat += section.offset_within_address_space -
613 section.offset_within_region;
615 return (IOMMUTLBEntry) {
616 .target_as = as,
617 .iova = addr & ~page_mask,
618 .translated_addr = xlat & ~page_mask,
619 .addr_mask = page_mask,
620 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
621 .perm = IOMMU_RW,
624 iotlb_fail:
625 return (IOMMUTLBEntry) {0};
628 /* Called from RCU critical section */
629 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
630 hwaddr *plen, bool is_write,
631 MemTxAttrs attrs)
633 MemoryRegion *mr;
634 MemoryRegionSection section;
635 AddressSpace *as = NULL;
637 /* This can be MMIO, so setup MMIO bit. */
638 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
639 is_write, true, &as, attrs);
640 mr = section.mr;
642 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
643 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
644 *plen = MIN(page, *plen);
647 return mr;
650 typedef struct TCGIOMMUNotifier {
651 IOMMUNotifier n;
652 MemoryRegion *mr;
653 CPUState *cpu;
654 int iommu_idx;
655 bool active;
656 } TCGIOMMUNotifier;
658 static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
660 TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
662 if (!notifier->active) {
663 return;
665 tlb_flush(notifier->cpu);
666 notifier->active = false;
667 /* We leave the notifier struct on the list to avoid reallocating it later.
668 * Generally the number of IOMMUs a CPU deals with will be small.
669 * In any case we can't unregister the iommu notifier from a notify
670 * callback.
674 static void tcg_register_iommu_notifier(CPUState *cpu,
675 IOMMUMemoryRegion *iommu_mr,
676 int iommu_idx)
678 /* Make sure this CPU has an IOMMU notifier registered for this
679 * IOMMU/IOMMU index combination, so that we can flush its TLB
680 * when the IOMMU tells us the mappings we've cached have changed.
682 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
683 TCGIOMMUNotifier *notifier;
684 int i;
686 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
687 notifier = &g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier, i);
688 if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
689 break;
692 if (i == cpu->iommu_notifiers->len) {
693 /* Not found, add a new entry at the end of the array */
694 cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
695 notifier = &g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier, i);
697 notifier->mr = mr;
698 notifier->iommu_idx = iommu_idx;
699 notifier->cpu = cpu;
700 /* Rather than trying to register interest in the specific part
701 * of the iommu's address space that we've accessed and then
702 * expand it later as subsequent accesses touch more of it, we
703 * just register interest in the whole thing, on the assumption
704 * that iommu reconfiguration will be rare.
706 iommu_notifier_init(&notifier->n,
707 tcg_iommu_unmap_notify,
708 IOMMU_NOTIFIER_UNMAP,
710 HWADDR_MAX,
711 iommu_idx);
712 memory_region_register_iommu_notifier(notifier->mr, &notifier->n);
715 if (!notifier->active) {
716 notifier->active = true;
720 static void tcg_iommu_free_notifier_list(CPUState *cpu)
722 /* Destroy the CPU's notifier list */
723 int i;
724 TCGIOMMUNotifier *notifier;
726 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
727 notifier = &g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier, i);
728 memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
730 g_array_free(cpu->iommu_notifiers, true);
733 /* Called from RCU critical section */
734 MemoryRegionSection *
735 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
736 hwaddr *xlat, hwaddr *plen,
737 MemTxAttrs attrs, int *prot)
739 MemoryRegionSection *section;
740 IOMMUMemoryRegion *iommu_mr;
741 IOMMUMemoryRegionClass *imrc;
742 IOMMUTLBEntry iotlb;
743 int iommu_idx;
744 AddressSpaceDispatch *d = atomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
746 for (;;) {
747 section = address_space_translate_internal(d, addr, &addr, plen, false);
749 iommu_mr = memory_region_get_iommu(section->mr);
750 if (!iommu_mr) {
751 break;
754 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
756 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
757 tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
758 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
759 * doesn't short-cut its translation table walk.
761 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
762 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
763 | (addr & iotlb.addr_mask));
764 /* Update the caller's prot bits to remove permissions the IOMMU
765 * is giving us a failure response for. If we get down to no
766 * permissions left at all we can give up now.
768 if (!(iotlb.perm & IOMMU_RO)) {
769 *prot &= ~(PAGE_READ | PAGE_EXEC);
771 if (!(iotlb.perm & IOMMU_WO)) {
772 *prot &= ~PAGE_WRITE;
775 if (!*prot) {
776 goto translate_fail;
779 d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
782 assert(!memory_region_is_iommu(section->mr));
783 *xlat = addr;
784 return section;
786 translate_fail:
787 return &d->map.sections[PHYS_SECTION_UNASSIGNED];
789 #endif
791 #if !defined(CONFIG_USER_ONLY)
793 static int cpu_common_post_load(void *opaque, int version_id)
795 CPUState *cpu = opaque;
797 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
798 version_id is increased. */
799 cpu->interrupt_request &= ~0x01;
800 tlb_flush(cpu);
802 /* loadvm has just updated the content of RAM, bypassing the
803 * usual mechanisms that ensure we flush TBs for writes to
804 * memory we've translated code from. So we must flush all TBs,
805 * which will now be stale.
807 tb_flush(cpu);
809 return 0;
812 static int cpu_common_pre_load(void *opaque)
814 CPUState *cpu = opaque;
816 cpu->exception_index = -1;
818 return 0;
821 static bool cpu_common_exception_index_needed(void *opaque)
823 CPUState *cpu = opaque;
825 return tcg_enabled() && cpu->exception_index != -1;
828 static const VMStateDescription vmstate_cpu_common_exception_index = {
829 .name = "cpu_common/exception_index",
830 .version_id = 1,
831 .minimum_version_id = 1,
832 .needed = cpu_common_exception_index_needed,
833 .fields = (VMStateField[]) {
834 VMSTATE_INT32(exception_index, CPUState),
835 VMSTATE_END_OF_LIST()
839 static bool cpu_common_crash_occurred_needed(void *opaque)
841 CPUState *cpu = opaque;
843 return cpu->crash_occurred;
846 static const VMStateDescription vmstate_cpu_common_crash_occurred = {
847 .name = "cpu_common/crash_occurred",
848 .version_id = 1,
849 .minimum_version_id = 1,
850 .needed = cpu_common_crash_occurred_needed,
851 .fields = (VMStateField[]) {
852 VMSTATE_BOOL(crash_occurred, CPUState),
853 VMSTATE_END_OF_LIST()
857 const VMStateDescription vmstate_cpu_common = {
858 .name = "cpu_common",
859 .version_id = 1,
860 .minimum_version_id = 1,
861 .pre_load = cpu_common_pre_load,
862 .post_load = cpu_common_post_load,
863 .fields = (VMStateField[]) {
864 VMSTATE_UINT32(halted, CPUState),
865 VMSTATE_UINT32(interrupt_request, CPUState),
866 VMSTATE_END_OF_LIST()
868 .subsections = (const VMStateDescription*[]) {
869 &vmstate_cpu_common_exception_index,
870 &vmstate_cpu_common_crash_occurred,
871 NULL
875 #endif
877 CPUState *qemu_get_cpu(int index)
879 CPUState *cpu;
881 CPU_FOREACH(cpu) {
882 if (cpu->cpu_index == index) {
883 return cpu;
887 return NULL;
890 #if !defined(CONFIG_USER_ONLY)
891 void cpu_address_space_init(CPUState *cpu, int asidx,
892 const char *prefix, MemoryRegion *mr)
894 CPUAddressSpace *newas;
895 AddressSpace *as = g_new0(AddressSpace, 1);
896 char *as_name;
898 assert(mr);
899 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
900 address_space_init(as, mr, as_name);
901 g_free(as_name);
903 /* Target code should have set num_ases before calling us */
904 assert(asidx < cpu->num_ases);
906 if (asidx == 0) {
907 /* address space 0 gets the convenience alias */
908 cpu->as = as;
911 /* KVM cannot currently support multiple address spaces. */
912 assert(asidx == 0 || !kvm_enabled());
914 if (!cpu->cpu_ases) {
915 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
918 newas = &cpu->cpu_ases[asidx];
919 newas->cpu = cpu;
920 newas->as = as;
921 if (tcg_enabled()) {
922 newas->tcg_as_listener.commit = tcg_commit;
923 memory_listener_register(&newas->tcg_as_listener, as);
927 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
929 /* Return the AddressSpace corresponding to the specified index */
930 return cpu->cpu_ases[asidx].as;
932 #endif
934 void cpu_exec_unrealizefn(CPUState *cpu)
936 CPUClass *cc = CPU_GET_CLASS(cpu);
938 cpu_list_remove(cpu);
940 if (cc->vmsd != NULL) {
941 vmstate_unregister(NULL, cc->vmsd, cpu);
943 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
944 vmstate_unregister(NULL, &vmstate_cpu_common, cpu);
946 #ifndef CONFIG_USER_ONLY
947 tcg_iommu_free_notifier_list(cpu);
948 #endif
951 Property cpu_common_props[] = {
952 #ifndef CONFIG_USER_ONLY
953 /* Create a memory property for softmmu CPU object,
954 * so users can wire up its memory. (This can't go in qom/cpu.c
955 * because that file is compiled only once for both user-mode
956 * and system builds.) The default if no link is set up is to use
957 * the system address space.
959 DEFINE_PROP_LINK("memory", CPUState, memory, TYPE_MEMORY_REGION,
960 MemoryRegion *),
961 #endif
962 DEFINE_PROP_END_OF_LIST(),
965 void cpu_exec_initfn(CPUState *cpu)
967 cpu->as = NULL;
968 cpu->num_ases = 0;
970 #ifndef CONFIG_USER_ONLY
971 cpu->thread_id = qemu_get_thread_id();
972 cpu->memory = system_memory;
973 object_ref(OBJECT(cpu->memory));
974 #endif
977 void cpu_exec_realizefn(CPUState *cpu, Error **errp)
979 CPUClass *cc = CPU_GET_CLASS(cpu);
980 static bool tcg_target_initialized;
982 cpu_list_add(cpu);
984 if (tcg_enabled() && !tcg_target_initialized) {
985 tcg_target_initialized = true;
986 cc->tcg_initialize();
989 #ifndef CONFIG_USER_ONLY
990 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
991 vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
993 if (cc->vmsd != NULL) {
994 vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);
997 cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier));
998 #endif
1001 const char *parse_cpu_model(const char *cpu_model)
1003 ObjectClass *oc;
1004 CPUClass *cc;
1005 gchar **model_pieces;
1006 const char *cpu_type;
1008 model_pieces = g_strsplit(cpu_model, ",", 2);
1010 oc = cpu_class_by_name(CPU_RESOLVING_TYPE, model_pieces[0]);
1011 if (oc == NULL) {
1012 error_report("unable to find CPU model '%s'", model_pieces[0]);
1013 g_strfreev(model_pieces);
1014 exit(EXIT_FAILURE);
1017 cpu_type = object_class_get_name(oc);
1018 cc = CPU_CLASS(oc);
1019 cc->parse_features(cpu_type, model_pieces[1], &error_fatal);
1020 g_strfreev(model_pieces);
1021 return cpu_type;
1024 #if defined(CONFIG_USER_ONLY)
1025 void tb_invalidate_phys_addr(target_ulong addr)
1027 mmap_lock();
1028 tb_invalidate_phys_page_range(addr, addr + 1, 0);
1029 mmap_unlock();
1032 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
1034 tb_invalidate_phys_addr(pc);
1036 #else
1037 void tb_invalidate_phys_addr(AddressSpace *as, hwaddr addr, MemTxAttrs attrs)
1039 ram_addr_t ram_addr;
1040 MemoryRegion *mr;
1041 hwaddr l = 1;
1043 if (!tcg_enabled()) {
1044 return;
1047 rcu_read_lock();
1048 mr = address_space_translate(as, addr, &addr, &l, false, attrs);
1049 if (!(memory_region_is_ram(mr)
1050 || memory_region_is_romd(mr))) {
1051 rcu_read_unlock();
1052 return;
1054 ram_addr = memory_region_get_ram_addr(mr) + addr;
1055 tb_invalidate_phys_page_range(ram_addr, ram_addr + 1, 0);
1056 rcu_read_unlock();
1059 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
1061 MemTxAttrs attrs;
1062 hwaddr phys = cpu_get_phys_page_attrs_debug(cpu, pc, &attrs);
1063 int asidx = cpu_asidx_from_attrs(cpu, attrs);
1064 if (phys != -1) {
1065 /* Locks grabbed by tb_invalidate_phys_addr */
1066 tb_invalidate_phys_addr(cpu->cpu_ases[asidx].as,
1067 phys | (pc & ~TARGET_PAGE_MASK), attrs);
1070 #endif
1072 #if defined(CONFIG_USER_ONLY)
1073 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
1078 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
1079 int flags)
1081 return -ENOSYS;
1084 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
1088 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
1089 int flags, CPUWatchpoint **watchpoint)
1091 return -ENOSYS;
1093 #else
1094 /* Add a watchpoint. */
1095 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
1096 int flags, CPUWatchpoint **watchpoint)
1098 CPUWatchpoint *wp;
1100 /* forbid ranges which are empty or run off the end of the address space */
1101 if (len == 0 || (addr + len - 1) < addr) {
1102 error_report("tried to set invalid watchpoint at %"
1103 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
1104 return -EINVAL;
1106 wp = g_malloc(sizeof(*wp));
1108 wp->vaddr = addr;
1109 wp->len = len;
1110 wp->flags = flags;
1112 /* keep all GDB-injected watchpoints in front */
1113 if (flags & BP_GDB) {
1114 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
1115 } else {
1116 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
1119 tlb_flush_page(cpu, addr);
1121 if (watchpoint)
1122 *watchpoint = wp;
1123 return 0;
1126 /* Remove a specific watchpoint. */
1127 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
1128 int flags)
1130 CPUWatchpoint *wp;
1132 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1133 if (addr == wp->vaddr && len == wp->len
1134 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
1135 cpu_watchpoint_remove_by_ref(cpu, wp);
1136 return 0;
1139 return -ENOENT;
1142 /* Remove a specific watchpoint by reference. */
1143 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
1145 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
1147 tlb_flush_page(cpu, watchpoint->vaddr);
1149 g_free(watchpoint);
1152 /* Remove all matching watchpoints. */
1153 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
1155 CPUWatchpoint *wp, *next;
1157 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
1158 if (wp->flags & mask) {
1159 cpu_watchpoint_remove_by_ref(cpu, wp);
1164 /* Return true if this watchpoint address matches the specified
1165 * access (ie the address range covered by the watchpoint overlaps
1166 * partially or completely with the address range covered by the
1167 * access).
1169 static inline bool cpu_watchpoint_address_matches(CPUWatchpoint *wp,
1170 vaddr addr,
1171 vaddr len)
1173 /* We know the lengths are non-zero, but a little caution is
1174 * required to avoid errors in the case where the range ends
1175 * exactly at the top of the address space and so addr + len
1176 * wraps round to zero.
1178 vaddr wpend = wp->vaddr + wp->len - 1;
1179 vaddr addrend = addr + len - 1;
1181 return !(addr > wpend || wp->vaddr > addrend);
1184 #endif
1186 /* Add a breakpoint. */
1187 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
1188 CPUBreakpoint **breakpoint)
1190 CPUBreakpoint *bp;
1192 bp = g_malloc(sizeof(*bp));
1194 bp->pc = pc;
1195 bp->flags = flags;
1197 /* keep all GDB-injected breakpoints in front */
1198 if (flags & BP_GDB) {
1199 QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
1200 } else {
1201 QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
1204 breakpoint_invalidate(cpu, pc);
1206 if (breakpoint) {
1207 *breakpoint = bp;
1209 return 0;
1212 /* Remove a specific breakpoint. */
1213 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
1215 CPUBreakpoint *bp;
1217 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
1218 if (bp->pc == pc && bp->flags == flags) {
1219 cpu_breakpoint_remove_by_ref(cpu, bp);
1220 return 0;
1223 return -ENOENT;
1226 /* Remove a specific breakpoint by reference. */
1227 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
1229 QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);
1231 breakpoint_invalidate(cpu, breakpoint->pc);
1233 g_free(breakpoint);
1236 /* Remove all matching breakpoints. */
1237 void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
1239 CPUBreakpoint *bp, *next;
1241 QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
1242 if (bp->flags & mask) {
1243 cpu_breakpoint_remove_by_ref(cpu, bp);
1248 /* enable or disable single step mode. EXCP_DEBUG is returned by the
1249 CPU loop after each instruction */
1250 void cpu_single_step(CPUState *cpu, int enabled)
1252 if (cpu->singlestep_enabled != enabled) {
1253 cpu->singlestep_enabled = enabled;
1254 if (kvm_enabled()) {
1255 kvm_update_guest_debug(cpu, 0);
1256 } else {
1257 /* must flush all the translated code to avoid inconsistencies */
1258 /* XXX: only flush what is necessary */
1259 tb_flush(cpu);
1264 void cpu_abort(CPUState *cpu, const char *fmt, ...)
1266 va_list ap;
1267 va_list ap2;
1269 va_start(ap, fmt);
1270 va_copy(ap2, ap);
1271 fprintf(stderr, "qemu: fatal: ");
1272 vfprintf(stderr, fmt, ap);
1273 fprintf(stderr, "\n");
1274 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1275 if (qemu_log_separate()) {
1276 qemu_log_lock();
1277 qemu_log("qemu: fatal: ");
1278 qemu_log_vprintf(fmt, ap2);
1279 qemu_log("\n");
1280 log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1281 qemu_log_flush();
1282 qemu_log_unlock();
1283 qemu_log_close();
1285 va_end(ap2);
1286 va_end(ap);
1287 replay_finish();
1288 #if defined(CONFIG_USER_ONLY)
1290 struct sigaction act;
1291 sigfillset(&act.sa_mask);
1292 act.sa_handler = SIG_DFL;
1293 act.sa_flags = 0;
1294 sigaction(SIGABRT, &act, NULL);
1296 #endif
1297 abort();
1300 #if !defined(CONFIG_USER_ONLY)
1301 /* Called from RCU critical section */
1302 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
1304 RAMBlock *block;
1306 block = atomic_rcu_read(&ram_list.mru_block);
1307 if (block && addr - block->offset < block->max_length) {
1308 return block;
1310 RAMBLOCK_FOREACH(block) {
1311 if (addr - block->offset < block->max_length) {
1312 goto found;
1316 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1317 abort();
1319 found:
1320 /* It is safe to write mru_block outside the iothread lock. This
1321 * is what happens:
1323 * mru_block = xxx
1324 * rcu_read_unlock()
1325 * xxx removed from list
1326 * rcu_read_lock()
1327 * read mru_block
1328 * mru_block = NULL;
1329 * call_rcu(reclaim_ramblock, xxx);
1330 * rcu_read_unlock()
1332 * atomic_rcu_set is not needed here. The block was already published
1333 * when it was placed into the list. Here we're just making an extra
1334 * copy of the pointer.
1336 ram_list.mru_block = block;
1337 return block;
1340 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1342 CPUState *cpu;
1343 ram_addr_t start1;
1344 RAMBlock *block;
1345 ram_addr_t end;
1347 assert(tcg_enabled());
1348 end = TARGET_PAGE_ALIGN(start + length);
1349 start &= TARGET_PAGE_MASK;
1351 rcu_read_lock();
1352 block = qemu_get_ram_block(start);
1353 assert(block == qemu_get_ram_block(end - 1));
1354 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1355 CPU_FOREACH(cpu) {
1356 tlb_reset_dirty(cpu, start1, length);
1358 rcu_read_unlock();
1361 /* Note: start and end must be within the same ram block. */
1362 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1363 ram_addr_t length,
1364 unsigned client)
1366 DirtyMemoryBlocks *blocks;
1367 unsigned long end, page;
1368 bool dirty = false;
1370 if (length == 0) {
1371 return false;
1374 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1375 page = start >> TARGET_PAGE_BITS;
1377 rcu_read_lock();
1379 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1381 while (page < end) {
1382 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1383 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1384 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1386 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1387 offset, num);
1388 page += num;
1391 rcu_read_unlock();
1393 if (dirty && tcg_enabled()) {
1394 tlb_reset_dirty_range_all(start, length);
1397 return dirty;
1400 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1401 (ram_addr_t start, ram_addr_t length, unsigned client)
1403 DirtyMemoryBlocks *blocks;
1404 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1405 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1406 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1407 DirtyBitmapSnapshot *snap;
1408 unsigned long page, end, dest;
1410 snap = g_malloc0(sizeof(*snap) +
1411 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1412 snap->start = first;
1413 snap->end = last;
1415 page = first >> TARGET_PAGE_BITS;
1416 end = last >> TARGET_PAGE_BITS;
1417 dest = 0;
1419 rcu_read_lock();
1421 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1423 while (page < end) {
1424 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1425 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1426 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1428 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1429 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1430 offset >>= BITS_PER_LEVEL;
1432 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1433 blocks->blocks[idx] + offset,
1434 num);
1435 page += num;
1436 dest += num >> BITS_PER_LEVEL;
1439 rcu_read_unlock();
1441 if (tcg_enabled()) {
1442 tlb_reset_dirty_range_all(start, length);
1445 return snap;
1448 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1449 ram_addr_t start,
1450 ram_addr_t length)
1452 unsigned long page, end;
1454 assert(start >= snap->start);
1455 assert(start + length <= snap->end);
1457 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1458 page = (start - snap->start) >> TARGET_PAGE_BITS;
1460 while (page < end) {
1461 if (test_bit(page, snap->dirty)) {
1462 return true;
1464 page++;
1466 return false;
1469 /* Called from RCU critical section */
1470 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1471 MemoryRegionSection *section,
1472 target_ulong vaddr,
1473 hwaddr paddr, hwaddr xlat,
1474 int prot,
1475 target_ulong *address)
1477 hwaddr iotlb;
1478 CPUWatchpoint *wp;
1480 if (memory_region_is_ram(section->mr)) {
1481 /* Normal RAM. */
1482 iotlb = memory_region_get_ram_addr(section->mr) + xlat;
1483 if (!section->readonly) {
1484 iotlb |= PHYS_SECTION_NOTDIRTY;
1485 } else {
1486 iotlb |= PHYS_SECTION_ROM;
1488 } else {
1489 AddressSpaceDispatch *d;
1491 d = flatview_to_dispatch(section->fv);
1492 iotlb = section - d->map.sections;
1493 iotlb += xlat;
1496 /* Make accesses to pages with watchpoints go via the
1497 watchpoint trap routines. */
1498 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1499 if (cpu_watchpoint_address_matches(wp, vaddr, TARGET_PAGE_SIZE)) {
1500 /* Avoid trapping reads of pages with a write breakpoint. */
1501 if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
1502 iotlb = PHYS_SECTION_WATCH + paddr;
1503 *address |= TLB_MMIO;
1504 break;
1509 return iotlb;
1511 #endif /* defined(CONFIG_USER_ONLY) */
1513 #if !defined(CONFIG_USER_ONLY)
1515 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
1516 uint16_t section);
1517 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1519 static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
1520 qemu_anon_ram_alloc;
1523 * Set a custom physical guest memory alloator.
1524 * Accelerators with unusual needs may need this. Hopefully, we can
1525 * get rid of it eventually.
1527 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
1529 phys_mem_alloc = alloc;
1532 static uint16_t phys_section_add(PhysPageMap *map,
1533 MemoryRegionSection *section)
1535 /* The physical section number is ORed with a page-aligned
1536 * pointer to produce the iotlb entries. Thus it should
1537 * never overflow into the page-aligned value.
1539 assert(map->sections_nb < TARGET_PAGE_SIZE);
1541 if (map->sections_nb == map->sections_nb_alloc) {
1542 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1543 map->sections = g_renew(MemoryRegionSection, map->sections,
1544 map->sections_nb_alloc);
1546 map->sections[map->sections_nb] = *section;
1547 memory_region_ref(section->mr);
1548 return map->sections_nb++;
1551 static void phys_section_destroy(MemoryRegion *mr)
1553 bool have_sub_page = mr->subpage;
1555 memory_region_unref(mr);
1557 if (have_sub_page) {
1558 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1559 object_unref(OBJECT(&subpage->iomem));
1560 g_free(subpage);
1564 static void phys_sections_free(PhysPageMap *map)
1566 while (map->sections_nb > 0) {
1567 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1568 phys_section_destroy(section->mr);
1570 g_free(map->sections);
1571 g_free(map->nodes);
1574 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1576 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1577 subpage_t *subpage;
1578 hwaddr base = section->offset_within_address_space
1579 & TARGET_PAGE_MASK;
1580 MemoryRegionSection *existing = phys_page_find(d, base);
1581 MemoryRegionSection subsection = {
1582 .offset_within_address_space = base,
1583 .size = int128_make64(TARGET_PAGE_SIZE),
1585 hwaddr start, end;
1587 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1589 if (!(existing->mr->subpage)) {
1590 subpage = subpage_init(fv, base);
1591 subsection.fv = fv;
1592 subsection.mr = &subpage->iomem;
1593 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1594 phys_section_add(&d->map, &subsection));
1595 } else {
1596 subpage = container_of(existing->mr, subpage_t, iomem);
1598 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1599 end = start + int128_get64(section->size) - 1;
1600 subpage_register(subpage, start, end,
1601 phys_section_add(&d->map, section));
1605 static void register_multipage(FlatView *fv,
1606 MemoryRegionSection *section)
1608 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1609 hwaddr start_addr = section->offset_within_address_space;
1610 uint16_t section_index = phys_section_add(&d->map, section);
1611 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1612 TARGET_PAGE_BITS));
1614 assert(num_pages);
1615 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1618 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1620 MemoryRegionSection now = *section, remain = *section;
1621 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1623 if (now.offset_within_address_space & ~TARGET_PAGE_MASK) {
1624 uint64_t left = TARGET_PAGE_ALIGN(now.offset_within_address_space)
1625 - now.offset_within_address_space;
1627 now.size = int128_min(int128_make64(left), now.size);
1628 register_subpage(fv, &now);
1629 } else {
1630 now.size = int128_zero();
1632 while (int128_ne(remain.size, now.size)) {
1633 remain.size = int128_sub(remain.size, now.size);
1634 remain.offset_within_address_space += int128_get64(now.size);
1635 remain.offset_within_region += int128_get64(now.size);
1636 now = remain;
1637 if (int128_lt(remain.size, page_size)) {
1638 register_subpage(fv, &now);
1639 } else if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1640 now.size = page_size;
1641 register_subpage(fv, &now);
1642 } else {
1643 now.size = int128_and(now.size, int128_neg(page_size));
1644 register_multipage(fv, &now);
1649 void qemu_flush_coalesced_mmio_buffer(void)
1651 if (kvm_enabled())
1652 kvm_flush_coalesced_mmio_buffer();
1655 void qemu_mutex_lock_ramlist(void)
1657 qemu_mutex_lock(&ram_list.mutex);
1660 void qemu_mutex_unlock_ramlist(void)
1662 qemu_mutex_unlock(&ram_list.mutex);
1665 void ram_block_dump(Monitor *mon)
1667 RAMBlock *block;
1668 char *psize;
1670 rcu_read_lock();
1671 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1672 "Block Name", "PSize", "Offset", "Used", "Total");
1673 RAMBLOCK_FOREACH(block) {
1674 psize = size_to_str(block->page_size);
1675 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1676 " 0x%016" PRIx64 "\n", block->idstr, psize,
1677 (uint64_t)block->offset,
1678 (uint64_t)block->used_length,
1679 (uint64_t)block->max_length);
1680 g_free(psize);
1682 rcu_read_unlock();
1685 #ifdef __linux__
1687 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1688 * may or may not name the same files / on the same filesystem now as
1689 * when we actually open and map them. Iterate over the file
1690 * descriptors instead, and use qemu_fd_getpagesize().
1692 static int find_max_supported_pagesize(Object *obj, void *opaque)
1694 long *hpsize_min = opaque;
1696 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1697 long hpsize = host_memory_backend_pagesize(MEMORY_BACKEND(obj));
1699 if (hpsize < *hpsize_min) {
1700 *hpsize_min = hpsize;
1704 return 0;
1707 long qemu_getrampagesize(void)
1709 long hpsize = LONG_MAX;
1710 long mainrampagesize;
1711 Object *memdev_root;
1713 mainrampagesize = qemu_mempath_getpagesize(mem_path);
1715 /* it's possible we have memory-backend objects with
1716 * hugepage-backed RAM. these may get mapped into system
1717 * address space via -numa parameters or memory hotplug
1718 * hooks. we want to take these into account, but we
1719 * also want to make sure these supported hugepage
1720 * sizes are applicable across the entire range of memory
1721 * we may boot from, so we take the min across all
1722 * backends, and assume normal pages in cases where a
1723 * backend isn't backed by hugepages.
1725 memdev_root = object_resolve_path("/objects", NULL);
1726 if (memdev_root) {
1727 object_child_foreach(memdev_root, find_max_supported_pagesize, &hpsize);
1729 if (hpsize == LONG_MAX) {
1730 /* No additional memory regions found ==> Report main RAM page size */
1731 return mainrampagesize;
1734 /* If NUMA is disabled or the NUMA nodes are not backed with a
1735 * memory-backend, then there is at least one node using "normal" RAM,
1736 * so if its page size is smaller we have got to report that size instead.
1738 if (hpsize > mainrampagesize &&
1739 (nb_numa_nodes == 0 || numa_info[0].node_memdev == NULL)) {
1740 static bool warned;
1741 if (!warned) {
1742 error_report("Huge page support disabled (n/a for main memory).");
1743 warned = true;
1745 return mainrampagesize;
1748 return hpsize;
1750 #else
1751 long qemu_getrampagesize(void)
1753 return getpagesize();
1755 #endif
1757 #ifdef __linux__
1758 static int64_t get_file_size(int fd)
1760 int64_t size = lseek(fd, 0, SEEK_END);
1761 if (size < 0) {
1762 return -errno;
1764 return size;
1767 static int file_ram_open(const char *path,
1768 const char *region_name,
1769 bool *created,
1770 Error **errp)
1772 char *filename;
1773 char *sanitized_name;
1774 char *c;
1775 int fd = -1;
1777 *created = false;
1778 for (;;) {
1779 fd = open(path, O_RDWR);
1780 if (fd >= 0) {
1781 /* @path names an existing file, use it */
1782 break;
1784 if (errno == ENOENT) {
1785 /* @path names a file that doesn't exist, create it */
1786 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1787 if (fd >= 0) {
1788 *created = true;
1789 break;
1791 } else if (errno == EISDIR) {
1792 /* @path names a directory, create a file there */
1793 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1794 sanitized_name = g_strdup(region_name);
1795 for (c = sanitized_name; *c != '\0'; c++) {
1796 if (*c == '/') {
1797 *c = '_';
1801 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1802 sanitized_name);
1803 g_free(sanitized_name);
1805 fd = mkstemp(filename);
1806 if (fd >= 0) {
1807 unlink(filename);
1808 g_free(filename);
1809 break;
1811 g_free(filename);
1813 if (errno != EEXIST && errno != EINTR) {
1814 error_setg_errno(errp, errno,
1815 "can't open backing store %s for guest RAM",
1816 path);
1817 return -1;
1820 * Try again on EINTR and EEXIST. The latter happens when
1821 * something else creates the file between our two open().
1825 return fd;
1828 static void *file_ram_alloc(RAMBlock *block,
1829 ram_addr_t memory,
1830 int fd,
1831 bool truncate,
1832 Error **errp)
1834 void *area;
1836 block->page_size = qemu_fd_getpagesize(fd);
1837 if (block->mr->align % block->page_size) {
1838 error_setg(errp, "alignment 0x%" PRIx64
1839 " must be multiples of page size 0x%zx",
1840 block->mr->align, block->page_size);
1841 return NULL;
1842 } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1843 error_setg(errp, "alignment 0x%" PRIx64
1844 " must be a power of two", block->mr->align);
1845 return NULL;
1847 block->mr->align = MAX(block->page_size, block->mr->align);
1848 #if defined(__s390x__)
1849 if (kvm_enabled()) {
1850 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1852 #endif
1854 if (memory < block->page_size) {
1855 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1856 "or larger than page size 0x%zx",
1857 memory, block->page_size);
1858 return NULL;
1861 memory = ROUND_UP(memory, block->page_size);
1864 * ftruncate is not supported by hugetlbfs in older
1865 * hosts, so don't bother bailing out on errors.
1866 * If anything goes wrong with it under other filesystems,
1867 * mmap will fail.
1869 * Do not truncate the non-empty backend file to avoid corrupting
1870 * the existing data in the file. Disabling shrinking is not
1871 * enough. For example, the current vNVDIMM implementation stores
1872 * the guest NVDIMM labels at the end of the backend file. If the
1873 * backend file is later extended, QEMU will not be able to find
1874 * those labels. Therefore, extending the non-empty backend file
1875 * is disabled as well.
1877 if (truncate && ftruncate(fd, memory)) {
1878 perror("ftruncate");
1881 area = qemu_ram_mmap(fd, memory, block->mr->align,
1882 block->flags & RAM_SHARED);
1883 if (area == MAP_FAILED) {
1884 error_setg_errno(errp, errno,
1885 "unable to map backing store for guest RAM");
1886 return NULL;
1889 if (mem_prealloc) {
1890 os_mem_prealloc(fd, area, memory, smp_cpus, errp);
1891 if (errp && *errp) {
1892 qemu_ram_munmap(area, memory);
1893 return NULL;
1897 block->fd = fd;
1898 return area;
1900 #endif
1902 /* Allocate space within the ram_addr_t space that governs the
1903 * dirty bitmaps.
1904 * Called with the ramlist lock held.
1906 static ram_addr_t find_ram_offset(ram_addr_t size)
1908 RAMBlock *block, *next_block;
1909 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1911 assert(size != 0); /* it would hand out same offset multiple times */
1913 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1914 return 0;
1917 RAMBLOCK_FOREACH(block) {
1918 ram_addr_t candidate, next = RAM_ADDR_MAX;
1920 /* Align blocks to start on a 'long' in the bitmap
1921 * which makes the bitmap sync'ing take the fast path.
1923 candidate = block->offset + block->max_length;
1924 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1926 /* Search for the closest following block
1927 * and find the gap.
1929 RAMBLOCK_FOREACH(next_block) {
1930 if (next_block->offset >= candidate) {
1931 next = MIN(next, next_block->offset);
1935 /* If it fits remember our place and remember the size
1936 * of gap, but keep going so that we might find a smaller
1937 * gap to fill so avoiding fragmentation.
1939 if (next - candidate >= size && next - candidate < mingap) {
1940 offset = candidate;
1941 mingap = next - candidate;
1944 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1947 if (offset == RAM_ADDR_MAX) {
1948 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1949 (uint64_t)size);
1950 abort();
1953 trace_find_ram_offset(size, offset);
1955 return offset;
1958 static unsigned long last_ram_page(void)
1960 RAMBlock *block;
1961 ram_addr_t last = 0;
1963 rcu_read_lock();
1964 RAMBLOCK_FOREACH(block) {
1965 last = MAX(last, block->offset + block->max_length);
1967 rcu_read_unlock();
1968 return last >> TARGET_PAGE_BITS;
1971 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1973 int ret;
1975 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1976 if (!machine_dump_guest_core(current_machine)) {
1977 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1978 if (ret) {
1979 perror("qemu_madvise");
1980 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1981 "but dump_guest_core=off specified\n");
1986 const char *qemu_ram_get_idstr(RAMBlock *rb)
1988 return rb->idstr;
1991 bool qemu_ram_is_shared(RAMBlock *rb)
1993 return rb->flags & RAM_SHARED;
1996 /* Note: Only set at the start of postcopy */
1997 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1999 return rb->flags & RAM_UF_ZEROPAGE;
2002 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
2004 rb->flags |= RAM_UF_ZEROPAGE;
2007 bool qemu_ram_is_migratable(RAMBlock *rb)
2009 return rb->flags & RAM_MIGRATABLE;
2012 void qemu_ram_set_migratable(RAMBlock *rb)
2014 rb->flags |= RAM_MIGRATABLE;
2017 void qemu_ram_unset_migratable(RAMBlock *rb)
2019 rb->flags &= ~RAM_MIGRATABLE;
2022 /* Called with iothread lock held. */
2023 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
2025 RAMBlock *block;
2027 assert(new_block);
2028 assert(!new_block->idstr[0]);
2030 if (dev) {
2031 char *id = qdev_get_dev_path(dev);
2032 if (id) {
2033 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
2034 g_free(id);
2037 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
2039 rcu_read_lock();
2040 RAMBLOCK_FOREACH(block) {
2041 if (block != new_block &&
2042 !strcmp(block->idstr, new_block->idstr)) {
2043 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
2044 new_block->idstr);
2045 abort();
2048 rcu_read_unlock();
2051 /* Called with iothread lock held. */
2052 void qemu_ram_unset_idstr(RAMBlock *block)
2054 /* FIXME: arch_init.c assumes that this is not called throughout
2055 * migration. Ignore the problem since hot-unplug during migration
2056 * does not work anyway.
2058 if (block) {
2059 memset(block->idstr, 0, sizeof(block->idstr));
2063 size_t qemu_ram_pagesize(RAMBlock *rb)
2065 return rb->page_size;
2068 /* Returns the largest size of page in use */
2069 size_t qemu_ram_pagesize_largest(void)
2071 RAMBlock *block;
2072 size_t largest = 0;
2074 RAMBLOCK_FOREACH(block) {
2075 largest = MAX(largest, qemu_ram_pagesize(block));
2078 return largest;
2081 static int memory_try_enable_merging(void *addr, size_t len)
2083 if (!machine_mem_merge(current_machine)) {
2084 /* disabled by the user */
2085 return 0;
2088 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
2091 /* Only legal before guest might have detected the memory size: e.g. on
2092 * incoming migration, or right after reset.
2094 * As memory core doesn't know how is memory accessed, it is up to
2095 * resize callback to update device state and/or add assertions to detect
2096 * misuse, if necessary.
2098 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
2100 assert(block);
2102 newsize = HOST_PAGE_ALIGN(newsize);
2104 if (block->used_length == newsize) {
2105 return 0;
2108 if (!(block->flags & RAM_RESIZEABLE)) {
2109 error_setg_errno(errp, EINVAL,
2110 "Length mismatch: %s: 0x" RAM_ADDR_FMT
2111 " in != 0x" RAM_ADDR_FMT, block->idstr,
2112 newsize, block->used_length);
2113 return -EINVAL;
2116 if (block->max_length < newsize) {
2117 error_setg_errno(errp, EINVAL,
2118 "Length too large: %s: 0x" RAM_ADDR_FMT
2119 " > 0x" RAM_ADDR_FMT, block->idstr,
2120 newsize, block->max_length);
2121 return -EINVAL;
2124 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
2125 block->used_length = newsize;
2126 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
2127 DIRTY_CLIENTS_ALL);
2128 memory_region_set_size(block->mr, newsize);
2129 if (block->resized) {
2130 block->resized(block->idstr, newsize, block->host);
2132 return 0;
2135 /* Called with ram_list.mutex held */
2136 static void dirty_memory_extend(ram_addr_t old_ram_size,
2137 ram_addr_t new_ram_size)
2139 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
2140 DIRTY_MEMORY_BLOCK_SIZE);
2141 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
2142 DIRTY_MEMORY_BLOCK_SIZE);
2143 int i;
2145 /* Only need to extend if block count increased */
2146 if (new_num_blocks <= old_num_blocks) {
2147 return;
2150 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
2151 DirtyMemoryBlocks *old_blocks;
2152 DirtyMemoryBlocks *new_blocks;
2153 int j;
2155 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
2156 new_blocks = g_malloc(sizeof(*new_blocks) +
2157 sizeof(new_blocks->blocks[0]) * new_num_blocks);
2159 if (old_num_blocks) {
2160 memcpy(new_blocks->blocks, old_blocks->blocks,
2161 old_num_blocks * sizeof(old_blocks->blocks[0]));
2164 for (j = old_num_blocks; j < new_num_blocks; j++) {
2165 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
2168 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
2170 if (old_blocks) {
2171 g_free_rcu(old_blocks, rcu);
2176 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
2178 RAMBlock *block;
2179 RAMBlock *last_block = NULL;
2180 ram_addr_t old_ram_size, new_ram_size;
2181 Error *err = NULL;
2183 old_ram_size = last_ram_page();
2185 qemu_mutex_lock_ramlist();
2186 new_block->offset = find_ram_offset(new_block->max_length);
2188 if (!new_block->host) {
2189 if (xen_enabled()) {
2190 xen_ram_alloc(new_block->offset, new_block->max_length,
2191 new_block->mr, &err);
2192 if (err) {
2193 error_propagate(errp, err);
2194 qemu_mutex_unlock_ramlist();
2195 return;
2197 } else {
2198 new_block->host = phys_mem_alloc(new_block->max_length,
2199 &new_block->mr->align, shared);
2200 if (!new_block->host) {
2201 error_setg_errno(errp, errno,
2202 "cannot set up guest memory '%s'",
2203 memory_region_name(new_block->mr));
2204 qemu_mutex_unlock_ramlist();
2205 return;
2207 memory_try_enable_merging(new_block->host, new_block->max_length);
2211 new_ram_size = MAX(old_ram_size,
2212 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
2213 if (new_ram_size > old_ram_size) {
2214 dirty_memory_extend(old_ram_size, new_ram_size);
2216 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2217 * QLIST (which has an RCU-friendly variant) does not have insertion at
2218 * tail, so save the last element in last_block.
2220 RAMBLOCK_FOREACH(block) {
2221 last_block = block;
2222 if (block->max_length < new_block->max_length) {
2223 break;
2226 if (block) {
2227 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
2228 } else if (last_block) {
2229 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
2230 } else { /* list is empty */
2231 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
2233 ram_list.mru_block = NULL;
2235 /* Write list before version */
2236 smp_wmb();
2237 ram_list.version++;
2238 qemu_mutex_unlock_ramlist();
2240 cpu_physical_memory_set_dirty_range(new_block->offset,
2241 new_block->used_length,
2242 DIRTY_CLIENTS_ALL);
2244 if (new_block->host) {
2245 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2246 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2247 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
2248 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
2249 ram_block_notify_add(new_block->host, new_block->max_length);
2253 #ifdef __linux__
2254 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2255 bool share, int fd,
2256 Error **errp)
2258 RAMBlock *new_block;
2259 Error *local_err = NULL;
2260 int64_t file_size;
2262 if (xen_enabled()) {
2263 error_setg(errp, "-mem-path not supported with Xen");
2264 return NULL;
2267 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2268 error_setg(errp,
2269 "host lacks kvm mmu notifiers, -mem-path unsupported");
2270 return NULL;
2273 if (phys_mem_alloc != qemu_anon_ram_alloc) {
2275 * file_ram_alloc() needs to allocate just like
2276 * phys_mem_alloc, but we haven't bothered to provide
2277 * a hook there.
2279 error_setg(errp,
2280 "-mem-path not supported with this accelerator");
2281 return NULL;
2284 size = HOST_PAGE_ALIGN(size);
2285 file_size = get_file_size(fd);
2286 if (file_size > 0 && file_size < size) {
2287 error_setg(errp, "backing store %s size 0x%" PRIx64
2288 " does not match 'size' option 0x" RAM_ADDR_FMT,
2289 mem_path, file_size, size);
2290 return NULL;
2293 new_block = g_malloc0(sizeof(*new_block));
2294 new_block->mr = mr;
2295 new_block->used_length = size;
2296 new_block->max_length = size;
2297 new_block->flags = share ? RAM_SHARED : 0;
2298 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
2299 if (!new_block->host) {
2300 g_free(new_block);
2301 return NULL;
2304 ram_block_add(new_block, &local_err, share);
2305 if (local_err) {
2306 g_free(new_block);
2307 error_propagate(errp, local_err);
2308 return NULL;
2310 return new_block;
2315 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2316 bool share, const char *mem_path,
2317 Error **errp)
2319 int fd;
2320 bool created;
2321 RAMBlock *block;
2323 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2324 if (fd < 0) {
2325 return NULL;
2328 block = qemu_ram_alloc_from_fd(size, mr, share, fd, errp);
2329 if (!block) {
2330 if (created) {
2331 unlink(mem_path);
2333 close(fd);
2334 return NULL;
2337 return block;
2339 #endif
2341 static
2342 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2343 void (*resized)(const char*,
2344 uint64_t length,
2345 void *host),
2346 void *host, bool resizeable, bool share,
2347 MemoryRegion *mr, Error **errp)
2349 RAMBlock *new_block;
2350 Error *local_err = NULL;
2352 size = HOST_PAGE_ALIGN(size);
2353 max_size = HOST_PAGE_ALIGN(max_size);
2354 new_block = g_malloc0(sizeof(*new_block));
2355 new_block->mr = mr;
2356 new_block->resized = resized;
2357 new_block->used_length = size;
2358 new_block->max_length = max_size;
2359 assert(max_size >= size);
2360 new_block->fd = -1;
2361 new_block->page_size = getpagesize();
2362 new_block->host = host;
2363 if (host) {
2364 new_block->flags |= RAM_PREALLOC;
2366 if (resizeable) {
2367 new_block->flags |= RAM_RESIZEABLE;
2369 ram_block_add(new_block, &local_err, share);
2370 if (local_err) {
2371 g_free(new_block);
2372 error_propagate(errp, local_err);
2373 return NULL;
2375 return new_block;
2378 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2379 MemoryRegion *mr, Error **errp)
2381 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2382 false, mr, errp);
2385 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2386 MemoryRegion *mr, Error **errp)
2388 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2389 share, mr, errp);
2392 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2393 void (*resized)(const char*,
2394 uint64_t length,
2395 void *host),
2396 MemoryRegion *mr, Error **errp)
2398 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2399 false, mr, errp);
2402 static void reclaim_ramblock(RAMBlock *block)
2404 if (block->flags & RAM_PREALLOC) {
2406 } else if (xen_enabled()) {
2407 xen_invalidate_map_cache_entry(block->host);
2408 #ifndef _WIN32
2409 } else if (block->fd >= 0) {
2410 qemu_ram_munmap(block->host, block->max_length);
2411 close(block->fd);
2412 #endif
2413 } else {
2414 qemu_anon_ram_free(block->host, block->max_length);
2416 g_free(block);
2419 void qemu_ram_free(RAMBlock *block)
2421 if (!block) {
2422 return;
2425 if (block->host) {
2426 ram_block_notify_remove(block->host, block->max_length);
2429 qemu_mutex_lock_ramlist();
2430 QLIST_REMOVE_RCU(block, next);
2431 ram_list.mru_block = NULL;
2432 /* Write list before version */
2433 smp_wmb();
2434 ram_list.version++;
2435 call_rcu(block, reclaim_ramblock, rcu);
2436 qemu_mutex_unlock_ramlist();
2439 #ifndef _WIN32
2440 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2442 RAMBlock *block;
2443 ram_addr_t offset;
2444 int flags;
2445 void *area, *vaddr;
2447 RAMBLOCK_FOREACH(block) {
2448 offset = addr - block->offset;
2449 if (offset < block->max_length) {
2450 vaddr = ramblock_ptr(block, offset);
2451 if (block->flags & RAM_PREALLOC) {
2453 } else if (xen_enabled()) {
2454 abort();
2455 } else {
2456 flags = MAP_FIXED;
2457 if (block->fd >= 0) {
2458 flags |= (block->flags & RAM_SHARED ?
2459 MAP_SHARED : MAP_PRIVATE);
2460 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2461 flags, block->fd, offset);
2462 } else {
2464 * Remap needs to match alloc. Accelerators that
2465 * set phys_mem_alloc never remap. If they did,
2466 * we'd need a remap hook here.
2468 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2470 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2471 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2472 flags, -1, 0);
2474 if (area != vaddr) {
2475 error_report("Could not remap addr: "
2476 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2477 length, addr);
2478 exit(1);
2480 memory_try_enable_merging(vaddr, length);
2481 qemu_ram_setup_dump(vaddr, length);
2486 #endif /* !_WIN32 */
2488 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2489 * This should not be used for general purpose DMA. Use address_space_map
2490 * or address_space_rw instead. For local memory (e.g. video ram) that the
2491 * device owns, use memory_region_get_ram_ptr.
2493 * Called within RCU critical section.
2495 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2497 RAMBlock *block = ram_block;
2499 if (block == NULL) {
2500 block = qemu_get_ram_block(addr);
2501 addr -= block->offset;
2504 if (xen_enabled() && block->host == NULL) {
2505 /* We need to check if the requested address is in the RAM
2506 * because we don't want to map the entire memory in QEMU.
2507 * In that case just map until the end of the page.
2509 if (block->offset == 0) {
2510 return xen_map_cache(addr, 0, 0, false);
2513 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2515 return ramblock_ptr(block, addr);
2518 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2519 * but takes a size argument.
2521 * Called within RCU critical section.
2523 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2524 hwaddr *size, bool lock)
2526 RAMBlock *block = ram_block;
2527 if (*size == 0) {
2528 return NULL;
2531 if (block == NULL) {
2532 block = qemu_get_ram_block(addr);
2533 addr -= block->offset;
2535 *size = MIN(*size, block->max_length - addr);
2537 if (xen_enabled() && block->host == NULL) {
2538 /* We need to check if the requested address is in the RAM
2539 * because we don't want to map the entire memory in QEMU.
2540 * In that case just map the requested area.
2542 if (block->offset == 0) {
2543 return xen_map_cache(addr, *size, lock, lock);
2546 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2549 return ramblock_ptr(block, addr);
2552 /* Return the offset of a hostpointer within a ramblock */
2553 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2555 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2556 assert((uintptr_t)host >= (uintptr_t)rb->host);
2557 assert(res < rb->max_length);
2559 return res;
2563 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2564 * in that RAMBlock.
2566 * ptr: Host pointer to look up
2567 * round_offset: If true round the result offset down to a page boundary
2568 * *ram_addr: set to result ram_addr
2569 * *offset: set to result offset within the RAMBlock
2571 * Returns: RAMBlock (or NULL if not found)
2573 * By the time this function returns, the returned pointer is not protected
2574 * by RCU anymore. If the caller is not within an RCU critical section and
2575 * does not hold the iothread lock, it must have other means of protecting the
2576 * pointer, such as a reference to the region that includes the incoming
2577 * ram_addr_t.
2579 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2580 ram_addr_t *offset)
2582 RAMBlock *block;
2583 uint8_t *host = ptr;
2585 if (xen_enabled()) {
2586 ram_addr_t ram_addr;
2587 rcu_read_lock();
2588 ram_addr = xen_ram_addr_from_mapcache(ptr);
2589 block = qemu_get_ram_block(ram_addr);
2590 if (block) {
2591 *offset = ram_addr - block->offset;
2593 rcu_read_unlock();
2594 return block;
2597 rcu_read_lock();
2598 block = atomic_rcu_read(&ram_list.mru_block);
2599 if (block && block->host && host - block->host < block->max_length) {
2600 goto found;
2603 RAMBLOCK_FOREACH(block) {
2604 /* This case append when the block is not mapped. */
2605 if (block->host == NULL) {
2606 continue;
2608 if (host - block->host < block->max_length) {
2609 goto found;
2613 rcu_read_unlock();
2614 return NULL;
2616 found:
2617 *offset = (host - block->host);
2618 if (round_offset) {
2619 *offset &= TARGET_PAGE_MASK;
2621 rcu_read_unlock();
2622 return block;
2626 * Finds the named RAMBlock
2628 * name: The name of RAMBlock to find
2630 * Returns: RAMBlock (or NULL if not found)
2632 RAMBlock *qemu_ram_block_by_name(const char *name)
2634 RAMBlock *block;
2636 RAMBLOCK_FOREACH(block) {
2637 if (!strcmp(name, block->idstr)) {
2638 return block;
2642 return NULL;
2645 /* Some of the softmmu routines need to translate from a host pointer
2646 (typically a TLB entry) back to a ram offset. */
2647 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2649 RAMBlock *block;
2650 ram_addr_t offset;
2652 block = qemu_ram_block_from_host(ptr, false, &offset);
2653 if (!block) {
2654 return RAM_ADDR_INVALID;
2657 return block->offset + offset;
2660 /* Called within RCU critical section. */
2661 void memory_notdirty_write_prepare(NotDirtyInfo *ndi,
2662 CPUState *cpu,
2663 vaddr mem_vaddr,
2664 ram_addr_t ram_addr,
2665 unsigned size)
2667 ndi->cpu = cpu;
2668 ndi->ram_addr = ram_addr;
2669 ndi->mem_vaddr = mem_vaddr;
2670 ndi->size = size;
2671 ndi->pages = NULL;
2673 assert(tcg_enabled());
2674 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
2675 ndi->pages = page_collection_lock(ram_addr, ram_addr + size);
2676 tb_invalidate_phys_page_fast(ndi->pages, ram_addr, size);
2680 /* Called within RCU critical section. */
2681 void memory_notdirty_write_complete(NotDirtyInfo *ndi)
2683 if (ndi->pages) {
2684 assert(tcg_enabled());
2685 page_collection_unlock(ndi->pages);
2686 ndi->pages = NULL;
2689 /* Set both VGA and migration bits for simplicity and to remove
2690 * the notdirty callback faster.
2692 cpu_physical_memory_set_dirty_range(ndi->ram_addr, ndi->size,
2693 DIRTY_CLIENTS_NOCODE);
2694 /* we remove the notdirty callback only if the code has been
2695 flushed */
2696 if (!cpu_physical_memory_is_clean(ndi->ram_addr)) {
2697 tlb_set_dirty(ndi->cpu, ndi->mem_vaddr);
2701 /* Called within RCU critical section. */
2702 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2703 uint64_t val, unsigned size)
2705 NotDirtyInfo ndi;
2707 memory_notdirty_write_prepare(&ndi, current_cpu, current_cpu->mem_io_vaddr,
2708 ram_addr, size);
2710 stn_p(qemu_map_ram_ptr(NULL, ram_addr), size, val);
2711 memory_notdirty_write_complete(&ndi);
2714 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
2715 unsigned size, bool is_write,
2716 MemTxAttrs attrs)
2718 return is_write;
2721 static const MemoryRegionOps notdirty_mem_ops = {
2722 .write = notdirty_mem_write,
2723 .valid.accepts = notdirty_mem_accepts,
2724 .endianness = DEVICE_NATIVE_ENDIAN,
2725 .valid = {
2726 .min_access_size = 1,
2727 .max_access_size = 8,
2728 .unaligned = false,
2730 .impl = {
2731 .min_access_size = 1,
2732 .max_access_size = 8,
2733 .unaligned = false,
2737 /* Generate a debug exception if a watchpoint has been hit. */
2738 static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
2740 CPUState *cpu = current_cpu;
2741 CPUClass *cc = CPU_GET_CLASS(cpu);
2742 target_ulong vaddr;
2743 CPUWatchpoint *wp;
2745 assert(tcg_enabled());
2746 if (cpu->watchpoint_hit) {
2747 /* We re-entered the check after replacing the TB. Now raise
2748 * the debug interrupt so that is will trigger after the
2749 * current instruction. */
2750 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2751 return;
2753 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
2754 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
2755 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2756 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2757 && (wp->flags & flags)) {
2758 if (flags == BP_MEM_READ) {
2759 wp->flags |= BP_WATCHPOINT_HIT_READ;
2760 } else {
2761 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2763 wp->hitaddr = vaddr;
2764 wp->hitattrs = attrs;
2765 if (!cpu->watchpoint_hit) {
2766 if (wp->flags & BP_CPU &&
2767 !cc->debug_check_watchpoint(cpu, wp)) {
2768 wp->flags &= ~BP_WATCHPOINT_HIT;
2769 continue;
2771 cpu->watchpoint_hit = wp;
2773 mmap_lock();
2774 tb_check_watchpoint(cpu);
2775 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2776 cpu->exception_index = EXCP_DEBUG;
2777 mmap_unlock();
2778 cpu_loop_exit(cpu);
2779 } else {
2780 /* Force execution of one insn next time. */
2781 cpu->cflags_next_tb = 1 | curr_cflags();
2782 mmap_unlock();
2783 cpu_loop_exit_noexc(cpu);
2786 } else {
2787 wp->flags &= ~BP_WATCHPOINT_HIT;
2792 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2793 so these check for a hit then pass through to the normal out-of-line
2794 phys routines. */
2795 static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2796 unsigned size, MemTxAttrs attrs)
2798 MemTxResult res;
2799 uint64_t data;
2800 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2801 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2803 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2804 switch (size) {
2805 case 1:
2806 data = address_space_ldub(as, addr, attrs, &res);
2807 break;
2808 case 2:
2809 data = address_space_lduw(as, addr, attrs, &res);
2810 break;
2811 case 4:
2812 data = address_space_ldl(as, addr, attrs, &res);
2813 break;
2814 case 8:
2815 data = address_space_ldq(as, addr, attrs, &res);
2816 break;
2817 default: abort();
2819 *pdata = data;
2820 return res;
2823 static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2824 uint64_t val, unsigned size,
2825 MemTxAttrs attrs)
2827 MemTxResult res;
2828 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2829 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2831 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2832 switch (size) {
2833 case 1:
2834 address_space_stb(as, addr, val, attrs, &res);
2835 break;
2836 case 2:
2837 address_space_stw(as, addr, val, attrs, &res);
2838 break;
2839 case 4:
2840 address_space_stl(as, addr, val, attrs, &res);
2841 break;
2842 case 8:
2843 address_space_stq(as, addr, val, attrs, &res);
2844 break;
2845 default: abort();
2847 return res;
2850 static const MemoryRegionOps watch_mem_ops = {
2851 .read_with_attrs = watch_mem_read,
2852 .write_with_attrs = watch_mem_write,
2853 .endianness = DEVICE_NATIVE_ENDIAN,
2854 .valid = {
2855 .min_access_size = 1,
2856 .max_access_size = 8,
2857 .unaligned = false,
2859 .impl = {
2860 .min_access_size = 1,
2861 .max_access_size = 8,
2862 .unaligned = false,
2866 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2867 MemTxAttrs attrs, uint8_t *buf, int len);
2868 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2869 const uint8_t *buf, int len);
2870 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
2871 bool is_write, MemTxAttrs attrs);
2873 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2874 unsigned len, MemTxAttrs attrs)
2876 subpage_t *subpage = opaque;
2877 uint8_t buf[8];
2878 MemTxResult res;
2880 #if defined(DEBUG_SUBPAGE)
2881 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2882 subpage, len, addr);
2883 #endif
2884 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2885 if (res) {
2886 return res;
2888 *data = ldn_p(buf, len);
2889 return MEMTX_OK;
2892 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2893 uint64_t value, unsigned len, MemTxAttrs attrs)
2895 subpage_t *subpage = opaque;
2896 uint8_t buf[8];
2898 #if defined(DEBUG_SUBPAGE)
2899 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2900 " value %"PRIx64"\n",
2901 __func__, subpage, len, addr, value);
2902 #endif
2903 stn_p(buf, len, value);
2904 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2907 static bool subpage_accepts(void *opaque, hwaddr addr,
2908 unsigned len, bool is_write,
2909 MemTxAttrs attrs)
2911 subpage_t *subpage = opaque;
2912 #if defined(DEBUG_SUBPAGE)
2913 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2914 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2915 #endif
2917 return flatview_access_valid(subpage->fv, addr + subpage->base,
2918 len, is_write, attrs);
2921 static const MemoryRegionOps subpage_ops = {
2922 .read_with_attrs = subpage_read,
2923 .write_with_attrs = subpage_write,
2924 .impl.min_access_size = 1,
2925 .impl.max_access_size = 8,
2926 .valid.min_access_size = 1,
2927 .valid.max_access_size = 8,
2928 .valid.accepts = subpage_accepts,
2929 .endianness = DEVICE_NATIVE_ENDIAN,
2932 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
2933 uint16_t section)
2935 int idx, eidx;
2937 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2938 return -1;
2939 idx = SUBPAGE_IDX(start);
2940 eidx = SUBPAGE_IDX(end);
2941 #if defined(DEBUG_SUBPAGE)
2942 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2943 __func__, mmio, start, end, idx, eidx, section);
2944 #endif
2945 for (; idx <= eidx; idx++) {
2946 mmio->sub_section[idx] = section;
2949 return 0;
2952 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2954 subpage_t *mmio;
2956 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2957 mmio->fv = fv;
2958 mmio->base = base;
2959 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2960 NULL, TARGET_PAGE_SIZE);
2961 mmio->iomem.subpage = true;
2962 #if defined(DEBUG_SUBPAGE)
2963 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2964 mmio, base, TARGET_PAGE_SIZE);
2965 #endif
2966 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
2968 return mmio;
2971 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2973 assert(fv);
2974 MemoryRegionSection section = {
2975 .fv = fv,
2976 .mr = mr,
2977 .offset_within_address_space = 0,
2978 .offset_within_region = 0,
2979 .size = int128_2_64(),
2982 return phys_section_add(map, &section);
2985 static void readonly_mem_write(void *opaque, hwaddr addr,
2986 uint64_t val, unsigned size)
2988 /* Ignore any write to ROM. */
2991 static bool readonly_mem_accepts(void *opaque, hwaddr addr,
2992 unsigned size, bool is_write,
2993 MemTxAttrs attrs)
2995 return is_write;
2998 /* This will only be used for writes, because reads are special cased
2999 * to directly access the underlying host ram.
3001 static const MemoryRegionOps readonly_mem_ops = {
3002 .write = readonly_mem_write,
3003 .valid.accepts = readonly_mem_accepts,
3004 .endianness = DEVICE_NATIVE_ENDIAN,
3005 .valid = {
3006 .min_access_size = 1,
3007 .max_access_size = 8,
3008 .unaligned = false,
3010 .impl = {
3011 .min_access_size = 1,
3012 .max_access_size = 8,
3013 .unaligned = false,
3017 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
3018 hwaddr index, MemTxAttrs attrs)
3020 int asidx = cpu_asidx_from_attrs(cpu, attrs);
3021 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
3022 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
3023 MemoryRegionSection *sections = d->map.sections;
3025 return &sections[index & ~TARGET_PAGE_MASK];
3028 static void io_mem_init(void)
3030 memory_region_init_io(&io_mem_rom, NULL, &readonly_mem_ops,
3031 NULL, NULL, UINT64_MAX);
3032 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
3033 NULL, UINT64_MAX);
3035 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
3036 * which can be called without the iothread mutex.
3038 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
3039 NULL, UINT64_MAX);
3040 memory_region_clear_global_locking(&io_mem_notdirty);
3042 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
3043 NULL, UINT64_MAX);
3046 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
3048 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
3049 uint16_t n;
3051 n = dummy_section(&d->map, fv, &io_mem_unassigned);
3052 assert(n == PHYS_SECTION_UNASSIGNED);
3053 n = dummy_section(&d->map, fv, &io_mem_notdirty);
3054 assert(n == PHYS_SECTION_NOTDIRTY);
3055 n = dummy_section(&d->map, fv, &io_mem_rom);
3056 assert(n == PHYS_SECTION_ROM);
3057 n = dummy_section(&d->map, fv, &io_mem_watch);
3058 assert(n == PHYS_SECTION_WATCH);
3060 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
3062 return d;
3065 void address_space_dispatch_free(AddressSpaceDispatch *d)
3067 phys_sections_free(&d->map);
3068 g_free(d);
3071 static void tcg_commit(MemoryListener *listener)
3073 CPUAddressSpace *cpuas;
3074 AddressSpaceDispatch *d;
3076 assert(tcg_enabled());
3077 /* since each CPU stores ram addresses in its TLB cache, we must
3078 reset the modified entries */
3079 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
3080 cpu_reloading_memory_map();
3081 /* The CPU and TLB are protected by the iothread lock.
3082 * We reload the dispatch pointer now because cpu_reloading_memory_map()
3083 * may have split the RCU critical section.
3085 d = address_space_to_dispatch(cpuas->as);
3086 atomic_rcu_set(&cpuas->memory_dispatch, d);
3087 tlb_flush(cpuas->cpu);
3090 static void memory_map_init(void)
3092 system_memory = g_malloc(sizeof(*system_memory));
3094 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
3095 address_space_init(&address_space_memory, system_memory, "memory");
3097 system_io = g_malloc(sizeof(*system_io));
3098 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
3099 65536);
3100 address_space_init(&address_space_io, system_io, "I/O");
3103 MemoryRegion *get_system_memory(void)
3105 return system_memory;
3108 MemoryRegion *get_system_io(void)
3110 return system_io;
3113 #endif /* !defined(CONFIG_USER_ONLY) */
3115 /* physical memory access (slow version, mainly for debug) */
3116 #if defined(CONFIG_USER_ONLY)
3117 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3118 uint8_t *buf, int len, int is_write)
3120 int l, flags;
3121 target_ulong page;
3122 void * p;
3124 while (len > 0) {
3125 page = addr & TARGET_PAGE_MASK;
3126 l = (page + TARGET_PAGE_SIZE) - addr;
3127 if (l > len)
3128 l = len;
3129 flags = page_get_flags(page);
3130 if (!(flags & PAGE_VALID))
3131 return -1;
3132 if (is_write) {
3133 if (!(flags & PAGE_WRITE))
3134 return -1;
3135 /* XXX: this code should not depend on lock_user */
3136 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
3137 return -1;
3138 memcpy(p, buf, l);
3139 unlock_user(p, addr, l);
3140 } else {
3141 if (!(flags & PAGE_READ))
3142 return -1;
3143 /* XXX: this code should not depend on lock_user */
3144 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
3145 return -1;
3146 memcpy(buf, p, l);
3147 unlock_user(p, addr, 0);
3149 len -= l;
3150 buf += l;
3151 addr += l;
3153 return 0;
3156 #else
3158 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
3159 hwaddr length)
3161 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
3162 addr += memory_region_get_ram_addr(mr);
3164 /* No early return if dirty_log_mask is or becomes 0, because
3165 * cpu_physical_memory_set_dirty_range will still call
3166 * xen_modified_memory.
3168 if (dirty_log_mask) {
3169 dirty_log_mask =
3170 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
3172 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
3173 assert(tcg_enabled());
3174 tb_invalidate_phys_range(addr, addr + length);
3175 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
3177 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
3180 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
3182 unsigned access_size_max = mr->ops->valid.max_access_size;
3184 /* Regions are assumed to support 1-4 byte accesses unless
3185 otherwise specified. */
3186 if (access_size_max == 0) {
3187 access_size_max = 4;
3190 /* Bound the maximum access by the alignment of the address. */
3191 if (!mr->ops->impl.unaligned) {
3192 unsigned align_size_max = addr & -addr;
3193 if (align_size_max != 0 && align_size_max < access_size_max) {
3194 access_size_max = align_size_max;
3198 /* Don't attempt accesses larger than the maximum. */
3199 if (l > access_size_max) {
3200 l = access_size_max;
3202 l = pow2floor(l);
3204 return l;
3207 static bool prepare_mmio_access(MemoryRegion *mr)
3209 bool unlocked = !qemu_mutex_iothread_locked();
3210 bool release_lock = false;
3212 if (unlocked && mr->global_locking) {
3213 qemu_mutex_lock_iothread();
3214 unlocked = false;
3215 release_lock = true;
3217 if (mr->flush_coalesced_mmio) {
3218 if (unlocked) {
3219 qemu_mutex_lock_iothread();
3221 qemu_flush_coalesced_mmio_buffer();
3222 if (unlocked) {
3223 qemu_mutex_unlock_iothread();
3227 return release_lock;
3230 /* Called within RCU critical section. */
3231 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
3232 MemTxAttrs attrs,
3233 const uint8_t *buf,
3234 int len, hwaddr addr1,
3235 hwaddr l, MemoryRegion *mr)
3237 uint8_t *ptr;
3238 uint64_t val;
3239 MemTxResult result = MEMTX_OK;
3240 bool release_lock = false;
3242 for (;;) {
3243 if (!memory_access_is_direct(mr, true)) {
3244 release_lock |= prepare_mmio_access(mr);
3245 l = memory_access_size(mr, l, addr1);
3246 /* XXX: could force current_cpu to NULL to avoid
3247 potential bugs */
3248 val = ldn_p(buf, l);
3249 result |= memory_region_dispatch_write(mr, addr1, val, l, attrs);
3250 } else {
3251 /* RAM case */
3252 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3253 memcpy(ptr, buf, l);
3254 invalidate_and_set_dirty(mr, addr1, l);
3257 if (release_lock) {
3258 qemu_mutex_unlock_iothread();
3259 release_lock = false;
3262 len -= l;
3263 buf += l;
3264 addr += l;
3266 if (!len) {
3267 break;
3270 l = len;
3271 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
3274 return result;
3277 /* Called from RCU critical section. */
3278 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
3279 const uint8_t *buf, int len)
3281 hwaddr l;
3282 hwaddr addr1;
3283 MemoryRegion *mr;
3284 MemTxResult result = MEMTX_OK;
3286 l = len;
3287 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
3288 result = flatview_write_continue(fv, addr, attrs, buf, len,
3289 addr1, l, mr);
3291 return result;
3294 /* Called within RCU critical section. */
3295 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
3296 MemTxAttrs attrs, uint8_t *buf,
3297 int len, hwaddr addr1, hwaddr l,
3298 MemoryRegion *mr)
3300 uint8_t *ptr;
3301 uint64_t val;
3302 MemTxResult result = MEMTX_OK;
3303 bool release_lock = false;
3305 for (;;) {
3306 if (!memory_access_is_direct(mr, false)) {
3307 /* I/O case */
3308 release_lock |= prepare_mmio_access(mr);
3309 l = memory_access_size(mr, l, addr1);
3310 result |= memory_region_dispatch_read(mr, addr1, &val, l, attrs);
3311 stn_p(buf, l, val);
3312 } else {
3313 /* RAM case */
3314 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3315 memcpy(buf, ptr, l);
3318 if (release_lock) {
3319 qemu_mutex_unlock_iothread();
3320 release_lock = false;
3323 len -= l;
3324 buf += l;
3325 addr += l;
3327 if (!len) {
3328 break;
3331 l = len;
3332 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3335 return result;
3338 /* Called from RCU critical section. */
3339 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
3340 MemTxAttrs attrs, uint8_t *buf, int len)
3342 hwaddr l;
3343 hwaddr addr1;
3344 MemoryRegion *mr;
3346 l = len;
3347 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3348 return flatview_read_continue(fv, addr, attrs, buf, len,
3349 addr1, l, mr);
3352 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3353 MemTxAttrs attrs, uint8_t *buf, int len)
3355 MemTxResult result = MEMTX_OK;
3356 FlatView *fv;
3358 if (len > 0) {
3359 rcu_read_lock();
3360 fv = address_space_to_flatview(as);
3361 result = flatview_read(fv, addr, attrs, buf, len);
3362 rcu_read_unlock();
3365 return result;
3368 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
3369 MemTxAttrs attrs,
3370 const uint8_t *buf, int len)
3372 MemTxResult result = MEMTX_OK;
3373 FlatView *fv;
3375 if (len > 0) {
3376 rcu_read_lock();
3377 fv = address_space_to_flatview(as);
3378 result = flatview_write(fv, addr, attrs, buf, len);
3379 rcu_read_unlock();
3382 return result;
3385 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3386 uint8_t *buf, int len, bool is_write)
3388 if (is_write) {
3389 return address_space_write(as, addr, attrs, buf, len);
3390 } else {
3391 return address_space_read_full(as, addr, attrs, buf, len);
3395 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
3396 int len, int is_write)
3398 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3399 buf, len, is_write);
3402 enum write_rom_type {
3403 WRITE_DATA,
3404 FLUSH_CACHE,
3407 static inline void cpu_physical_memory_write_rom_internal(AddressSpace *as,
3408 hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
3410 hwaddr l;
3411 uint8_t *ptr;
3412 hwaddr addr1;
3413 MemoryRegion *mr;
3415 rcu_read_lock();
3416 while (len > 0) {
3417 l = len;
3418 mr = address_space_translate(as, addr, &addr1, &l, true,
3419 MEMTXATTRS_UNSPECIFIED);
3421 if (!(memory_region_is_ram(mr) ||
3422 memory_region_is_romd(mr))) {
3423 l = memory_access_size(mr, l, addr1);
3424 } else {
3425 /* ROM/RAM case */
3426 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3427 switch (type) {
3428 case WRITE_DATA:
3429 memcpy(ptr, buf, l);
3430 invalidate_and_set_dirty(mr, addr1, l);
3431 break;
3432 case FLUSH_CACHE:
3433 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
3434 break;
3437 len -= l;
3438 buf += l;
3439 addr += l;
3441 rcu_read_unlock();
3444 /* used for ROM loading : can write in RAM and ROM */
3445 void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
3446 const uint8_t *buf, int len)
3448 cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
3451 void cpu_flush_icache_range(hwaddr start, int len)
3454 * This function should do the same thing as an icache flush that was
3455 * triggered from within the guest. For TCG we are always cache coherent,
3456 * so there is no need to flush anything. For KVM / Xen we need to flush
3457 * the host's instruction cache at least.
3459 if (tcg_enabled()) {
3460 return;
3463 cpu_physical_memory_write_rom_internal(&address_space_memory,
3464 start, NULL, len, FLUSH_CACHE);
3467 typedef struct {
3468 MemoryRegion *mr;
3469 void *buffer;
3470 hwaddr addr;
3471 hwaddr len;
3472 bool in_use;
3473 } BounceBuffer;
3475 static BounceBuffer bounce;
3477 typedef struct MapClient {
3478 QEMUBH *bh;
3479 QLIST_ENTRY(MapClient) link;
3480 } MapClient;
3482 QemuMutex map_client_list_lock;
3483 static QLIST_HEAD(map_client_list, MapClient) map_client_list
3484 = QLIST_HEAD_INITIALIZER(map_client_list);
3486 static void cpu_unregister_map_client_do(MapClient *client)
3488 QLIST_REMOVE(client, link);
3489 g_free(client);
3492 static void cpu_notify_map_clients_locked(void)
3494 MapClient *client;
3496 while (!QLIST_EMPTY(&map_client_list)) {
3497 client = QLIST_FIRST(&map_client_list);
3498 qemu_bh_schedule(client->bh);
3499 cpu_unregister_map_client_do(client);
3503 void cpu_register_map_client(QEMUBH *bh)
3505 MapClient *client = g_malloc(sizeof(*client));
3507 qemu_mutex_lock(&map_client_list_lock);
3508 client->bh = bh;
3509 QLIST_INSERT_HEAD(&map_client_list, client, link);
3510 if (!atomic_read(&bounce.in_use)) {
3511 cpu_notify_map_clients_locked();
3513 qemu_mutex_unlock(&map_client_list_lock);
3516 void cpu_exec_init_all(void)
3518 qemu_mutex_init(&ram_list.mutex);
3519 /* The data structures we set up here depend on knowing the page size,
3520 * so no more changes can be made after this point.
3521 * In an ideal world, nothing we did before we had finished the
3522 * machine setup would care about the target page size, and we could
3523 * do this much later, rather than requiring board models to state
3524 * up front what their requirements are.
3526 finalize_target_page_bits();
3527 io_mem_init();
3528 memory_map_init();
3529 qemu_mutex_init(&map_client_list_lock);
3532 void cpu_unregister_map_client(QEMUBH *bh)
3534 MapClient *client;
3536 qemu_mutex_lock(&map_client_list_lock);
3537 QLIST_FOREACH(client, &map_client_list, link) {
3538 if (client->bh == bh) {
3539 cpu_unregister_map_client_do(client);
3540 break;
3543 qemu_mutex_unlock(&map_client_list_lock);
3546 static void cpu_notify_map_clients(void)
3548 qemu_mutex_lock(&map_client_list_lock);
3549 cpu_notify_map_clients_locked();
3550 qemu_mutex_unlock(&map_client_list_lock);
3553 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
3554 bool is_write, MemTxAttrs attrs)
3556 MemoryRegion *mr;
3557 hwaddr l, xlat;
3559 while (len > 0) {
3560 l = len;
3561 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3562 if (!memory_access_is_direct(mr, is_write)) {
3563 l = memory_access_size(mr, l, addr);
3564 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3565 return false;
3569 len -= l;
3570 addr += l;
3572 return true;
3575 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3576 int len, bool is_write,
3577 MemTxAttrs attrs)
3579 FlatView *fv;
3580 bool result;
3582 rcu_read_lock();
3583 fv = address_space_to_flatview(as);
3584 result = flatview_access_valid(fv, addr, len, is_write, attrs);
3585 rcu_read_unlock();
3586 return result;
3589 static hwaddr
3590 flatview_extend_translation(FlatView *fv, hwaddr addr,
3591 hwaddr target_len,
3592 MemoryRegion *mr, hwaddr base, hwaddr len,
3593 bool is_write, MemTxAttrs attrs)
3595 hwaddr done = 0;
3596 hwaddr xlat;
3597 MemoryRegion *this_mr;
3599 for (;;) {
3600 target_len -= len;
3601 addr += len;
3602 done += len;
3603 if (target_len == 0) {
3604 return done;
3607 len = target_len;
3608 this_mr = flatview_translate(fv, addr, &xlat,
3609 &len, is_write, attrs);
3610 if (this_mr != mr || xlat != base + done) {
3611 return done;
3616 /* Map a physical memory region into a host virtual address.
3617 * May map a subset of the requested range, given by and returned in *plen.
3618 * May return NULL if resources needed to perform the mapping are exhausted.
3619 * Use only for reads OR writes - not for read-modify-write operations.
3620 * Use cpu_register_map_client() to know when retrying the map operation is
3621 * likely to succeed.
3623 void *address_space_map(AddressSpace *as,
3624 hwaddr addr,
3625 hwaddr *plen,
3626 bool is_write,
3627 MemTxAttrs attrs)
3629 hwaddr len = *plen;
3630 hwaddr l, xlat;
3631 MemoryRegion *mr;
3632 void *ptr;
3633 FlatView *fv;
3635 if (len == 0) {
3636 return NULL;
3639 l = len;
3640 rcu_read_lock();
3641 fv = address_space_to_flatview(as);
3642 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3644 if (!memory_access_is_direct(mr, is_write)) {
3645 if (atomic_xchg(&bounce.in_use, true)) {
3646 rcu_read_unlock();
3647 return NULL;
3649 /* Avoid unbounded allocations */
3650 l = MIN(l, TARGET_PAGE_SIZE);
3651 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3652 bounce.addr = addr;
3653 bounce.len = l;
3655 memory_region_ref(mr);
3656 bounce.mr = mr;
3657 if (!is_write) {
3658 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3659 bounce.buffer, l);
3662 rcu_read_unlock();
3663 *plen = l;
3664 return bounce.buffer;
3668 memory_region_ref(mr);
3669 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3670 l, is_write, attrs);
3671 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3672 rcu_read_unlock();
3674 return ptr;
3677 /* Unmaps a memory region previously mapped by address_space_map().
3678 * Will also mark the memory as dirty if is_write == 1. access_len gives
3679 * the amount of memory that was actually read or written by the caller.
3681 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3682 int is_write, hwaddr access_len)
3684 if (buffer != bounce.buffer) {
3685 MemoryRegion *mr;
3686 ram_addr_t addr1;
3688 mr = memory_region_from_host(buffer, &addr1);
3689 assert(mr != NULL);
3690 if (is_write) {
3691 invalidate_and_set_dirty(mr, addr1, access_len);
3693 if (xen_enabled()) {
3694 xen_invalidate_map_cache_entry(buffer);
3696 memory_region_unref(mr);
3697 return;
3699 if (is_write) {
3700 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3701 bounce.buffer, access_len);
3703 qemu_vfree(bounce.buffer);
3704 bounce.buffer = NULL;
3705 memory_region_unref(bounce.mr);
3706 atomic_mb_set(&bounce.in_use, false);
3707 cpu_notify_map_clients();
3710 void *cpu_physical_memory_map(hwaddr addr,
3711 hwaddr *plen,
3712 int is_write)
3714 return address_space_map(&address_space_memory, addr, plen, is_write,
3715 MEMTXATTRS_UNSPECIFIED);
3718 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3719 int is_write, hwaddr access_len)
3721 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3724 #define ARG1_DECL AddressSpace *as
3725 #define ARG1 as
3726 #define SUFFIX
3727 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3728 #define RCU_READ_LOCK(...) rcu_read_lock()
3729 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3730 #include "memory_ldst.inc.c"
3732 int64_t address_space_cache_init(MemoryRegionCache *cache,
3733 AddressSpace *as,
3734 hwaddr addr,
3735 hwaddr len,
3736 bool is_write)
3738 AddressSpaceDispatch *d;
3739 hwaddr l;
3740 MemoryRegion *mr;
3742 assert(len > 0);
3744 l = len;
3745 cache->fv = address_space_get_flatview(as);
3746 d = flatview_to_dispatch(cache->fv);
3747 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3749 mr = cache->mrs.mr;
3750 memory_region_ref(mr);
3751 if (memory_access_is_direct(mr, is_write)) {
3752 /* We don't care about the memory attributes here as we're only
3753 * doing this if we found actual RAM, which behaves the same
3754 * regardless of attributes; so UNSPECIFIED is fine.
3756 l = flatview_extend_translation(cache->fv, addr, len, mr,
3757 cache->xlat, l, is_write,
3758 MEMTXATTRS_UNSPECIFIED);
3759 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3760 } else {
3761 cache->ptr = NULL;
3764 cache->len = l;
3765 cache->is_write = is_write;
3766 return l;
3769 void address_space_cache_invalidate(MemoryRegionCache *cache,
3770 hwaddr addr,
3771 hwaddr access_len)
3773 assert(cache->is_write);
3774 if (likely(cache->ptr)) {
3775 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3779 void address_space_cache_destroy(MemoryRegionCache *cache)
3781 if (!cache->mrs.mr) {
3782 return;
3785 if (xen_enabled()) {
3786 xen_invalidate_map_cache_entry(cache->ptr);
3788 memory_region_unref(cache->mrs.mr);
3789 flatview_unref(cache->fv);
3790 cache->mrs.mr = NULL;
3791 cache->fv = NULL;
3794 /* Called from RCU critical section. This function has the same
3795 * semantics as address_space_translate, but it only works on a
3796 * predefined range of a MemoryRegion that was mapped with
3797 * address_space_cache_init.
3799 static inline MemoryRegion *address_space_translate_cached(
3800 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3801 hwaddr *plen, bool is_write, MemTxAttrs attrs)
3803 MemoryRegionSection section;
3804 MemoryRegion *mr;
3805 IOMMUMemoryRegion *iommu_mr;
3806 AddressSpace *target_as;
3808 assert(!cache->ptr);
3809 *xlat = addr + cache->xlat;
3811 mr = cache->mrs.mr;
3812 iommu_mr = memory_region_get_iommu(mr);
3813 if (!iommu_mr) {
3814 /* MMIO region. */
3815 return mr;
3818 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3819 NULL, is_write, true,
3820 &target_as, attrs);
3821 return section.mr;
3824 /* Called from RCU critical section. address_space_read_cached uses this
3825 * out of line function when the target is an MMIO or IOMMU region.
3827 void
3828 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3829 void *buf, int len)
3831 hwaddr addr1, l;
3832 MemoryRegion *mr;
3834 l = len;
3835 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3836 MEMTXATTRS_UNSPECIFIED);
3837 flatview_read_continue(cache->fv,
3838 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3839 addr1, l, mr);
3842 /* Called from RCU critical section. address_space_write_cached uses this
3843 * out of line function when the target is an MMIO or IOMMU region.
3845 void
3846 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3847 const void *buf, int len)
3849 hwaddr addr1, l;
3850 MemoryRegion *mr;
3852 l = len;
3853 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3854 MEMTXATTRS_UNSPECIFIED);
3855 flatview_write_continue(cache->fv,
3856 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3857 addr1, l, mr);
3860 #define ARG1_DECL MemoryRegionCache *cache
3861 #define ARG1 cache
3862 #define SUFFIX _cached_slow
3863 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3864 #define RCU_READ_LOCK() ((void)0)
3865 #define RCU_READ_UNLOCK() ((void)0)
3866 #include "memory_ldst.inc.c"
3868 /* virtual memory access for debug (includes writing to ROM) */
3869 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3870 uint8_t *buf, int len, int is_write)
3872 int l;
3873 hwaddr phys_addr;
3874 target_ulong page;
3876 cpu_synchronize_state(cpu);
3877 while (len > 0) {
3878 int asidx;
3879 MemTxAttrs attrs;
3881 page = addr & TARGET_PAGE_MASK;
3882 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3883 asidx = cpu_asidx_from_attrs(cpu, attrs);
3884 /* if no physical page mapped, return an error */
3885 if (phys_addr == -1)
3886 return -1;
3887 l = (page + TARGET_PAGE_SIZE) - addr;
3888 if (l > len)
3889 l = len;
3890 phys_addr += (addr & ~TARGET_PAGE_MASK);
3891 if (is_write) {
3892 cpu_physical_memory_write_rom(cpu->cpu_ases[asidx].as,
3893 phys_addr, buf, l);
3894 } else {
3895 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3896 MEMTXATTRS_UNSPECIFIED,
3897 buf, l, 0);
3899 len -= l;
3900 buf += l;
3901 addr += l;
3903 return 0;
3907 * Allows code that needs to deal with migration bitmaps etc to still be built
3908 * target independent.
3910 size_t qemu_target_page_size(void)
3912 return TARGET_PAGE_SIZE;
3915 int qemu_target_page_bits(void)
3917 return TARGET_PAGE_BITS;
3920 int qemu_target_page_bits_min(void)
3922 return TARGET_PAGE_BITS_MIN;
3924 #endif
3927 * A helper function for the _utterly broken_ virtio device model to find out if
3928 * it's running on a big endian machine. Don't do this at home kids!
3930 bool target_words_bigendian(void);
3931 bool target_words_bigendian(void)
3933 #if defined(TARGET_WORDS_BIGENDIAN)
3934 return true;
3935 #else
3936 return false;
3937 #endif
3940 #ifndef CONFIG_USER_ONLY
3941 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3943 MemoryRegion*mr;
3944 hwaddr l = 1;
3945 bool res;
3947 rcu_read_lock();
3948 mr = address_space_translate(&address_space_memory,
3949 phys_addr, &phys_addr, &l, false,
3950 MEMTXATTRS_UNSPECIFIED);
3952 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3953 rcu_read_unlock();
3954 return res;
3957 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3959 RAMBlock *block;
3960 int ret = 0;
3962 rcu_read_lock();
3963 RAMBLOCK_FOREACH(block) {
3964 ret = func(block->idstr, block->host, block->offset,
3965 block->used_length, opaque);
3966 if (ret) {
3967 break;
3970 rcu_read_unlock();
3971 return ret;
3974 int qemu_ram_foreach_migratable_block(RAMBlockIterFunc func, void *opaque)
3976 RAMBlock *block;
3977 int ret = 0;
3979 rcu_read_lock();
3980 RAMBLOCK_FOREACH(block) {
3981 if (!qemu_ram_is_migratable(block)) {
3982 continue;
3984 ret = func(block->idstr, block->host, block->offset,
3985 block->used_length, opaque);
3986 if (ret) {
3987 break;
3990 rcu_read_unlock();
3991 return ret;
3995 * Unmap pages of memory from start to start+length such that
3996 * they a) read as 0, b) Trigger whatever fault mechanism
3997 * the OS provides for postcopy.
3998 * The pages must be unmapped by the end of the function.
3999 * Returns: 0 on success, none-0 on failure
4002 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
4004 int ret = -1;
4006 uint8_t *host_startaddr = rb->host + start;
4008 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
4009 error_report("ram_block_discard_range: Unaligned start address: %p",
4010 host_startaddr);
4011 goto err;
4014 if ((start + length) <= rb->used_length) {
4015 bool need_madvise, need_fallocate;
4016 uint8_t *host_endaddr = host_startaddr + length;
4017 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
4018 error_report("ram_block_discard_range: Unaligned end address: %p",
4019 host_endaddr);
4020 goto err;
4023 errno = ENOTSUP; /* If we are missing MADVISE etc */
4025 /* The logic here is messy;
4026 * madvise DONTNEED fails for hugepages
4027 * fallocate works on hugepages and shmem
4029 need_madvise = (rb->page_size == qemu_host_page_size);
4030 need_fallocate = rb->fd != -1;
4031 if (need_fallocate) {
4032 /* For a file, this causes the area of the file to be zero'd
4033 * if read, and for hugetlbfs also causes it to be unmapped
4034 * so a userfault will trigger.
4036 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
4037 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
4038 start, length);
4039 if (ret) {
4040 ret = -errno;
4041 error_report("ram_block_discard_range: Failed to fallocate "
4042 "%s:%" PRIx64 " +%zx (%d)",
4043 rb->idstr, start, length, ret);
4044 goto err;
4046 #else
4047 ret = -ENOSYS;
4048 error_report("ram_block_discard_range: fallocate not available/file"
4049 "%s:%" PRIx64 " +%zx (%d)",
4050 rb->idstr, start, length, ret);
4051 goto err;
4052 #endif
4054 if (need_madvise) {
4055 /* For normal RAM this causes it to be unmapped,
4056 * for shared memory it causes the local mapping to disappear
4057 * and to fall back on the file contents (which we just
4058 * fallocate'd away).
4060 #if defined(CONFIG_MADVISE)
4061 ret = madvise(host_startaddr, length, MADV_DONTNEED);
4062 if (ret) {
4063 ret = -errno;
4064 error_report("ram_block_discard_range: Failed to discard range "
4065 "%s:%" PRIx64 " +%zx (%d)",
4066 rb->idstr, start, length, ret);
4067 goto err;
4069 #else
4070 ret = -ENOSYS;
4071 error_report("ram_block_discard_range: MADVISE not available"
4072 "%s:%" PRIx64 " +%zx (%d)",
4073 rb->idstr, start, length, ret);
4074 goto err;
4075 #endif
4077 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
4078 need_madvise, need_fallocate, ret);
4079 } else {
4080 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
4081 "/%zx/" RAM_ADDR_FMT")",
4082 rb->idstr, start, length, rb->used_length);
4085 err:
4086 return ret;
4089 #endif
4091 void page_size_init(void)
4093 /* NOTE: we can always suppose that qemu_host_page_size >=
4094 TARGET_PAGE_SIZE */
4095 if (qemu_host_page_size == 0) {
4096 qemu_host_page_size = qemu_real_host_page_size;
4098 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
4099 qemu_host_page_size = TARGET_PAGE_SIZE;
4101 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;
4104 #if !defined(CONFIG_USER_ONLY)
4106 static void mtree_print_phys_entries(fprintf_function mon, void *f,
4107 int start, int end, int skip, int ptr)
4109 if (start == end - 1) {
4110 mon(f, "\t%3d ", start);
4111 } else {
4112 mon(f, "\t%3d..%-3d ", start, end - 1);
4114 mon(f, " skip=%d ", skip);
4115 if (ptr == PHYS_MAP_NODE_NIL) {
4116 mon(f, " ptr=NIL");
4117 } else if (!skip) {
4118 mon(f, " ptr=#%d", ptr);
4119 } else {
4120 mon(f, " ptr=[%d]", ptr);
4122 mon(f, "\n");
4125 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
4126 int128_sub((size), int128_one())) : 0)
4128 void mtree_print_dispatch(fprintf_function mon, void *f,
4129 AddressSpaceDispatch *d, MemoryRegion *root)
4131 int i;
4133 mon(f, " Dispatch\n");
4134 mon(f, " Physical sections\n");
4136 for (i = 0; i < d->map.sections_nb; ++i) {
4137 MemoryRegionSection *s = d->map.sections + i;
4138 const char *names[] = { " [unassigned]", " [not dirty]",
4139 " [ROM]", " [watch]" };
4141 mon(f, " #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx " %s%s%s%s%s",
4143 s->offset_within_address_space,
4144 s->offset_within_address_space + MR_SIZE(s->mr->size),
4145 s->mr->name ? s->mr->name : "(noname)",
4146 i < ARRAY_SIZE(names) ? names[i] : "",
4147 s->mr == root ? " [ROOT]" : "",
4148 s == d->mru_section ? " [MRU]" : "",
4149 s->mr->is_iommu ? " [iommu]" : "");
4151 if (s->mr->alias) {
4152 mon(f, " alias=%s", s->mr->alias->name ?
4153 s->mr->alias->name : "noname");
4155 mon(f, "\n");
4158 mon(f, " Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
4159 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
4160 for (i = 0; i < d->map.nodes_nb; ++i) {
4161 int j, jprev;
4162 PhysPageEntry prev;
4163 Node *n = d->map.nodes + i;
4165 mon(f, " [%d]\n", i);
4167 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
4168 PhysPageEntry *pe = *n + j;
4170 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
4171 continue;
4174 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
4176 jprev = j;
4177 prev = *pe;
4180 if (jprev != ARRAY_SIZE(*n)) {
4181 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
4186 #endif