Merge remote-tracking branch 'remotes/dgibson/tags/ppc-for-3.0-20180622' into staging
[qemu.git] / exec.c
blob28f9bdcbf95ebf3d49d8efbc711c5fb54513c66b
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 bool memory_region_is_unassigned(MemoryRegion *mr)
407 return mr != &io_mem_rom && mr != &io_mem_notdirty && !mr->rom_device
408 && mr != &io_mem_watch;
411 /* Called from RCU critical section */
412 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
413 hwaddr addr,
414 bool resolve_subpage)
416 MemoryRegionSection *section = atomic_read(&d->mru_section);
417 subpage_t *subpage;
419 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
420 !section_covers_addr(section, addr)) {
421 section = phys_page_find(d, addr);
422 atomic_set(&d->mru_section, section);
424 if (resolve_subpage && section->mr->subpage) {
425 subpage = container_of(section->mr, subpage_t, iomem);
426 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
428 return section;
431 /* Called from RCU critical section */
432 static MemoryRegionSection *
433 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
434 hwaddr *plen, bool resolve_subpage)
436 MemoryRegionSection *section;
437 MemoryRegion *mr;
438 Int128 diff;
440 section = address_space_lookup_region(d, addr, resolve_subpage);
441 /* Compute offset within MemoryRegionSection */
442 addr -= section->offset_within_address_space;
444 /* Compute offset within MemoryRegion */
445 *xlat = addr + section->offset_within_region;
447 mr = section->mr;
449 /* MMIO registers can be expected to perform full-width accesses based only
450 * on their address, without considering adjacent registers that could
451 * decode to completely different MemoryRegions. When such registers
452 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
453 * regions overlap wildly. For this reason we cannot clamp the accesses
454 * here.
456 * If the length is small (as is the case for address_space_ldl/stl),
457 * everything works fine. If the incoming length is large, however,
458 * the caller really has to do the clamping through memory_access_size.
460 if (memory_region_is_ram(mr)) {
461 diff = int128_sub(section->size, int128_make64(addr));
462 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
464 return section;
468 * address_space_translate_iommu - translate an address through an IOMMU
469 * memory region and then through the target address space.
471 * @iommu_mr: the IOMMU memory region that we start the translation from
472 * @addr: the address to be translated through the MMU
473 * @xlat: the translated address offset within the destination memory region.
474 * It cannot be %NULL.
475 * @plen_out: valid read/write length of the translated address. It
476 * cannot be %NULL.
477 * @page_mask_out: page mask for the translated address. This
478 * should only be meaningful for IOMMU translated
479 * addresses, since there may be huge pages that this bit
480 * would tell. It can be %NULL if we don't care about it.
481 * @is_write: whether the translation operation is for write
482 * @is_mmio: whether this can be MMIO, set true if it can
483 * @target_as: the address space targeted by the IOMMU
484 * @attrs: transaction attributes
486 * This function is called from RCU critical section. It is the common
487 * part of flatview_do_translate and address_space_translate_cached.
489 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
490 hwaddr *xlat,
491 hwaddr *plen_out,
492 hwaddr *page_mask_out,
493 bool is_write,
494 bool is_mmio,
495 AddressSpace **target_as,
496 MemTxAttrs attrs)
498 MemoryRegionSection *section;
499 hwaddr page_mask = (hwaddr)-1;
501 do {
502 hwaddr addr = *xlat;
503 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
504 int iommu_idx = 0;
505 IOMMUTLBEntry iotlb;
507 if (imrc->attrs_to_index) {
508 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
511 iotlb = imrc->translate(iommu_mr, addr, is_write ?
512 IOMMU_WO : IOMMU_RO, iommu_idx);
514 if (!(iotlb.perm & (1 << is_write))) {
515 goto unassigned;
518 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
519 | (addr & iotlb.addr_mask));
520 page_mask &= iotlb.addr_mask;
521 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
522 *target_as = iotlb.target_as;
524 section = address_space_translate_internal(
525 address_space_to_dispatch(iotlb.target_as), addr, xlat,
526 plen_out, is_mmio);
528 iommu_mr = memory_region_get_iommu(section->mr);
529 } while (unlikely(iommu_mr));
531 if (page_mask_out) {
532 *page_mask_out = page_mask;
534 return *section;
536 unassigned:
537 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
541 * flatview_do_translate - translate an address in FlatView
543 * @fv: the flat view that we want to translate on
544 * @addr: the address to be translated in above address space
545 * @xlat: the translated address offset within memory region. It
546 * cannot be @NULL.
547 * @plen_out: valid read/write length of the translated address. It
548 * can be @NULL when we don't care about it.
549 * @page_mask_out: page mask for the translated address. This
550 * should only be meaningful for IOMMU translated
551 * addresses, since there may be huge pages that this bit
552 * would tell. It can be @NULL if we don't care about it.
553 * @is_write: whether the translation operation is for write
554 * @is_mmio: whether this can be MMIO, set true if it can
555 * @target_as: the address space targeted by the IOMMU
556 * @attrs: memory transaction attributes
558 * This function is called from RCU critical section
560 static MemoryRegionSection flatview_do_translate(FlatView *fv,
561 hwaddr addr,
562 hwaddr *xlat,
563 hwaddr *plen_out,
564 hwaddr *page_mask_out,
565 bool is_write,
566 bool is_mmio,
567 AddressSpace **target_as,
568 MemTxAttrs attrs)
570 MemoryRegionSection *section;
571 IOMMUMemoryRegion *iommu_mr;
572 hwaddr plen = (hwaddr)(-1);
574 if (!plen_out) {
575 plen_out = &plen;
578 section = address_space_translate_internal(
579 flatview_to_dispatch(fv), addr, xlat,
580 plen_out, is_mmio);
582 iommu_mr = memory_region_get_iommu(section->mr);
583 if (unlikely(iommu_mr)) {
584 return address_space_translate_iommu(iommu_mr, xlat,
585 plen_out, page_mask_out,
586 is_write, is_mmio,
587 target_as, attrs);
589 if (page_mask_out) {
590 /* Not behind an IOMMU, use default page size. */
591 *page_mask_out = ~TARGET_PAGE_MASK;
594 return *section;
597 /* Called from RCU critical section */
598 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
599 bool is_write, MemTxAttrs attrs)
601 MemoryRegionSection section;
602 hwaddr xlat, page_mask;
605 * This can never be MMIO, and we don't really care about plen,
606 * but page mask.
608 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
609 NULL, &page_mask, is_write, false, &as,
610 attrs);
612 /* Illegal translation */
613 if (section.mr == &io_mem_unassigned) {
614 goto iotlb_fail;
617 /* Convert memory region offset into address space offset */
618 xlat += section.offset_within_address_space -
619 section.offset_within_region;
621 return (IOMMUTLBEntry) {
622 .target_as = as,
623 .iova = addr & ~page_mask,
624 .translated_addr = xlat & ~page_mask,
625 .addr_mask = page_mask,
626 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
627 .perm = IOMMU_RW,
630 iotlb_fail:
631 return (IOMMUTLBEntry) {0};
634 /* Called from RCU critical section */
635 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
636 hwaddr *plen, bool is_write,
637 MemTxAttrs attrs)
639 MemoryRegion *mr;
640 MemoryRegionSection section;
641 AddressSpace *as = NULL;
643 /* This can be MMIO, so setup MMIO bit. */
644 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
645 is_write, true, &as, attrs);
646 mr = section.mr;
648 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
649 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
650 *plen = MIN(page, *plen);
653 return mr;
656 typedef struct TCGIOMMUNotifier {
657 IOMMUNotifier n;
658 MemoryRegion *mr;
659 CPUState *cpu;
660 int iommu_idx;
661 bool active;
662 } TCGIOMMUNotifier;
664 static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
666 TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
668 if (!notifier->active) {
669 return;
671 tlb_flush(notifier->cpu);
672 notifier->active = false;
673 /* We leave the notifier struct on the list to avoid reallocating it later.
674 * Generally the number of IOMMUs a CPU deals with will be small.
675 * In any case we can't unregister the iommu notifier from a notify
676 * callback.
680 static void tcg_register_iommu_notifier(CPUState *cpu,
681 IOMMUMemoryRegion *iommu_mr,
682 int iommu_idx)
684 /* Make sure this CPU has an IOMMU notifier registered for this
685 * IOMMU/IOMMU index combination, so that we can flush its TLB
686 * when the IOMMU tells us the mappings we've cached have changed.
688 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
689 TCGIOMMUNotifier *notifier;
690 int i;
692 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
693 notifier = &g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier, i);
694 if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
695 break;
698 if (i == cpu->iommu_notifiers->len) {
699 /* Not found, add a new entry at the end of the array */
700 cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
701 notifier = &g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier, i);
703 notifier->mr = mr;
704 notifier->iommu_idx = iommu_idx;
705 notifier->cpu = cpu;
706 /* Rather than trying to register interest in the specific part
707 * of the iommu's address space that we've accessed and then
708 * expand it later as subsequent accesses touch more of it, we
709 * just register interest in the whole thing, on the assumption
710 * that iommu reconfiguration will be rare.
712 iommu_notifier_init(&notifier->n,
713 tcg_iommu_unmap_notify,
714 IOMMU_NOTIFIER_UNMAP,
716 HWADDR_MAX,
717 iommu_idx);
718 memory_region_register_iommu_notifier(notifier->mr, &notifier->n);
721 if (!notifier->active) {
722 notifier->active = true;
726 static void tcg_iommu_free_notifier_list(CPUState *cpu)
728 /* Destroy the CPU's notifier list */
729 int i;
730 TCGIOMMUNotifier *notifier;
732 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
733 notifier = &g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier, i);
734 memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
736 g_array_free(cpu->iommu_notifiers, true);
739 /* Called from RCU critical section */
740 MemoryRegionSection *
741 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
742 hwaddr *xlat, hwaddr *plen,
743 MemTxAttrs attrs, int *prot)
745 MemoryRegionSection *section;
746 IOMMUMemoryRegion *iommu_mr;
747 IOMMUMemoryRegionClass *imrc;
748 IOMMUTLBEntry iotlb;
749 int iommu_idx;
750 AddressSpaceDispatch *d = atomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
752 for (;;) {
753 section = address_space_translate_internal(d, addr, &addr, plen, false);
755 iommu_mr = memory_region_get_iommu(section->mr);
756 if (!iommu_mr) {
757 break;
760 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
762 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
763 tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
764 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
765 * doesn't short-cut its translation table walk.
767 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
768 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
769 | (addr & iotlb.addr_mask));
770 /* Update the caller's prot bits to remove permissions the IOMMU
771 * is giving us a failure response for. If we get down to no
772 * permissions left at all we can give up now.
774 if (!(iotlb.perm & IOMMU_RO)) {
775 *prot &= ~(PAGE_READ | PAGE_EXEC);
777 if (!(iotlb.perm & IOMMU_WO)) {
778 *prot &= ~PAGE_WRITE;
781 if (!*prot) {
782 goto translate_fail;
785 d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
788 assert(!memory_region_is_iommu(section->mr));
789 *xlat = addr;
790 return section;
792 translate_fail:
793 return &d->map.sections[PHYS_SECTION_UNASSIGNED];
795 #endif
797 #if !defined(CONFIG_USER_ONLY)
799 static int cpu_common_post_load(void *opaque, int version_id)
801 CPUState *cpu = opaque;
803 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
804 version_id is increased. */
805 cpu->interrupt_request &= ~0x01;
806 tlb_flush(cpu);
808 /* loadvm has just updated the content of RAM, bypassing the
809 * usual mechanisms that ensure we flush TBs for writes to
810 * memory we've translated code from. So we must flush all TBs,
811 * which will now be stale.
813 tb_flush(cpu);
815 return 0;
818 static int cpu_common_pre_load(void *opaque)
820 CPUState *cpu = opaque;
822 cpu->exception_index = -1;
824 return 0;
827 static bool cpu_common_exception_index_needed(void *opaque)
829 CPUState *cpu = opaque;
831 return tcg_enabled() && cpu->exception_index != -1;
834 static const VMStateDescription vmstate_cpu_common_exception_index = {
835 .name = "cpu_common/exception_index",
836 .version_id = 1,
837 .minimum_version_id = 1,
838 .needed = cpu_common_exception_index_needed,
839 .fields = (VMStateField[]) {
840 VMSTATE_INT32(exception_index, CPUState),
841 VMSTATE_END_OF_LIST()
845 static bool cpu_common_crash_occurred_needed(void *opaque)
847 CPUState *cpu = opaque;
849 return cpu->crash_occurred;
852 static const VMStateDescription vmstate_cpu_common_crash_occurred = {
853 .name = "cpu_common/crash_occurred",
854 .version_id = 1,
855 .minimum_version_id = 1,
856 .needed = cpu_common_crash_occurred_needed,
857 .fields = (VMStateField[]) {
858 VMSTATE_BOOL(crash_occurred, CPUState),
859 VMSTATE_END_OF_LIST()
863 const VMStateDescription vmstate_cpu_common = {
864 .name = "cpu_common",
865 .version_id = 1,
866 .minimum_version_id = 1,
867 .pre_load = cpu_common_pre_load,
868 .post_load = cpu_common_post_load,
869 .fields = (VMStateField[]) {
870 VMSTATE_UINT32(halted, CPUState),
871 VMSTATE_UINT32(interrupt_request, CPUState),
872 VMSTATE_END_OF_LIST()
874 .subsections = (const VMStateDescription*[]) {
875 &vmstate_cpu_common_exception_index,
876 &vmstate_cpu_common_crash_occurred,
877 NULL
881 #endif
883 CPUState *qemu_get_cpu(int index)
885 CPUState *cpu;
887 CPU_FOREACH(cpu) {
888 if (cpu->cpu_index == index) {
889 return cpu;
893 return NULL;
896 #if !defined(CONFIG_USER_ONLY)
897 void cpu_address_space_init(CPUState *cpu, int asidx,
898 const char *prefix, MemoryRegion *mr)
900 CPUAddressSpace *newas;
901 AddressSpace *as = g_new0(AddressSpace, 1);
902 char *as_name;
904 assert(mr);
905 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
906 address_space_init(as, mr, as_name);
907 g_free(as_name);
909 /* Target code should have set num_ases before calling us */
910 assert(asidx < cpu->num_ases);
912 if (asidx == 0) {
913 /* address space 0 gets the convenience alias */
914 cpu->as = as;
917 /* KVM cannot currently support multiple address spaces. */
918 assert(asidx == 0 || !kvm_enabled());
920 if (!cpu->cpu_ases) {
921 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
924 newas = &cpu->cpu_ases[asidx];
925 newas->cpu = cpu;
926 newas->as = as;
927 if (tcg_enabled()) {
928 newas->tcg_as_listener.commit = tcg_commit;
929 memory_listener_register(&newas->tcg_as_listener, as);
933 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
935 /* Return the AddressSpace corresponding to the specified index */
936 return cpu->cpu_ases[asidx].as;
938 #endif
940 void cpu_exec_unrealizefn(CPUState *cpu)
942 CPUClass *cc = CPU_GET_CLASS(cpu);
944 cpu_list_remove(cpu);
946 if (cc->vmsd != NULL) {
947 vmstate_unregister(NULL, cc->vmsd, cpu);
949 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
950 vmstate_unregister(NULL, &vmstate_cpu_common, cpu);
952 #ifndef CONFIG_USER_ONLY
953 tcg_iommu_free_notifier_list(cpu);
954 #endif
957 Property cpu_common_props[] = {
958 #ifndef CONFIG_USER_ONLY
959 /* Create a memory property for softmmu CPU object,
960 * so users can wire up its memory. (This can't go in qom/cpu.c
961 * because that file is compiled only once for both user-mode
962 * and system builds.) The default if no link is set up is to use
963 * the system address space.
965 DEFINE_PROP_LINK("memory", CPUState, memory, TYPE_MEMORY_REGION,
966 MemoryRegion *),
967 #endif
968 DEFINE_PROP_END_OF_LIST(),
971 void cpu_exec_initfn(CPUState *cpu)
973 cpu->as = NULL;
974 cpu->num_ases = 0;
976 #ifndef CONFIG_USER_ONLY
977 cpu->thread_id = qemu_get_thread_id();
978 cpu->memory = system_memory;
979 object_ref(OBJECT(cpu->memory));
980 #endif
983 void cpu_exec_realizefn(CPUState *cpu, Error **errp)
985 CPUClass *cc = CPU_GET_CLASS(cpu);
986 static bool tcg_target_initialized;
988 cpu_list_add(cpu);
990 if (tcg_enabled() && !tcg_target_initialized) {
991 tcg_target_initialized = true;
992 cc->tcg_initialize();
995 #ifndef CONFIG_USER_ONLY
996 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
997 vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
999 if (cc->vmsd != NULL) {
1000 vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);
1003 cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier));
1004 #endif
1007 const char *parse_cpu_model(const char *cpu_model)
1009 ObjectClass *oc;
1010 CPUClass *cc;
1011 gchar **model_pieces;
1012 const char *cpu_type;
1014 model_pieces = g_strsplit(cpu_model, ",", 2);
1016 oc = cpu_class_by_name(CPU_RESOLVING_TYPE, model_pieces[0]);
1017 if (oc == NULL) {
1018 error_report("unable to find CPU model '%s'", model_pieces[0]);
1019 g_strfreev(model_pieces);
1020 exit(EXIT_FAILURE);
1023 cpu_type = object_class_get_name(oc);
1024 cc = CPU_CLASS(oc);
1025 cc->parse_features(cpu_type, model_pieces[1], &error_fatal);
1026 g_strfreev(model_pieces);
1027 return cpu_type;
1030 #if defined(CONFIG_USER_ONLY)
1031 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
1033 mmap_lock();
1034 tb_invalidate_phys_page_range(pc, pc + 1, 0);
1035 mmap_unlock();
1037 #else
1038 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
1040 MemTxAttrs attrs;
1041 hwaddr phys = cpu_get_phys_page_attrs_debug(cpu, pc, &attrs);
1042 int asidx = cpu_asidx_from_attrs(cpu, attrs);
1043 if (phys != -1) {
1044 /* Locks grabbed by tb_invalidate_phys_addr */
1045 tb_invalidate_phys_addr(cpu->cpu_ases[asidx].as,
1046 phys | (pc & ~TARGET_PAGE_MASK), attrs);
1049 #endif
1051 #if defined(CONFIG_USER_ONLY)
1052 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
1057 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
1058 int flags)
1060 return -ENOSYS;
1063 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
1067 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
1068 int flags, CPUWatchpoint **watchpoint)
1070 return -ENOSYS;
1072 #else
1073 /* Add a watchpoint. */
1074 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
1075 int flags, CPUWatchpoint **watchpoint)
1077 CPUWatchpoint *wp;
1079 /* forbid ranges which are empty or run off the end of the address space */
1080 if (len == 0 || (addr + len - 1) < addr) {
1081 error_report("tried to set invalid watchpoint at %"
1082 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
1083 return -EINVAL;
1085 wp = g_malloc(sizeof(*wp));
1087 wp->vaddr = addr;
1088 wp->len = len;
1089 wp->flags = flags;
1091 /* keep all GDB-injected watchpoints in front */
1092 if (flags & BP_GDB) {
1093 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
1094 } else {
1095 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
1098 tlb_flush_page(cpu, addr);
1100 if (watchpoint)
1101 *watchpoint = wp;
1102 return 0;
1105 /* Remove a specific watchpoint. */
1106 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
1107 int flags)
1109 CPUWatchpoint *wp;
1111 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1112 if (addr == wp->vaddr && len == wp->len
1113 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
1114 cpu_watchpoint_remove_by_ref(cpu, wp);
1115 return 0;
1118 return -ENOENT;
1121 /* Remove a specific watchpoint by reference. */
1122 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
1124 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
1126 tlb_flush_page(cpu, watchpoint->vaddr);
1128 g_free(watchpoint);
1131 /* Remove all matching watchpoints. */
1132 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
1134 CPUWatchpoint *wp, *next;
1136 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
1137 if (wp->flags & mask) {
1138 cpu_watchpoint_remove_by_ref(cpu, wp);
1143 /* Return true if this watchpoint address matches the specified
1144 * access (ie the address range covered by the watchpoint overlaps
1145 * partially or completely with the address range covered by the
1146 * access).
1148 static inline bool cpu_watchpoint_address_matches(CPUWatchpoint *wp,
1149 vaddr addr,
1150 vaddr len)
1152 /* We know the lengths are non-zero, but a little caution is
1153 * required to avoid errors in the case where the range ends
1154 * exactly at the top of the address space and so addr + len
1155 * wraps round to zero.
1157 vaddr wpend = wp->vaddr + wp->len - 1;
1158 vaddr addrend = addr + len - 1;
1160 return !(addr > wpend || wp->vaddr > addrend);
1163 #endif
1165 /* Add a breakpoint. */
1166 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
1167 CPUBreakpoint **breakpoint)
1169 CPUBreakpoint *bp;
1171 bp = g_malloc(sizeof(*bp));
1173 bp->pc = pc;
1174 bp->flags = flags;
1176 /* keep all GDB-injected breakpoints in front */
1177 if (flags & BP_GDB) {
1178 QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
1179 } else {
1180 QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
1183 breakpoint_invalidate(cpu, pc);
1185 if (breakpoint) {
1186 *breakpoint = bp;
1188 return 0;
1191 /* Remove a specific breakpoint. */
1192 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
1194 CPUBreakpoint *bp;
1196 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
1197 if (bp->pc == pc && bp->flags == flags) {
1198 cpu_breakpoint_remove_by_ref(cpu, bp);
1199 return 0;
1202 return -ENOENT;
1205 /* Remove a specific breakpoint by reference. */
1206 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
1208 QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);
1210 breakpoint_invalidate(cpu, breakpoint->pc);
1212 g_free(breakpoint);
1215 /* Remove all matching breakpoints. */
1216 void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
1218 CPUBreakpoint *bp, *next;
1220 QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
1221 if (bp->flags & mask) {
1222 cpu_breakpoint_remove_by_ref(cpu, bp);
1227 /* enable or disable single step mode. EXCP_DEBUG is returned by the
1228 CPU loop after each instruction */
1229 void cpu_single_step(CPUState *cpu, int enabled)
1231 if (cpu->singlestep_enabled != enabled) {
1232 cpu->singlestep_enabled = enabled;
1233 if (kvm_enabled()) {
1234 kvm_update_guest_debug(cpu, 0);
1235 } else {
1236 /* must flush all the translated code to avoid inconsistencies */
1237 /* XXX: only flush what is necessary */
1238 tb_flush(cpu);
1243 void cpu_abort(CPUState *cpu, const char *fmt, ...)
1245 va_list ap;
1246 va_list ap2;
1248 va_start(ap, fmt);
1249 va_copy(ap2, ap);
1250 fprintf(stderr, "qemu: fatal: ");
1251 vfprintf(stderr, fmt, ap);
1252 fprintf(stderr, "\n");
1253 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1254 if (qemu_log_separate()) {
1255 qemu_log_lock();
1256 qemu_log("qemu: fatal: ");
1257 qemu_log_vprintf(fmt, ap2);
1258 qemu_log("\n");
1259 log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1260 qemu_log_flush();
1261 qemu_log_unlock();
1262 qemu_log_close();
1264 va_end(ap2);
1265 va_end(ap);
1266 replay_finish();
1267 #if defined(CONFIG_USER_ONLY)
1269 struct sigaction act;
1270 sigfillset(&act.sa_mask);
1271 act.sa_handler = SIG_DFL;
1272 act.sa_flags = 0;
1273 sigaction(SIGABRT, &act, NULL);
1275 #endif
1276 abort();
1279 #if !defined(CONFIG_USER_ONLY)
1280 /* Called from RCU critical section */
1281 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
1283 RAMBlock *block;
1285 block = atomic_rcu_read(&ram_list.mru_block);
1286 if (block && addr - block->offset < block->max_length) {
1287 return block;
1289 RAMBLOCK_FOREACH(block) {
1290 if (addr - block->offset < block->max_length) {
1291 goto found;
1295 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1296 abort();
1298 found:
1299 /* It is safe to write mru_block outside the iothread lock. This
1300 * is what happens:
1302 * mru_block = xxx
1303 * rcu_read_unlock()
1304 * xxx removed from list
1305 * rcu_read_lock()
1306 * read mru_block
1307 * mru_block = NULL;
1308 * call_rcu(reclaim_ramblock, xxx);
1309 * rcu_read_unlock()
1311 * atomic_rcu_set is not needed here. The block was already published
1312 * when it was placed into the list. Here we're just making an extra
1313 * copy of the pointer.
1315 ram_list.mru_block = block;
1316 return block;
1319 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1321 CPUState *cpu;
1322 ram_addr_t start1;
1323 RAMBlock *block;
1324 ram_addr_t end;
1326 end = TARGET_PAGE_ALIGN(start + length);
1327 start &= TARGET_PAGE_MASK;
1329 rcu_read_lock();
1330 block = qemu_get_ram_block(start);
1331 assert(block == qemu_get_ram_block(end - 1));
1332 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1333 CPU_FOREACH(cpu) {
1334 tlb_reset_dirty(cpu, start1, length);
1336 rcu_read_unlock();
1339 /* Note: start and end must be within the same ram block. */
1340 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1341 ram_addr_t length,
1342 unsigned client)
1344 DirtyMemoryBlocks *blocks;
1345 unsigned long end, page;
1346 bool dirty = false;
1348 if (length == 0) {
1349 return false;
1352 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1353 page = start >> TARGET_PAGE_BITS;
1355 rcu_read_lock();
1357 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1359 while (page < end) {
1360 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1361 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1362 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1364 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1365 offset, num);
1366 page += num;
1369 rcu_read_unlock();
1371 if (dirty && tcg_enabled()) {
1372 tlb_reset_dirty_range_all(start, length);
1375 return dirty;
1378 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1379 (ram_addr_t start, ram_addr_t length, unsigned client)
1381 DirtyMemoryBlocks *blocks;
1382 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1383 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1384 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1385 DirtyBitmapSnapshot *snap;
1386 unsigned long page, end, dest;
1388 snap = g_malloc0(sizeof(*snap) +
1389 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1390 snap->start = first;
1391 snap->end = last;
1393 page = first >> TARGET_PAGE_BITS;
1394 end = last >> TARGET_PAGE_BITS;
1395 dest = 0;
1397 rcu_read_lock();
1399 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1401 while (page < end) {
1402 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1403 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1404 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1406 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1407 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1408 offset >>= BITS_PER_LEVEL;
1410 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1411 blocks->blocks[idx] + offset,
1412 num);
1413 page += num;
1414 dest += num >> BITS_PER_LEVEL;
1417 rcu_read_unlock();
1419 if (tcg_enabled()) {
1420 tlb_reset_dirty_range_all(start, length);
1423 return snap;
1426 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1427 ram_addr_t start,
1428 ram_addr_t length)
1430 unsigned long page, end;
1432 assert(start >= snap->start);
1433 assert(start + length <= snap->end);
1435 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1436 page = (start - snap->start) >> TARGET_PAGE_BITS;
1438 while (page < end) {
1439 if (test_bit(page, snap->dirty)) {
1440 return true;
1442 page++;
1444 return false;
1447 /* Called from RCU critical section */
1448 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1449 MemoryRegionSection *section,
1450 target_ulong vaddr,
1451 hwaddr paddr, hwaddr xlat,
1452 int prot,
1453 target_ulong *address)
1455 hwaddr iotlb;
1456 CPUWatchpoint *wp;
1458 if (memory_region_is_ram(section->mr)) {
1459 /* Normal RAM. */
1460 iotlb = memory_region_get_ram_addr(section->mr) + xlat;
1461 if (!section->readonly) {
1462 iotlb |= PHYS_SECTION_NOTDIRTY;
1463 } else {
1464 iotlb |= PHYS_SECTION_ROM;
1466 } else {
1467 AddressSpaceDispatch *d;
1469 d = flatview_to_dispatch(section->fv);
1470 iotlb = section - d->map.sections;
1471 iotlb += xlat;
1474 /* Make accesses to pages with watchpoints go via the
1475 watchpoint trap routines. */
1476 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1477 if (cpu_watchpoint_address_matches(wp, vaddr, TARGET_PAGE_SIZE)) {
1478 /* Avoid trapping reads of pages with a write breakpoint. */
1479 if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
1480 iotlb = PHYS_SECTION_WATCH + paddr;
1481 *address |= TLB_MMIO;
1482 break;
1487 return iotlb;
1489 #endif /* defined(CONFIG_USER_ONLY) */
1491 #if !defined(CONFIG_USER_ONLY)
1493 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
1494 uint16_t section);
1495 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1497 static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
1498 qemu_anon_ram_alloc;
1501 * Set a custom physical guest memory alloator.
1502 * Accelerators with unusual needs may need this. Hopefully, we can
1503 * get rid of it eventually.
1505 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
1507 phys_mem_alloc = alloc;
1510 static uint16_t phys_section_add(PhysPageMap *map,
1511 MemoryRegionSection *section)
1513 /* The physical section number is ORed with a page-aligned
1514 * pointer to produce the iotlb entries. Thus it should
1515 * never overflow into the page-aligned value.
1517 assert(map->sections_nb < TARGET_PAGE_SIZE);
1519 if (map->sections_nb == map->sections_nb_alloc) {
1520 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1521 map->sections = g_renew(MemoryRegionSection, map->sections,
1522 map->sections_nb_alloc);
1524 map->sections[map->sections_nb] = *section;
1525 memory_region_ref(section->mr);
1526 return map->sections_nb++;
1529 static void phys_section_destroy(MemoryRegion *mr)
1531 bool have_sub_page = mr->subpage;
1533 memory_region_unref(mr);
1535 if (have_sub_page) {
1536 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1537 object_unref(OBJECT(&subpage->iomem));
1538 g_free(subpage);
1542 static void phys_sections_free(PhysPageMap *map)
1544 while (map->sections_nb > 0) {
1545 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1546 phys_section_destroy(section->mr);
1548 g_free(map->sections);
1549 g_free(map->nodes);
1552 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1554 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1555 subpage_t *subpage;
1556 hwaddr base = section->offset_within_address_space
1557 & TARGET_PAGE_MASK;
1558 MemoryRegionSection *existing = phys_page_find(d, base);
1559 MemoryRegionSection subsection = {
1560 .offset_within_address_space = base,
1561 .size = int128_make64(TARGET_PAGE_SIZE),
1563 hwaddr start, end;
1565 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1567 if (!(existing->mr->subpage)) {
1568 subpage = subpage_init(fv, base);
1569 subsection.fv = fv;
1570 subsection.mr = &subpage->iomem;
1571 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1572 phys_section_add(&d->map, &subsection));
1573 } else {
1574 subpage = container_of(existing->mr, subpage_t, iomem);
1576 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1577 end = start + int128_get64(section->size) - 1;
1578 subpage_register(subpage, start, end,
1579 phys_section_add(&d->map, section));
1583 static void register_multipage(FlatView *fv,
1584 MemoryRegionSection *section)
1586 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1587 hwaddr start_addr = section->offset_within_address_space;
1588 uint16_t section_index = phys_section_add(&d->map, section);
1589 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1590 TARGET_PAGE_BITS));
1592 assert(num_pages);
1593 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1596 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1598 MemoryRegionSection now = *section, remain = *section;
1599 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1601 if (now.offset_within_address_space & ~TARGET_PAGE_MASK) {
1602 uint64_t left = TARGET_PAGE_ALIGN(now.offset_within_address_space)
1603 - now.offset_within_address_space;
1605 now.size = int128_min(int128_make64(left), now.size);
1606 register_subpage(fv, &now);
1607 } else {
1608 now.size = int128_zero();
1610 while (int128_ne(remain.size, now.size)) {
1611 remain.size = int128_sub(remain.size, now.size);
1612 remain.offset_within_address_space += int128_get64(now.size);
1613 remain.offset_within_region += int128_get64(now.size);
1614 now = remain;
1615 if (int128_lt(remain.size, page_size)) {
1616 register_subpage(fv, &now);
1617 } else if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1618 now.size = page_size;
1619 register_subpage(fv, &now);
1620 } else {
1621 now.size = int128_and(now.size, int128_neg(page_size));
1622 register_multipage(fv, &now);
1627 void qemu_flush_coalesced_mmio_buffer(void)
1629 if (kvm_enabled())
1630 kvm_flush_coalesced_mmio_buffer();
1633 void qemu_mutex_lock_ramlist(void)
1635 qemu_mutex_lock(&ram_list.mutex);
1638 void qemu_mutex_unlock_ramlist(void)
1640 qemu_mutex_unlock(&ram_list.mutex);
1643 void ram_block_dump(Monitor *mon)
1645 RAMBlock *block;
1646 char *psize;
1648 rcu_read_lock();
1649 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1650 "Block Name", "PSize", "Offset", "Used", "Total");
1651 RAMBLOCK_FOREACH(block) {
1652 psize = size_to_str(block->page_size);
1653 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1654 " 0x%016" PRIx64 "\n", block->idstr, psize,
1655 (uint64_t)block->offset,
1656 (uint64_t)block->used_length,
1657 (uint64_t)block->max_length);
1658 g_free(psize);
1660 rcu_read_unlock();
1663 #ifdef __linux__
1665 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1666 * may or may not name the same files / on the same filesystem now as
1667 * when we actually open and map them. Iterate over the file
1668 * descriptors instead, and use qemu_fd_getpagesize().
1670 static int find_max_supported_pagesize(Object *obj, void *opaque)
1672 long *hpsize_min = opaque;
1674 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1675 long hpsize = host_memory_backend_pagesize(MEMORY_BACKEND(obj));
1677 if (hpsize < *hpsize_min) {
1678 *hpsize_min = hpsize;
1682 return 0;
1685 long qemu_getrampagesize(void)
1687 long hpsize = LONG_MAX;
1688 long mainrampagesize;
1689 Object *memdev_root;
1691 mainrampagesize = qemu_mempath_getpagesize(mem_path);
1693 /* it's possible we have memory-backend objects with
1694 * hugepage-backed RAM. these may get mapped into system
1695 * address space via -numa parameters or memory hotplug
1696 * hooks. we want to take these into account, but we
1697 * also want to make sure these supported hugepage
1698 * sizes are applicable across the entire range of memory
1699 * we may boot from, so we take the min across all
1700 * backends, and assume normal pages in cases where a
1701 * backend isn't backed by hugepages.
1703 memdev_root = object_resolve_path("/objects", NULL);
1704 if (memdev_root) {
1705 object_child_foreach(memdev_root, find_max_supported_pagesize, &hpsize);
1707 if (hpsize == LONG_MAX) {
1708 /* No additional memory regions found ==> Report main RAM page size */
1709 return mainrampagesize;
1712 /* If NUMA is disabled or the NUMA nodes are not backed with a
1713 * memory-backend, then there is at least one node using "normal" RAM,
1714 * so if its page size is smaller we have got to report that size instead.
1716 if (hpsize > mainrampagesize &&
1717 (nb_numa_nodes == 0 || numa_info[0].node_memdev == NULL)) {
1718 static bool warned;
1719 if (!warned) {
1720 error_report("Huge page support disabled (n/a for main memory).");
1721 warned = true;
1723 return mainrampagesize;
1726 return hpsize;
1728 #else
1729 long qemu_getrampagesize(void)
1731 return getpagesize();
1733 #endif
1735 #ifdef __linux__
1736 static int64_t get_file_size(int fd)
1738 int64_t size = lseek(fd, 0, SEEK_END);
1739 if (size < 0) {
1740 return -errno;
1742 return size;
1745 static int file_ram_open(const char *path,
1746 const char *region_name,
1747 bool *created,
1748 Error **errp)
1750 char *filename;
1751 char *sanitized_name;
1752 char *c;
1753 int fd = -1;
1755 *created = false;
1756 for (;;) {
1757 fd = open(path, O_RDWR);
1758 if (fd >= 0) {
1759 /* @path names an existing file, use it */
1760 break;
1762 if (errno == ENOENT) {
1763 /* @path names a file that doesn't exist, create it */
1764 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1765 if (fd >= 0) {
1766 *created = true;
1767 break;
1769 } else if (errno == EISDIR) {
1770 /* @path names a directory, create a file there */
1771 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1772 sanitized_name = g_strdup(region_name);
1773 for (c = sanitized_name; *c != '\0'; c++) {
1774 if (*c == '/') {
1775 *c = '_';
1779 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1780 sanitized_name);
1781 g_free(sanitized_name);
1783 fd = mkstemp(filename);
1784 if (fd >= 0) {
1785 unlink(filename);
1786 g_free(filename);
1787 break;
1789 g_free(filename);
1791 if (errno != EEXIST && errno != EINTR) {
1792 error_setg_errno(errp, errno,
1793 "can't open backing store %s for guest RAM",
1794 path);
1795 return -1;
1798 * Try again on EINTR and EEXIST. The latter happens when
1799 * something else creates the file between our two open().
1803 return fd;
1806 static void *file_ram_alloc(RAMBlock *block,
1807 ram_addr_t memory,
1808 int fd,
1809 bool truncate,
1810 Error **errp)
1812 void *area;
1814 block->page_size = qemu_fd_getpagesize(fd);
1815 if (block->mr->align % block->page_size) {
1816 error_setg(errp, "alignment 0x%" PRIx64
1817 " must be multiples of page size 0x%zx",
1818 block->mr->align, block->page_size);
1819 return NULL;
1821 block->mr->align = MAX(block->page_size, block->mr->align);
1822 #if defined(__s390x__)
1823 if (kvm_enabled()) {
1824 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1826 #endif
1828 if (memory < block->page_size) {
1829 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1830 "or larger than page size 0x%zx",
1831 memory, block->page_size);
1832 return NULL;
1835 memory = ROUND_UP(memory, block->page_size);
1838 * ftruncate is not supported by hugetlbfs in older
1839 * hosts, so don't bother bailing out on errors.
1840 * If anything goes wrong with it under other filesystems,
1841 * mmap will fail.
1843 * Do not truncate the non-empty backend file to avoid corrupting
1844 * the existing data in the file. Disabling shrinking is not
1845 * enough. For example, the current vNVDIMM implementation stores
1846 * the guest NVDIMM labels at the end of the backend file. If the
1847 * backend file is later extended, QEMU will not be able to find
1848 * those labels. Therefore, extending the non-empty backend file
1849 * is disabled as well.
1851 if (truncate && ftruncate(fd, memory)) {
1852 perror("ftruncate");
1855 area = qemu_ram_mmap(fd, memory, block->mr->align,
1856 block->flags & RAM_SHARED);
1857 if (area == MAP_FAILED) {
1858 error_setg_errno(errp, errno,
1859 "unable to map backing store for guest RAM");
1860 return NULL;
1863 if (mem_prealloc) {
1864 os_mem_prealloc(fd, area, memory, smp_cpus, errp);
1865 if (errp && *errp) {
1866 qemu_ram_munmap(area, memory);
1867 return NULL;
1871 block->fd = fd;
1872 return area;
1874 #endif
1876 /* Allocate space within the ram_addr_t space that governs the
1877 * dirty bitmaps.
1878 * Called with the ramlist lock held.
1880 static ram_addr_t find_ram_offset(ram_addr_t size)
1882 RAMBlock *block, *next_block;
1883 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1885 assert(size != 0); /* it would hand out same offset multiple times */
1887 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1888 return 0;
1891 RAMBLOCK_FOREACH(block) {
1892 ram_addr_t candidate, next = RAM_ADDR_MAX;
1894 /* Align blocks to start on a 'long' in the bitmap
1895 * which makes the bitmap sync'ing take the fast path.
1897 candidate = block->offset + block->max_length;
1898 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1900 /* Search for the closest following block
1901 * and find the gap.
1903 RAMBLOCK_FOREACH(next_block) {
1904 if (next_block->offset >= candidate) {
1905 next = MIN(next, next_block->offset);
1909 /* If it fits remember our place and remember the size
1910 * of gap, but keep going so that we might find a smaller
1911 * gap to fill so avoiding fragmentation.
1913 if (next - candidate >= size && next - candidate < mingap) {
1914 offset = candidate;
1915 mingap = next - candidate;
1918 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1921 if (offset == RAM_ADDR_MAX) {
1922 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1923 (uint64_t)size);
1924 abort();
1927 trace_find_ram_offset(size, offset);
1929 return offset;
1932 unsigned long last_ram_page(void)
1934 RAMBlock *block;
1935 ram_addr_t last = 0;
1937 rcu_read_lock();
1938 RAMBLOCK_FOREACH(block) {
1939 last = MAX(last, block->offset + block->max_length);
1941 rcu_read_unlock();
1942 return last >> TARGET_PAGE_BITS;
1945 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1947 int ret;
1949 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1950 if (!machine_dump_guest_core(current_machine)) {
1951 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1952 if (ret) {
1953 perror("qemu_madvise");
1954 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1955 "but dump_guest_core=off specified\n");
1960 const char *qemu_ram_get_idstr(RAMBlock *rb)
1962 return rb->idstr;
1965 bool qemu_ram_is_shared(RAMBlock *rb)
1967 return rb->flags & RAM_SHARED;
1970 /* Note: Only set at the start of postcopy */
1971 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1973 return rb->flags & RAM_UF_ZEROPAGE;
1976 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1978 rb->flags |= RAM_UF_ZEROPAGE;
1981 bool qemu_ram_is_migratable(RAMBlock *rb)
1983 return rb->flags & RAM_MIGRATABLE;
1986 void qemu_ram_set_migratable(RAMBlock *rb)
1988 rb->flags |= RAM_MIGRATABLE;
1991 void qemu_ram_unset_migratable(RAMBlock *rb)
1993 rb->flags &= ~RAM_MIGRATABLE;
1996 /* Called with iothread lock held. */
1997 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1999 RAMBlock *block;
2001 assert(new_block);
2002 assert(!new_block->idstr[0]);
2004 if (dev) {
2005 char *id = qdev_get_dev_path(dev);
2006 if (id) {
2007 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
2008 g_free(id);
2011 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
2013 rcu_read_lock();
2014 RAMBLOCK_FOREACH(block) {
2015 if (block != new_block &&
2016 !strcmp(block->idstr, new_block->idstr)) {
2017 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
2018 new_block->idstr);
2019 abort();
2022 rcu_read_unlock();
2025 /* Called with iothread lock held. */
2026 void qemu_ram_unset_idstr(RAMBlock *block)
2028 /* FIXME: arch_init.c assumes that this is not called throughout
2029 * migration. Ignore the problem since hot-unplug during migration
2030 * does not work anyway.
2032 if (block) {
2033 memset(block->idstr, 0, sizeof(block->idstr));
2037 size_t qemu_ram_pagesize(RAMBlock *rb)
2039 return rb->page_size;
2042 /* Returns the largest size of page in use */
2043 size_t qemu_ram_pagesize_largest(void)
2045 RAMBlock *block;
2046 size_t largest = 0;
2048 RAMBLOCK_FOREACH(block) {
2049 largest = MAX(largest, qemu_ram_pagesize(block));
2052 return largest;
2055 static int memory_try_enable_merging(void *addr, size_t len)
2057 if (!machine_mem_merge(current_machine)) {
2058 /* disabled by the user */
2059 return 0;
2062 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
2065 /* Only legal before guest might have detected the memory size: e.g. on
2066 * incoming migration, or right after reset.
2068 * As memory core doesn't know how is memory accessed, it is up to
2069 * resize callback to update device state and/or add assertions to detect
2070 * misuse, if necessary.
2072 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
2074 assert(block);
2076 newsize = HOST_PAGE_ALIGN(newsize);
2078 if (block->used_length == newsize) {
2079 return 0;
2082 if (!(block->flags & RAM_RESIZEABLE)) {
2083 error_setg_errno(errp, EINVAL,
2084 "Length mismatch: %s: 0x" RAM_ADDR_FMT
2085 " in != 0x" RAM_ADDR_FMT, block->idstr,
2086 newsize, block->used_length);
2087 return -EINVAL;
2090 if (block->max_length < newsize) {
2091 error_setg_errno(errp, EINVAL,
2092 "Length too large: %s: 0x" RAM_ADDR_FMT
2093 " > 0x" RAM_ADDR_FMT, block->idstr,
2094 newsize, block->max_length);
2095 return -EINVAL;
2098 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
2099 block->used_length = newsize;
2100 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
2101 DIRTY_CLIENTS_ALL);
2102 memory_region_set_size(block->mr, newsize);
2103 if (block->resized) {
2104 block->resized(block->idstr, newsize, block->host);
2106 return 0;
2109 /* Called with ram_list.mutex held */
2110 static void dirty_memory_extend(ram_addr_t old_ram_size,
2111 ram_addr_t new_ram_size)
2113 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
2114 DIRTY_MEMORY_BLOCK_SIZE);
2115 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
2116 DIRTY_MEMORY_BLOCK_SIZE);
2117 int i;
2119 /* Only need to extend if block count increased */
2120 if (new_num_blocks <= old_num_blocks) {
2121 return;
2124 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
2125 DirtyMemoryBlocks *old_blocks;
2126 DirtyMemoryBlocks *new_blocks;
2127 int j;
2129 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
2130 new_blocks = g_malloc(sizeof(*new_blocks) +
2131 sizeof(new_blocks->blocks[0]) * new_num_blocks);
2133 if (old_num_blocks) {
2134 memcpy(new_blocks->blocks, old_blocks->blocks,
2135 old_num_blocks * sizeof(old_blocks->blocks[0]));
2138 for (j = old_num_blocks; j < new_num_blocks; j++) {
2139 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
2142 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
2144 if (old_blocks) {
2145 g_free_rcu(old_blocks, rcu);
2150 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
2152 RAMBlock *block;
2153 RAMBlock *last_block = NULL;
2154 ram_addr_t old_ram_size, new_ram_size;
2155 Error *err = NULL;
2157 old_ram_size = last_ram_page();
2159 qemu_mutex_lock_ramlist();
2160 new_block->offset = find_ram_offset(new_block->max_length);
2162 if (!new_block->host) {
2163 if (xen_enabled()) {
2164 xen_ram_alloc(new_block->offset, new_block->max_length,
2165 new_block->mr, &err);
2166 if (err) {
2167 error_propagate(errp, err);
2168 qemu_mutex_unlock_ramlist();
2169 return;
2171 } else {
2172 new_block->host = phys_mem_alloc(new_block->max_length,
2173 &new_block->mr->align, shared);
2174 if (!new_block->host) {
2175 error_setg_errno(errp, errno,
2176 "cannot set up guest memory '%s'",
2177 memory_region_name(new_block->mr));
2178 qemu_mutex_unlock_ramlist();
2179 return;
2181 memory_try_enable_merging(new_block->host, new_block->max_length);
2185 new_ram_size = MAX(old_ram_size,
2186 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
2187 if (new_ram_size > old_ram_size) {
2188 dirty_memory_extend(old_ram_size, new_ram_size);
2190 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2191 * QLIST (which has an RCU-friendly variant) does not have insertion at
2192 * tail, so save the last element in last_block.
2194 RAMBLOCK_FOREACH(block) {
2195 last_block = block;
2196 if (block->max_length < new_block->max_length) {
2197 break;
2200 if (block) {
2201 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
2202 } else if (last_block) {
2203 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
2204 } else { /* list is empty */
2205 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
2207 ram_list.mru_block = NULL;
2209 /* Write list before version */
2210 smp_wmb();
2211 ram_list.version++;
2212 qemu_mutex_unlock_ramlist();
2214 cpu_physical_memory_set_dirty_range(new_block->offset,
2215 new_block->used_length,
2216 DIRTY_CLIENTS_ALL);
2218 if (new_block->host) {
2219 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2220 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2221 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
2222 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
2223 ram_block_notify_add(new_block->host, new_block->max_length);
2227 #ifdef __linux__
2228 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2229 bool share, int fd,
2230 Error **errp)
2232 RAMBlock *new_block;
2233 Error *local_err = NULL;
2234 int64_t file_size;
2236 if (xen_enabled()) {
2237 error_setg(errp, "-mem-path not supported with Xen");
2238 return NULL;
2241 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2242 error_setg(errp,
2243 "host lacks kvm mmu notifiers, -mem-path unsupported");
2244 return NULL;
2247 if (phys_mem_alloc != qemu_anon_ram_alloc) {
2249 * file_ram_alloc() needs to allocate just like
2250 * phys_mem_alloc, but we haven't bothered to provide
2251 * a hook there.
2253 error_setg(errp,
2254 "-mem-path not supported with this accelerator");
2255 return NULL;
2258 size = HOST_PAGE_ALIGN(size);
2259 file_size = get_file_size(fd);
2260 if (file_size > 0 && file_size < size) {
2261 error_setg(errp, "backing store %s size 0x%" PRIx64
2262 " does not match 'size' option 0x" RAM_ADDR_FMT,
2263 mem_path, file_size, size);
2264 return NULL;
2267 new_block = g_malloc0(sizeof(*new_block));
2268 new_block->mr = mr;
2269 new_block->used_length = size;
2270 new_block->max_length = size;
2271 new_block->flags = share ? RAM_SHARED : 0;
2272 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
2273 if (!new_block->host) {
2274 g_free(new_block);
2275 return NULL;
2278 ram_block_add(new_block, &local_err, share);
2279 if (local_err) {
2280 g_free(new_block);
2281 error_propagate(errp, local_err);
2282 return NULL;
2284 return new_block;
2289 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2290 bool share, const char *mem_path,
2291 Error **errp)
2293 int fd;
2294 bool created;
2295 RAMBlock *block;
2297 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2298 if (fd < 0) {
2299 return NULL;
2302 block = qemu_ram_alloc_from_fd(size, mr, share, fd, errp);
2303 if (!block) {
2304 if (created) {
2305 unlink(mem_path);
2307 close(fd);
2308 return NULL;
2311 return block;
2313 #endif
2315 static
2316 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2317 void (*resized)(const char*,
2318 uint64_t length,
2319 void *host),
2320 void *host, bool resizeable, bool share,
2321 MemoryRegion *mr, Error **errp)
2323 RAMBlock *new_block;
2324 Error *local_err = NULL;
2326 size = HOST_PAGE_ALIGN(size);
2327 max_size = HOST_PAGE_ALIGN(max_size);
2328 new_block = g_malloc0(sizeof(*new_block));
2329 new_block->mr = mr;
2330 new_block->resized = resized;
2331 new_block->used_length = size;
2332 new_block->max_length = max_size;
2333 assert(max_size >= size);
2334 new_block->fd = -1;
2335 new_block->page_size = getpagesize();
2336 new_block->host = host;
2337 if (host) {
2338 new_block->flags |= RAM_PREALLOC;
2340 if (resizeable) {
2341 new_block->flags |= RAM_RESIZEABLE;
2343 ram_block_add(new_block, &local_err, share);
2344 if (local_err) {
2345 g_free(new_block);
2346 error_propagate(errp, local_err);
2347 return NULL;
2349 return new_block;
2352 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2353 MemoryRegion *mr, Error **errp)
2355 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2356 false, mr, errp);
2359 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2360 MemoryRegion *mr, Error **errp)
2362 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2363 share, mr, errp);
2366 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2367 void (*resized)(const char*,
2368 uint64_t length,
2369 void *host),
2370 MemoryRegion *mr, Error **errp)
2372 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2373 false, mr, errp);
2376 static void reclaim_ramblock(RAMBlock *block)
2378 if (block->flags & RAM_PREALLOC) {
2380 } else if (xen_enabled()) {
2381 xen_invalidate_map_cache_entry(block->host);
2382 #ifndef _WIN32
2383 } else if (block->fd >= 0) {
2384 qemu_ram_munmap(block->host, block->max_length);
2385 close(block->fd);
2386 #endif
2387 } else {
2388 qemu_anon_ram_free(block->host, block->max_length);
2390 g_free(block);
2393 void qemu_ram_free(RAMBlock *block)
2395 if (!block) {
2396 return;
2399 if (block->host) {
2400 ram_block_notify_remove(block->host, block->max_length);
2403 qemu_mutex_lock_ramlist();
2404 QLIST_REMOVE_RCU(block, next);
2405 ram_list.mru_block = NULL;
2406 /* Write list before version */
2407 smp_wmb();
2408 ram_list.version++;
2409 call_rcu(block, reclaim_ramblock, rcu);
2410 qemu_mutex_unlock_ramlist();
2413 #ifndef _WIN32
2414 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2416 RAMBlock *block;
2417 ram_addr_t offset;
2418 int flags;
2419 void *area, *vaddr;
2421 RAMBLOCK_FOREACH(block) {
2422 offset = addr - block->offset;
2423 if (offset < block->max_length) {
2424 vaddr = ramblock_ptr(block, offset);
2425 if (block->flags & RAM_PREALLOC) {
2427 } else if (xen_enabled()) {
2428 abort();
2429 } else {
2430 flags = MAP_FIXED;
2431 if (block->fd >= 0) {
2432 flags |= (block->flags & RAM_SHARED ?
2433 MAP_SHARED : MAP_PRIVATE);
2434 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2435 flags, block->fd, offset);
2436 } else {
2438 * Remap needs to match alloc. Accelerators that
2439 * set phys_mem_alloc never remap. If they did,
2440 * we'd need a remap hook here.
2442 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2444 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2445 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2446 flags, -1, 0);
2448 if (area != vaddr) {
2449 error_report("Could not remap addr: "
2450 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2451 length, addr);
2452 exit(1);
2454 memory_try_enable_merging(vaddr, length);
2455 qemu_ram_setup_dump(vaddr, length);
2460 #endif /* !_WIN32 */
2462 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2463 * This should not be used for general purpose DMA. Use address_space_map
2464 * or address_space_rw instead. For local memory (e.g. video ram) that the
2465 * device owns, use memory_region_get_ram_ptr.
2467 * Called within RCU critical section.
2469 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2471 RAMBlock *block = ram_block;
2473 if (block == NULL) {
2474 block = qemu_get_ram_block(addr);
2475 addr -= block->offset;
2478 if (xen_enabled() && block->host == NULL) {
2479 /* We need to check if the requested address is in the RAM
2480 * because we don't want to map the entire memory in QEMU.
2481 * In that case just map until the end of the page.
2483 if (block->offset == 0) {
2484 return xen_map_cache(addr, 0, 0, false);
2487 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2489 return ramblock_ptr(block, addr);
2492 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2493 * but takes a size argument.
2495 * Called within RCU critical section.
2497 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2498 hwaddr *size, bool lock)
2500 RAMBlock *block = ram_block;
2501 if (*size == 0) {
2502 return NULL;
2505 if (block == NULL) {
2506 block = qemu_get_ram_block(addr);
2507 addr -= block->offset;
2509 *size = MIN(*size, block->max_length - addr);
2511 if (xen_enabled() && block->host == NULL) {
2512 /* We need to check if the requested address is in the RAM
2513 * because we don't want to map the entire memory in QEMU.
2514 * In that case just map the requested area.
2516 if (block->offset == 0) {
2517 return xen_map_cache(addr, *size, lock, lock);
2520 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2523 return ramblock_ptr(block, addr);
2526 /* Return the offset of a hostpointer within a ramblock */
2527 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2529 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2530 assert((uintptr_t)host >= (uintptr_t)rb->host);
2531 assert(res < rb->max_length);
2533 return res;
2537 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2538 * in that RAMBlock.
2540 * ptr: Host pointer to look up
2541 * round_offset: If true round the result offset down to a page boundary
2542 * *ram_addr: set to result ram_addr
2543 * *offset: set to result offset within the RAMBlock
2545 * Returns: RAMBlock (or NULL if not found)
2547 * By the time this function returns, the returned pointer is not protected
2548 * by RCU anymore. If the caller is not within an RCU critical section and
2549 * does not hold the iothread lock, it must have other means of protecting the
2550 * pointer, such as a reference to the region that includes the incoming
2551 * ram_addr_t.
2553 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2554 ram_addr_t *offset)
2556 RAMBlock *block;
2557 uint8_t *host = ptr;
2559 if (xen_enabled()) {
2560 ram_addr_t ram_addr;
2561 rcu_read_lock();
2562 ram_addr = xen_ram_addr_from_mapcache(ptr);
2563 block = qemu_get_ram_block(ram_addr);
2564 if (block) {
2565 *offset = ram_addr - block->offset;
2567 rcu_read_unlock();
2568 return block;
2571 rcu_read_lock();
2572 block = atomic_rcu_read(&ram_list.mru_block);
2573 if (block && block->host && host - block->host < block->max_length) {
2574 goto found;
2577 RAMBLOCK_FOREACH(block) {
2578 /* This case append when the block is not mapped. */
2579 if (block->host == NULL) {
2580 continue;
2582 if (host - block->host < block->max_length) {
2583 goto found;
2587 rcu_read_unlock();
2588 return NULL;
2590 found:
2591 *offset = (host - block->host);
2592 if (round_offset) {
2593 *offset &= TARGET_PAGE_MASK;
2595 rcu_read_unlock();
2596 return block;
2600 * Finds the named RAMBlock
2602 * name: The name of RAMBlock to find
2604 * Returns: RAMBlock (or NULL if not found)
2606 RAMBlock *qemu_ram_block_by_name(const char *name)
2608 RAMBlock *block;
2610 RAMBLOCK_FOREACH(block) {
2611 if (!strcmp(name, block->idstr)) {
2612 return block;
2616 return NULL;
2619 /* Some of the softmmu routines need to translate from a host pointer
2620 (typically a TLB entry) back to a ram offset. */
2621 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2623 RAMBlock *block;
2624 ram_addr_t offset;
2626 block = qemu_ram_block_from_host(ptr, false, &offset);
2627 if (!block) {
2628 return RAM_ADDR_INVALID;
2631 return block->offset + offset;
2634 /* Called within RCU critical section. */
2635 void memory_notdirty_write_prepare(NotDirtyInfo *ndi,
2636 CPUState *cpu,
2637 vaddr mem_vaddr,
2638 ram_addr_t ram_addr,
2639 unsigned size)
2641 ndi->cpu = cpu;
2642 ndi->ram_addr = ram_addr;
2643 ndi->mem_vaddr = mem_vaddr;
2644 ndi->size = size;
2645 ndi->pages = NULL;
2647 assert(tcg_enabled());
2648 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
2649 ndi->pages = page_collection_lock(ram_addr, ram_addr + size);
2650 tb_invalidate_phys_page_fast(ndi->pages, ram_addr, size);
2654 /* Called within RCU critical section. */
2655 void memory_notdirty_write_complete(NotDirtyInfo *ndi)
2657 if (ndi->pages) {
2658 page_collection_unlock(ndi->pages);
2659 ndi->pages = NULL;
2662 /* Set both VGA and migration bits for simplicity and to remove
2663 * the notdirty callback faster.
2665 cpu_physical_memory_set_dirty_range(ndi->ram_addr, ndi->size,
2666 DIRTY_CLIENTS_NOCODE);
2667 /* we remove the notdirty callback only if the code has been
2668 flushed */
2669 if (!cpu_physical_memory_is_clean(ndi->ram_addr)) {
2670 tlb_set_dirty(ndi->cpu, ndi->mem_vaddr);
2674 /* Called within RCU critical section. */
2675 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2676 uint64_t val, unsigned size)
2678 NotDirtyInfo ndi;
2680 memory_notdirty_write_prepare(&ndi, current_cpu, current_cpu->mem_io_vaddr,
2681 ram_addr, size);
2683 stn_p(qemu_map_ram_ptr(NULL, ram_addr), size, val);
2684 memory_notdirty_write_complete(&ndi);
2687 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
2688 unsigned size, bool is_write,
2689 MemTxAttrs attrs)
2691 return is_write;
2694 static const MemoryRegionOps notdirty_mem_ops = {
2695 .write = notdirty_mem_write,
2696 .valid.accepts = notdirty_mem_accepts,
2697 .endianness = DEVICE_NATIVE_ENDIAN,
2698 .valid = {
2699 .min_access_size = 1,
2700 .max_access_size = 8,
2701 .unaligned = false,
2703 .impl = {
2704 .min_access_size = 1,
2705 .max_access_size = 8,
2706 .unaligned = false,
2710 /* Generate a debug exception if a watchpoint has been hit. */
2711 static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
2713 CPUState *cpu = current_cpu;
2714 CPUClass *cc = CPU_GET_CLASS(cpu);
2715 target_ulong vaddr;
2716 CPUWatchpoint *wp;
2718 assert(tcg_enabled());
2719 if (cpu->watchpoint_hit) {
2720 /* We re-entered the check after replacing the TB. Now raise
2721 * the debug interrupt so that is will trigger after the
2722 * current instruction. */
2723 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2724 return;
2726 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
2727 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
2728 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2729 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2730 && (wp->flags & flags)) {
2731 if (flags == BP_MEM_READ) {
2732 wp->flags |= BP_WATCHPOINT_HIT_READ;
2733 } else {
2734 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2736 wp->hitaddr = vaddr;
2737 wp->hitattrs = attrs;
2738 if (!cpu->watchpoint_hit) {
2739 if (wp->flags & BP_CPU &&
2740 !cc->debug_check_watchpoint(cpu, wp)) {
2741 wp->flags &= ~BP_WATCHPOINT_HIT;
2742 continue;
2744 cpu->watchpoint_hit = wp;
2746 mmap_lock();
2747 tb_check_watchpoint(cpu);
2748 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2749 cpu->exception_index = EXCP_DEBUG;
2750 mmap_unlock();
2751 cpu_loop_exit(cpu);
2752 } else {
2753 /* Force execution of one insn next time. */
2754 cpu->cflags_next_tb = 1 | curr_cflags();
2755 mmap_unlock();
2756 cpu_loop_exit_noexc(cpu);
2759 } else {
2760 wp->flags &= ~BP_WATCHPOINT_HIT;
2765 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2766 so these check for a hit then pass through to the normal out-of-line
2767 phys routines. */
2768 static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2769 unsigned size, MemTxAttrs attrs)
2771 MemTxResult res;
2772 uint64_t data;
2773 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2774 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2776 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2777 switch (size) {
2778 case 1:
2779 data = address_space_ldub(as, addr, attrs, &res);
2780 break;
2781 case 2:
2782 data = address_space_lduw(as, addr, attrs, &res);
2783 break;
2784 case 4:
2785 data = address_space_ldl(as, addr, attrs, &res);
2786 break;
2787 case 8:
2788 data = address_space_ldq(as, addr, attrs, &res);
2789 break;
2790 default: abort();
2792 *pdata = data;
2793 return res;
2796 static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2797 uint64_t val, unsigned size,
2798 MemTxAttrs attrs)
2800 MemTxResult res;
2801 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2802 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2804 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2805 switch (size) {
2806 case 1:
2807 address_space_stb(as, addr, val, attrs, &res);
2808 break;
2809 case 2:
2810 address_space_stw(as, addr, val, attrs, &res);
2811 break;
2812 case 4:
2813 address_space_stl(as, addr, val, attrs, &res);
2814 break;
2815 case 8:
2816 address_space_stq(as, addr, val, attrs, &res);
2817 break;
2818 default: abort();
2820 return res;
2823 static const MemoryRegionOps watch_mem_ops = {
2824 .read_with_attrs = watch_mem_read,
2825 .write_with_attrs = watch_mem_write,
2826 .endianness = DEVICE_NATIVE_ENDIAN,
2827 .valid = {
2828 .min_access_size = 1,
2829 .max_access_size = 8,
2830 .unaligned = false,
2832 .impl = {
2833 .min_access_size = 1,
2834 .max_access_size = 8,
2835 .unaligned = false,
2839 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2840 MemTxAttrs attrs, uint8_t *buf, int len);
2841 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2842 const uint8_t *buf, int len);
2843 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
2844 bool is_write, MemTxAttrs attrs);
2846 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2847 unsigned len, MemTxAttrs attrs)
2849 subpage_t *subpage = opaque;
2850 uint8_t buf[8];
2851 MemTxResult res;
2853 #if defined(DEBUG_SUBPAGE)
2854 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2855 subpage, len, addr);
2856 #endif
2857 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2858 if (res) {
2859 return res;
2861 *data = ldn_p(buf, len);
2862 return MEMTX_OK;
2865 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2866 uint64_t value, unsigned len, MemTxAttrs attrs)
2868 subpage_t *subpage = opaque;
2869 uint8_t buf[8];
2871 #if defined(DEBUG_SUBPAGE)
2872 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2873 " value %"PRIx64"\n",
2874 __func__, subpage, len, addr, value);
2875 #endif
2876 stn_p(buf, len, value);
2877 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2880 static bool subpage_accepts(void *opaque, hwaddr addr,
2881 unsigned len, bool is_write,
2882 MemTxAttrs attrs)
2884 subpage_t *subpage = opaque;
2885 #if defined(DEBUG_SUBPAGE)
2886 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2887 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2888 #endif
2890 return flatview_access_valid(subpage->fv, addr + subpage->base,
2891 len, is_write, attrs);
2894 static const MemoryRegionOps subpage_ops = {
2895 .read_with_attrs = subpage_read,
2896 .write_with_attrs = subpage_write,
2897 .impl.min_access_size = 1,
2898 .impl.max_access_size = 8,
2899 .valid.min_access_size = 1,
2900 .valid.max_access_size = 8,
2901 .valid.accepts = subpage_accepts,
2902 .endianness = DEVICE_NATIVE_ENDIAN,
2905 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
2906 uint16_t section)
2908 int idx, eidx;
2910 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2911 return -1;
2912 idx = SUBPAGE_IDX(start);
2913 eidx = SUBPAGE_IDX(end);
2914 #if defined(DEBUG_SUBPAGE)
2915 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2916 __func__, mmio, start, end, idx, eidx, section);
2917 #endif
2918 for (; idx <= eidx; idx++) {
2919 mmio->sub_section[idx] = section;
2922 return 0;
2925 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2927 subpage_t *mmio;
2929 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2930 mmio->fv = fv;
2931 mmio->base = base;
2932 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2933 NULL, TARGET_PAGE_SIZE);
2934 mmio->iomem.subpage = true;
2935 #if defined(DEBUG_SUBPAGE)
2936 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2937 mmio, base, TARGET_PAGE_SIZE);
2938 #endif
2939 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
2941 return mmio;
2944 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2946 assert(fv);
2947 MemoryRegionSection section = {
2948 .fv = fv,
2949 .mr = mr,
2950 .offset_within_address_space = 0,
2951 .offset_within_region = 0,
2952 .size = int128_2_64(),
2955 return phys_section_add(map, &section);
2958 static void readonly_mem_write(void *opaque, hwaddr addr,
2959 uint64_t val, unsigned size)
2961 /* Ignore any write to ROM. */
2964 static bool readonly_mem_accepts(void *opaque, hwaddr addr,
2965 unsigned size, bool is_write,
2966 MemTxAttrs attrs)
2968 return is_write;
2971 /* This will only be used for writes, because reads are special cased
2972 * to directly access the underlying host ram.
2974 static const MemoryRegionOps readonly_mem_ops = {
2975 .write = readonly_mem_write,
2976 .valid.accepts = readonly_mem_accepts,
2977 .endianness = DEVICE_NATIVE_ENDIAN,
2978 .valid = {
2979 .min_access_size = 1,
2980 .max_access_size = 8,
2981 .unaligned = false,
2983 .impl = {
2984 .min_access_size = 1,
2985 .max_access_size = 8,
2986 .unaligned = false,
2990 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2991 hwaddr index, MemTxAttrs attrs)
2993 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2994 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2995 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
2996 MemoryRegionSection *sections = d->map.sections;
2998 return &sections[index & ~TARGET_PAGE_MASK];
3001 static void io_mem_init(void)
3003 memory_region_init_io(&io_mem_rom, NULL, &readonly_mem_ops,
3004 NULL, NULL, UINT64_MAX);
3005 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
3006 NULL, UINT64_MAX);
3008 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
3009 * which can be called without the iothread mutex.
3011 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
3012 NULL, UINT64_MAX);
3013 memory_region_clear_global_locking(&io_mem_notdirty);
3015 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
3016 NULL, UINT64_MAX);
3019 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
3021 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
3022 uint16_t n;
3024 n = dummy_section(&d->map, fv, &io_mem_unassigned);
3025 assert(n == PHYS_SECTION_UNASSIGNED);
3026 n = dummy_section(&d->map, fv, &io_mem_notdirty);
3027 assert(n == PHYS_SECTION_NOTDIRTY);
3028 n = dummy_section(&d->map, fv, &io_mem_rom);
3029 assert(n == PHYS_SECTION_ROM);
3030 n = dummy_section(&d->map, fv, &io_mem_watch);
3031 assert(n == PHYS_SECTION_WATCH);
3033 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
3035 return d;
3038 void address_space_dispatch_free(AddressSpaceDispatch *d)
3040 phys_sections_free(&d->map);
3041 g_free(d);
3044 static void tcg_commit(MemoryListener *listener)
3046 CPUAddressSpace *cpuas;
3047 AddressSpaceDispatch *d;
3049 /* since each CPU stores ram addresses in its TLB cache, we must
3050 reset the modified entries */
3051 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
3052 cpu_reloading_memory_map();
3053 /* The CPU and TLB are protected by the iothread lock.
3054 * We reload the dispatch pointer now because cpu_reloading_memory_map()
3055 * may have split the RCU critical section.
3057 d = address_space_to_dispatch(cpuas->as);
3058 atomic_rcu_set(&cpuas->memory_dispatch, d);
3059 tlb_flush(cpuas->cpu);
3062 static void memory_map_init(void)
3064 system_memory = g_malloc(sizeof(*system_memory));
3066 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
3067 address_space_init(&address_space_memory, system_memory, "memory");
3069 system_io = g_malloc(sizeof(*system_io));
3070 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
3071 65536);
3072 address_space_init(&address_space_io, system_io, "I/O");
3075 MemoryRegion *get_system_memory(void)
3077 return system_memory;
3080 MemoryRegion *get_system_io(void)
3082 return system_io;
3085 #endif /* !defined(CONFIG_USER_ONLY) */
3087 /* physical memory access (slow version, mainly for debug) */
3088 #if defined(CONFIG_USER_ONLY)
3089 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3090 uint8_t *buf, int len, int is_write)
3092 int l, flags;
3093 target_ulong page;
3094 void * p;
3096 while (len > 0) {
3097 page = addr & TARGET_PAGE_MASK;
3098 l = (page + TARGET_PAGE_SIZE) - addr;
3099 if (l > len)
3100 l = len;
3101 flags = page_get_flags(page);
3102 if (!(flags & PAGE_VALID))
3103 return -1;
3104 if (is_write) {
3105 if (!(flags & PAGE_WRITE))
3106 return -1;
3107 /* XXX: this code should not depend on lock_user */
3108 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
3109 return -1;
3110 memcpy(p, buf, l);
3111 unlock_user(p, addr, l);
3112 } else {
3113 if (!(flags & PAGE_READ))
3114 return -1;
3115 /* XXX: this code should not depend on lock_user */
3116 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
3117 return -1;
3118 memcpy(buf, p, l);
3119 unlock_user(p, addr, 0);
3121 len -= l;
3122 buf += l;
3123 addr += l;
3125 return 0;
3128 #else
3130 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
3131 hwaddr length)
3133 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
3134 addr += memory_region_get_ram_addr(mr);
3136 /* No early return if dirty_log_mask is or becomes 0, because
3137 * cpu_physical_memory_set_dirty_range will still call
3138 * xen_modified_memory.
3140 if (dirty_log_mask) {
3141 dirty_log_mask =
3142 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
3144 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
3145 assert(tcg_enabled());
3146 mmap_lock();
3147 tb_invalidate_phys_range(addr, addr + length);
3148 mmap_unlock();
3149 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
3151 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
3154 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
3156 unsigned access_size_max = mr->ops->valid.max_access_size;
3158 /* Regions are assumed to support 1-4 byte accesses unless
3159 otherwise specified. */
3160 if (access_size_max == 0) {
3161 access_size_max = 4;
3164 /* Bound the maximum access by the alignment of the address. */
3165 if (!mr->ops->impl.unaligned) {
3166 unsigned align_size_max = addr & -addr;
3167 if (align_size_max != 0 && align_size_max < access_size_max) {
3168 access_size_max = align_size_max;
3172 /* Don't attempt accesses larger than the maximum. */
3173 if (l > access_size_max) {
3174 l = access_size_max;
3176 l = pow2floor(l);
3178 return l;
3181 static bool prepare_mmio_access(MemoryRegion *mr)
3183 bool unlocked = !qemu_mutex_iothread_locked();
3184 bool release_lock = false;
3186 if (unlocked && mr->global_locking) {
3187 qemu_mutex_lock_iothread();
3188 unlocked = false;
3189 release_lock = true;
3191 if (mr->flush_coalesced_mmio) {
3192 if (unlocked) {
3193 qemu_mutex_lock_iothread();
3195 qemu_flush_coalesced_mmio_buffer();
3196 if (unlocked) {
3197 qemu_mutex_unlock_iothread();
3201 return release_lock;
3204 /* Called within RCU critical section. */
3205 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
3206 MemTxAttrs attrs,
3207 const uint8_t *buf,
3208 int len, hwaddr addr1,
3209 hwaddr l, MemoryRegion *mr)
3211 uint8_t *ptr;
3212 uint64_t val;
3213 MemTxResult result = MEMTX_OK;
3214 bool release_lock = false;
3216 for (;;) {
3217 if (!memory_access_is_direct(mr, true)) {
3218 release_lock |= prepare_mmio_access(mr);
3219 l = memory_access_size(mr, l, addr1);
3220 /* XXX: could force current_cpu to NULL to avoid
3221 potential bugs */
3222 val = ldn_p(buf, l);
3223 result |= memory_region_dispatch_write(mr, addr1, val, l, attrs);
3224 } else {
3225 /* RAM case */
3226 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3227 memcpy(ptr, buf, l);
3228 invalidate_and_set_dirty(mr, addr1, l);
3231 if (release_lock) {
3232 qemu_mutex_unlock_iothread();
3233 release_lock = false;
3236 len -= l;
3237 buf += l;
3238 addr += l;
3240 if (!len) {
3241 break;
3244 l = len;
3245 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
3248 return result;
3251 /* Called from RCU critical section. */
3252 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
3253 const uint8_t *buf, int len)
3255 hwaddr l;
3256 hwaddr addr1;
3257 MemoryRegion *mr;
3258 MemTxResult result = MEMTX_OK;
3260 l = len;
3261 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
3262 result = flatview_write_continue(fv, addr, attrs, buf, len,
3263 addr1, l, mr);
3265 return result;
3268 /* Called within RCU critical section. */
3269 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
3270 MemTxAttrs attrs, uint8_t *buf,
3271 int len, hwaddr addr1, hwaddr l,
3272 MemoryRegion *mr)
3274 uint8_t *ptr;
3275 uint64_t val;
3276 MemTxResult result = MEMTX_OK;
3277 bool release_lock = false;
3279 for (;;) {
3280 if (!memory_access_is_direct(mr, false)) {
3281 /* I/O case */
3282 release_lock |= prepare_mmio_access(mr);
3283 l = memory_access_size(mr, l, addr1);
3284 result |= memory_region_dispatch_read(mr, addr1, &val, l, attrs);
3285 stn_p(buf, l, val);
3286 } else {
3287 /* RAM case */
3288 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3289 memcpy(buf, ptr, l);
3292 if (release_lock) {
3293 qemu_mutex_unlock_iothread();
3294 release_lock = false;
3297 len -= l;
3298 buf += l;
3299 addr += l;
3301 if (!len) {
3302 break;
3305 l = len;
3306 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3309 return result;
3312 /* Called from RCU critical section. */
3313 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
3314 MemTxAttrs attrs, uint8_t *buf, int len)
3316 hwaddr l;
3317 hwaddr addr1;
3318 MemoryRegion *mr;
3320 l = len;
3321 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3322 return flatview_read_continue(fv, addr, attrs, buf, len,
3323 addr1, l, mr);
3326 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3327 MemTxAttrs attrs, uint8_t *buf, int len)
3329 MemTxResult result = MEMTX_OK;
3330 FlatView *fv;
3332 if (len > 0) {
3333 rcu_read_lock();
3334 fv = address_space_to_flatview(as);
3335 result = flatview_read(fv, addr, attrs, buf, len);
3336 rcu_read_unlock();
3339 return result;
3342 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
3343 MemTxAttrs attrs,
3344 const uint8_t *buf, int len)
3346 MemTxResult result = MEMTX_OK;
3347 FlatView *fv;
3349 if (len > 0) {
3350 rcu_read_lock();
3351 fv = address_space_to_flatview(as);
3352 result = flatview_write(fv, addr, attrs, buf, len);
3353 rcu_read_unlock();
3356 return result;
3359 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3360 uint8_t *buf, int len, bool is_write)
3362 if (is_write) {
3363 return address_space_write(as, addr, attrs, buf, len);
3364 } else {
3365 return address_space_read_full(as, addr, attrs, buf, len);
3369 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
3370 int len, int is_write)
3372 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3373 buf, len, is_write);
3376 enum write_rom_type {
3377 WRITE_DATA,
3378 FLUSH_CACHE,
3381 static inline void cpu_physical_memory_write_rom_internal(AddressSpace *as,
3382 hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
3384 hwaddr l;
3385 uint8_t *ptr;
3386 hwaddr addr1;
3387 MemoryRegion *mr;
3389 rcu_read_lock();
3390 while (len > 0) {
3391 l = len;
3392 mr = address_space_translate(as, addr, &addr1, &l, true,
3393 MEMTXATTRS_UNSPECIFIED);
3395 if (!(memory_region_is_ram(mr) ||
3396 memory_region_is_romd(mr))) {
3397 l = memory_access_size(mr, l, addr1);
3398 } else {
3399 /* ROM/RAM case */
3400 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3401 switch (type) {
3402 case WRITE_DATA:
3403 memcpy(ptr, buf, l);
3404 invalidate_and_set_dirty(mr, addr1, l);
3405 break;
3406 case FLUSH_CACHE:
3407 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
3408 break;
3411 len -= l;
3412 buf += l;
3413 addr += l;
3415 rcu_read_unlock();
3418 /* used for ROM loading : can write in RAM and ROM */
3419 void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
3420 const uint8_t *buf, int len)
3422 cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
3425 void cpu_flush_icache_range(hwaddr start, int len)
3428 * This function should do the same thing as an icache flush that was
3429 * triggered from within the guest. For TCG we are always cache coherent,
3430 * so there is no need to flush anything. For KVM / Xen we need to flush
3431 * the host's instruction cache at least.
3433 if (tcg_enabled()) {
3434 return;
3437 cpu_physical_memory_write_rom_internal(&address_space_memory,
3438 start, NULL, len, FLUSH_CACHE);
3441 typedef struct {
3442 MemoryRegion *mr;
3443 void *buffer;
3444 hwaddr addr;
3445 hwaddr len;
3446 bool in_use;
3447 } BounceBuffer;
3449 static BounceBuffer bounce;
3451 typedef struct MapClient {
3452 QEMUBH *bh;
3453 QLIST_ENTRY(MapClient) link;
3454 } MapClient;
3456 QemuMutex map_client_list_lock;
3457 static QLIST_HEAD(map_client_list, MapClient) map_client_list
3458 = QLIST_HEAD_INITIALIZER(map_client_list);
3460 static void cpu_unregister_map_client_do(MapClient *client)
3462 QLIST_REMOVE(client, link);
3463 g_free(client);
3466 static void cpu_notify_map_clients_locked(void)
3468 MapClient *client;
3470 while (!QLIST_EMPTY(&map_client_list)) {
3471 client = QLIST_FIRST(&map_client_list);
3472 qemu_bh_schedule(client->bh);
3473 cpu_unregister_map_client_do(client);
3477 void cpu_register_map_client(QEMUBH *bh)
3479 MapClient *client = g_malloc(sizeof(*client));
3481 qemu_mutex_lock(&map_client_list_lock);
3482 client->bh = bh;
3483 QLIST_INSERT_HEAD(&map_client_list, client, link);
3484 if (!atomic_read(&bounce.in_use)) {
3485 cpu_notify_map_clients_locked();
3487 qemu_mutex_unlock(&map_client_list_lock);
3490 void cpu_exec_init_all(void)
3492 qemu_mutex_init(&ram_list.mutex);
3493 /* The data structures we set up here depend on knowing the page size,
3494 * so no more changes can be made after this point.
3495 * In an ideal world, nothing we did before we had finished the
3496 * machine setup would care about the target page size, and we could
3497 * do this much later, rather than requiring board models to state
3498 * up front what their requirements are.
3500 finalize_target_page_bits();
3501 io_mem_init();
3502 memory_map_init();
3503 qemu_mutex_init(&map_client_list_lock);
3506 void cpu_unregister_map_client(QEMUBH *bh)
3508 MapClient *client;
3510 qemu_mutex_lock(&map_client_list_lock);
3511 QLIST_FOREACH(client, &map_client_list, link) {
3512 if (client->bh == bh) {
3513 cpu_unregister_map_client_do(client);
3514 break;
3517 qemu_mutex_unlock(&map_client_list_lock);
3520 static void cpu_notify_map_clients(void)
3522 qemu_mutex_lock(&map_client_list_lock);
3523 cpu_notify_map_clients_locked();
3524 qemu_mutex_unlock(&map_client_list_lock);
3527 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
3528 bool is_write, MemTxAttrs attrs)
3530 MemoryRegion *mr;
3531 hwaddr l, xlat;
3533 while (len > 0) {
3534 l = len;
3535 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3536 if (!memory_access_is_direct(mr, is_write)) {
3537 l = memory_access_size(mr, l, addr);
3538 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3539 return false;
3543 len -= l;
3544 addr += l;
3546 return true;
3549 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3550 int len, bool is_write,
3551 MemTxAttrs attrs)
3553 FlatView *fv;
3554 bool result;
3556 rcu_read_lock();
3557 fv = address_space_to_flatview(as);
3558 result = flatview_access_valid(fv, addr, len, is_write, attrs);
3559 rcu_read_unlock();
3560 return result;
3563 static hwaddr
3564 flatview_extend_translation(FlatView *fv, hwaddr addr,
3565 hwaddr target_len,
3566 MemoryRegion *mr, hwaddr base, hwaddr len,
3567 bool is_write, MemTxAttrs attrs)
3569 hwaddr done = 0;
3570 hwaddr xlat;
3571 MemoryRegion *this_mr;
3573 for (;;) {
3574 target_len -= len;
3575 addr += len;
3576 done += len;
3577 if (target_len == 0) {
3578 return done;
3581 len = target_len;
3582 this_mr = flatview_translate(fv, addr, &xlat,
3583 &len, is_write, attrs);
3584 if (this_mr != mr || xlat != base + done) {
3585 return done;
3590 /* Map a physical memory region into a host virtual address.
3591 * May map a subset of the requested range, given by and returned in *plen.
3592 * May return NULL if resources needed to perform the mapping are exhausted.
3593 * Use only for reads OR writes - not for read-modify-write operations.
3594 * Use cpu_register_map_client() to know when retrying the map operation is
3595 * likely to succeed.
3597 void *address_space_map(AddressSpace *as,
3598 hwaddr addr,
3599 hwaddr *plen,
3600 bool is_write,
3601 MemTxAttrs attrs)
3603 hwaddr len = *plen;
3604 hwaddr l, xlat;
3605 MemoryRegion *mr;
3606 void *ptr;
3607 FlatView *fv;
3609 if (len == 0) {
3610 return NULL;
3613 l = len;
3614 rcu_read_lock();
3615 fv = address_space_to_flatview(as);
3616 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3618 if (!memory_access_is_direct(mr, is_write)) {
3619 if (atomic_xchg(&bounce.in_use, true)) {
3620 rcu_read_unlock();
3621 return NULL;
3623 /* Avoid unbounded allocations */
3624 l = MIN(l, TARGET_PAGE_SIZE);
3625 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3626 bounce.addr = addr;
3627 bounce.len = l;
3629 memory_region_ref(mr);
3630 bounce.mr = mr;
3631 if (!is_write) {
3632 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3633 bounce.buffer, l);
3636 rcu_read_unlock();
3637 *plen = l;
3638 return bounce.buffer;
3642 memory_region_ref(mr);
3643 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3644 l, is_write, attrs);
3645 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3646 rcu_read_unlock();
3648 return ptr;
3651 /* Unmaps a memory region previously mapped by address_space_map().
3652 * Will also mark the memory as dirty if is_write == 1. access_len gives
3653 * the amount of memory that was actually read or written by the caller.
3655 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3656 int is_write, hwaddr access_len)
3658 if (buffer != bounce.buffer) {
3659 MemoryRegion *mr;
3660 ram_addr_t addr1;
3662 mr = memory_region_from_host(buffer, &addr1);
3663 assert(mr != NULL);
3664 if (is_write) {
3665 invalidate_and_set_dirty(mr, addr1, access_len);
3667 if (xen_enabled()) {
3668 xen_invalidate_map_cache_entry(buffer);
3670 memory_region_unref(mr);
3671 return;
3673 if (is_write) {
3674 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3675 bounce.buffer, access_len);
3677 qemu_vfree(bounce.buffer);
3678 bounce.buffer = NULL;
3679 memory_region_unref(bounce.mr);
3680 atomic_mb_set(&bounce.in_use, false);
3681 cpu_notify_map_clients();
3684 void *cpu_physical_memory_map(hwaddr addr,
3685 hwaddr *plen,
3686 int is_write)
3688 return address_space_map(&address_space_memory, addr, plen, is_write,
3689 MEMTXATTRS_UNSPECIFIED);
3692 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3693 int is_write, hwaddr access_len)
3695 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3698 #define ARG1_DECL AddressSpace *as
3699 #define ARG1 as
3700 #define SUFFIX
3701 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3702 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3703 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3704 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3705 #define RCU_READ_LOCK(...) rcu_read_lock()
3706 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3707 #include "memory_ldst.inc.c"
3709 int64_t address_space_cache_init(MemoryRegionCache *cache,
3710 AddressSpace *as,
3711 hwaddr addr,
3712 hwaddr len,
3713 bool is_write)
3715 AddressSpaceDispatch *d;
3716 hwaddr l;
3717 MemoryRegion *mr;
3719 assert(len > 0);
3721 l = len;
3722 cache->fv = address_space_get_flatview(as);
3723 d = flatview_to_dispatch(cache->fv);
3724 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3726 mr = cache->mrs.mr;
3727 memory_region_ref(mr);
3728 if (memory_access_is_direct(mr, is_write)) {
3729 /* We don't care about the memory attributes here as we're only
3730 * doing this if we found actual RAM, which behaves the same
3731 * regardless of attributes; so UNSPECIFIED is fine.
3733 l = flatview_extend_translation(cache->fv, addr, len, mr,
3734 cache->xlat, l, is_write,
3735 MEMTXATTRS_UNSPECIFIED);
3736 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3737 } else {
3738 cache->ptr = NULL;
3741 cache->len = l;
3742 cache->is_write = is_write;
3743 return l;
3746 void address_space_cache_invalidate(MemoryRegionCache *cache,
3747 hwaddr addr,
3748 hwaddr access_len)
3750 assert(cache->is_write);
3751 if (likely(cache->ptr)) {
3752 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3756 void address_space_cache_destroy(MemoryRegionCache *cache)
3758 if (!cache->mrs.mr) {
3759 return;
3762 if (xen_enabled()) {
3763 xen_invalidate_map_cache_entry(cache->ptr);
3765 memory_region_unref(cache->mrs.mr);
3766 flatview_unref(cache->fv);
3767 cache->mrs.mr = NULL;
3768 cache->fv = NULL;
3771 /* Called from RCU critical section. This function has the same
3772 * semantics as address_space_translate, but it only works on a
3773 * predefined range of a MemoryRegion that was mapped with
3774 * address_space_cache_init.
3776 static inline MemoryRegion *address_space_translate_cached(
3777 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3778 hwaddr *plen, bool is_write, MemTxAttrs attrs)
3780 MemoryRegionSection section;
3781 MemoryRegion *mr;
3782 IOMMUMemoryRegion *iommu_mr;
3783 AddressSpace *target_as;
3785 assert(!cache->ptr);
3786 *xlat = addr + cache->xlat;
3788 mr = cache->mrs.mr;
3789 iommu_mr = memory_region_get_iommu(mr);
3790 if (!iommu_mr) {
3791 /* MMIO region. */
3792 return mr;
3795 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3796 NULL, is_write, true,
3797 &target_as, attrs);
3798 return section.mr;
3801 /* Called from RCU critical section. address_space_read_cached uses this
3802 * out of line function when the target is an MMIO or IOMMU region.
3804 void
3805 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3806 void *buf, int len)
3808 hwaddr addr1, l;
3809 MemoryRegion *mr;
3811 l = len;
3812 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3813 MEMTXATTRS_UNSPECIFIED);
3814 flatview_read_continue(cache->fv,
3815 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3816 addr1, l, mr);
3819 /* Called from RCU critical section. address_space_write_cached uses this
3820 * out of line function when the target is an MMIO or IOMMU region.
3822 void
3823 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3824 const void *buf, int len)
3826 hwaddr addr1, l;
3827 MemoryRegion *mr;
3829 l = len;
3830 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3831 MEMTXATTRS_UNSPECIFIED);
3832 flatview_write_continue(cache->fv,
3833 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3834 addr1, l, mr);
3837 #define ARG1_DECL MemoryRegionCache *cache
3838 #define ARG1 cache
3839 #define SUFFIX _cached_slow
3840 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3841 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3842 #define MAP_RAM(mr, ofs) (cache->ptr + (ofs - cache->xlat))
3843 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3844 #define RCU_READ_LOCK() ((void)0)
3845 #define RCU_READ_UNLOCK() ((void)0)
3846 #include "memory_ldst.inc.c"
3848 /* virtual memory access for debug (includes writing to ROM) */
3849 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3850 uint8_t *buf, int len, int is_write)
3852 int l;
3853 hwaddr phys_addr;
3854 target_ulong page;
3856 cpu_synchronize_state(cpu);
3857 while (len > 0) {
3858 int asidx;
3859 MemTxAttrs attrs;
3861 page = addr & TARGET_PAGE_MASK;
3862 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3863 asidx = cpu_asidx_from_attrs(cpu, attrs);
3864 /* if no physical page mapped, return an error */
3865 if (phys_addr == -1)
3866 return -1;
3867 l = (page + TARGET_PAGE_SIZE) - addr;
3868 if (l > len)
3869 l = len;
3870 phys_addr += (addr & ~TARGET_PAGE_MASK);
3871 if (is_write) {
3872 cpu_physical_memory_write_rom(cpu->cpu_ases[asidx].as,
3873 phys_addr, buf, l);
3874 } else {
3875 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3876 MEMTXATTRS_UNSPECIFIED,
3877 buf, l, 0);
3879 len -= l;
3880 buf += l;
3881 addr += l;
3883 return 0;
3887 * Allows code that needs to deal with migration bitmaps etc to still be built
3888 * target independent.
3890 size_t qemu_target_page_size(void)
3892 return TARGET_PAGE_SIZE;
3895 int qemu_target_page_bits(void)
3897 return TARGET_PAGE_BITS;
3900 int qemu_target_page_bits_min(void)
3902 return TARGET_PAGE_BITS_MIN;
3904 #endif
3907 * A helper function for the _utterly broken_ virtio device model to find out if
3908 * it's running on a big endian machine. Don't do this at home kids!
3910 bool target_words_bigendian(void);
3911 bool target_words_bigendian(void)
3913 #if defined(TARGET_WORDS_BIGENDIAN)
3914 return true;
3915 #else
3916 return false;
3917 #endif
3920 #ifndef CONFIG_USER_ONLY
3921 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3923 MemoryRegion*mr;
3924 hwaddr l = 1;
3925 bool res;
3927 rcu_read_lock();
3928 mr = address_space_translate(&address_space_memory,
3929 phys_addr, &phys_addr, &l, false,
3930 MEMTXATTRS_UNSPECIFIED);
3932 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3933 rcu_read_unlock();
3934 return res;
3937 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3939 RAMBlock *block;
3940 int ret = 0;
3942 rcu_read_lock();
3943 RAMBLOCK_FOREACH(block) {
3944 ret = func(block->idstr, block->host, block->offset,
3945 block->used_length, opaque);
3946 if (ret) {
3947 break;
3950 rcu_read_unlock();
3951 return ret;
3954 int qemu_ram_foreach_migratable_block(RAMBlockIterFunc func, void *opaque)
3956 RAMBlock *block;
3957 int ret = 0;
3959 rcu_read_lock();
3960 RAMBLOCK_FOREACH(block) {
3961 if (!qemu_ram_is_migratable(block)) {
3962 continue;
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;
3975 * Unmap pages of memory from start to start+length such that
3976 * they a) read as 0, b) Trigger whatever fault mechanism
3977 * the OS provides for postcopy.
3978 * The pages must be unmapped by the end of the function.
3979 * Returns: 0 on success, none-0 on failure
3982 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3984 int ret = -1;
3986 uint8_t *host_startaddr = rb->host + start;
3988 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
3989 error_report("ram_block_discard_range: Unaligned start address: %p",
3990 host_startaddr);
3991 goto err;
3994 if ((start + length) <= rb->used_length) {
3995 bool need_madvise, need_fallocate;
3996 uint8_t *host_endaddr = host_startaddr + length;
3997 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
3998 error_report("ram_block_discard_range: Unaligned end address: %p",
3999 host_endaddr);
4000 goto err;
4003 errno = ENOTSUP; /* If we are missing MADVISE etc */
4005 /* The logic here is messy;
4006 * madvise DONTNEED fails for hugepages
4007 * fallocate works on hugepages and shmem
4009 need_madvise = (rb->page_size == qemu_host_page_size);
4010 need_fallocate = rb->fd != -1;
4011 if (need_fallocate) {
4012 /* For a file, this causes the area of the file to be zero'd
4013 * if read, and for hugetlbfs also causes it to be unmapped
4014 * so a userfault will trigger.
4016 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
4017 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
4018 start, length);
4019 if (ret) {
4020 ret = -errno;
4021 error_report("ram_block_discard_range: Failed to fallocate "
4022 "%s:%" PRIx64 " +%zx (%d)",
4023 rb->idstr, start, length, ret);
4024 goto err;
4026 #else
4027 ret = -ENOSYS;
4028 error_report("ram_block_discard_range: fallocate not available/file"
4029 "%s:%" PRIx64 " +%zx (%d)",
4030 rb->idstr, start, length, ret);
4031 goto err;
4032 #endif
4034 if (need_madvise) {
4035 /* For normal RAM this causes it to be unmapped,
4036 * for shared memory it causes the local mapping to disappear
4037 * and to fall back on the file contents (which we just
4038 * fallocate'd away).
4040 #if defined(CONFIG_MADVISE)
4041 ret = madvise(host_startaddr, length, MADV_DONTNEED);
4042 if (ret) {
4043 ret = -errno;
4044 error_report("ram_block_discard_range: Failed to discard range "
4045 "%s:%" PRIx64 " +%zx (%d)",
4046 rb->idstr, start, length, ret);
4047 goto err;
4049 #else
4050 ret = -ENOSYS;
4051 error_report("ram_block_discard_range: MADVISE not available"
4052 "%s:%" PRIx64 " +%zx (%d)",
4053 rb->idstr, start, length, ret);
4054 goto err;
4055 #endif
4057 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
4058 need_madvise, need_fallocate, ret);
4059 } else {
4060 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
4061 "/%zx/" RAM_ADDR_FMT")",
4062 rb->idstr, start, length, rb->used_length);
4065 err:
4066 return ret;
4069 #endif
4071 void page_size_init(void)
4073 /* NOTE: we can always suppose that qemu_host_page_size >=
4074 TARGET_PAGE_SIZE */
4075 if (qemu_host_page_size == 0) {
4076 qemu_host_page_size = qemu_real_host_page_size;
4078 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
4079 qemu_host_page_size = TARGET_PAGE_SIZE;
4081 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;
4084 #if !defined(CONFIG_USER_ONLY)
4086 static void mtree_print_phys_entries(fprintf_function mon, void *f,
4087 int start, int end, int skip, int ptr)
4089 if (start == end - 1) {
4090 mon(f, "\t%3d ", start);
4091 } else {
4092 mon(f, "\t%3d..%-3d ", start, end - 1);
4094 mon(f, " skip=%d ", skip);
4095 if (ptr == PHYS_MAP_NODE_NIL) {
4096 mon(f, " ptr=NIL");
4097 } else if (!skip) {
4098 mon(f, " ptr=#%d", ptr);
4099 } else {
4100 mon(f, " ptr=[%d]", ptr);
4102 mon(f, "\n");
4105 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
4106 int128_sub((size), int128_one())) : 0)
4108 void mtree_print_dispatch(fprintf_function mon, void *f,
4109 AddressSpaceDispatch *d, MemoryRegion *root)
4111 int i;
4113 mon(f, " Dispatch\n");
4114 mon(f, " Physical sections\n");
4116 for (i = 0; i < d->map.sections_nb; ++i) {
4117 MemoryRegionSection *s = d->map.sections + i;
4118 const char *names[] = { " [unassigned]", " [not dirty]",
4119 " [ROM]", " [watch]" };
4121 mon(f, " #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx " %s%s%s%s%s",
4123 s->offset_within_address_space,
4124 s->offset_within_address_space + MR_SIZE(s->mr->size),
4125 s->mr->name ? s->mr->name : "(noname)",
4126 i < ARRAY_SIZE(names) ? names[i] : "",
4127 s->mr == root ? " [ROOT]" : "",
4128 s == d->mru_section ? " [MRU]" : "",
4129 s->mr->is_iommu ? " [iommu]" : "");
4131 if (s->mr->alias) {
4132 mon(f, " alias=%s", s->mr->alias->name ?
4133 s->mr->alias->name : "noname");
4135 mon(f, "\n");
4138 mon(f, " Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
4139 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
4140 for (i = 0; i < d->map.nodes_nb; ++i) {
4141 int j, jprev;
4142 PhysPageEntry prev;
4143 Node *n = d->map.nodes + i;
4145 mon(f, " [%d]\n", i);
4147 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
4148 PhysPageEntry *pe = *n + j;
4150 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
4151 continue;
4154 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
4156 jprev = j;
4157 prev = *pe;
4160 if (jprev != ARRAY_SIZE(*n)) {
4161 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
4166 #endif