win32: Installer does not depend on install-doc
[qemu/ar7.git] / exec.c
blobc7898d869544bb787ef166445485363a46d5d714
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/>.
20 #include "qemu/osdep.h"
21 #include "qemu-common.h"
22 #include "qapi/error.h"
24 #include "qemu/cutils.h"
25 #include "cpu.h"
26 #include "exec/exec-all.h"
27 #include "exec/target_page.h"
28 #include "tcg.h"
29 #include "hw/qdev-core.h"
30 #include "hw/qdev-properties.h"
31 #if !defined(CONFIG_USER_ONLY)
32 #include "hw/boards.h"
33 #include "hw/xen/xen.h"
34 #endif
35 #include "sysemu/kvm.h"
36 #include "sysemu/sysemu.h"
37 #include "sysemu/tcg.h"
38 #include "qemu/timer.h"
39 #include "qemu/config-file.h"
40 #include "qemu/error-report.h"
41 #include "qemu/qemu-print.h"
42 #if defined(CONFIG_USER_ONLY)
43 #include "qemu.h"
44 #else /* !CONFIG_USER_ONLY */
45 #include "hw/hw.h"
46 #include "exec/memory.h"
47 #include "exec/ioport.h"
48 #include "sysemu/dma.h"
49 #include "sysemu/numa.h"
50 #include "sysemu/hw_accel.h"
51 #include "exec/address-spaces.h"
52 #include "sysemu/xen-mapcache.h"
53 #include "trace-root.h"
55 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
56 #include <linux/falloc.h>
57 #endif
59 #endif
60 #include "qemu/rcu_queue.h"
61 #include "qemu/main-loop.h"
62 #include "translate-all.h"
63 #include "sysemu/replay.h"
65 #include "exec/memory-internal.h"
66 #include "exec/ram_addr.h"
67 #include "exec/log.h"
69 #include "migration/vmstate.h"
71 #include "qemu/range.h"
72 #ifndef _WIN32
73 #include "qemu/mmap-alloc.h"
74 #endif
76 #include "monitor/monitor.h"
78 //#define DEBUG_SUBPAGE
80 #if !defined(CONFIG_USER_ONLY)
81 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
82 * are protected by the ramlist lock.
84 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
86 static MemoryRegion *system_memory;
87 static MemoryRegion *system_io;
89 AddressSpace address_space_io;
90 AddressSpace address_space_memory;
92 MemoryRegion io_mem_rom, io_mem_notdirty;
93 static MemoryRegion io_mem_unassigned;
94 #endif
96 #ifdef TARGET_PAGE_BITS_VARY
97 int target_page_bits;
98 bool target_page_bits_decided;
99 #endif
101 CPUTailQ cpus = QTAILQ_HEAD_INITIALIZER(cpus);
103 /* current CPU in the current thread. It is only valid inside
104 cpu_exec() */
105 __thread CPUState *current_cpu;
106 /* 0 = Do not count executed instructions.
107 1 = Precise instruction counting.
108 2 = Adaptive rate instruction counting. */
109 int use_icount;
111 uintptr_t qemu_host_page_size;
112 intptr_t qemu_host_page_mask;
114 bool set_preferred_target_page_bits(int bits)
116 /* The target page size is the lowest common denominator for all
117 * the CPUs in the system, so we can only make it smaller, never
118 * larger. And we can't make it smaller once we've committed to
119 * a particular size.
121 #ifdef TARGET_PAGE_BITS_VARY
122 assert(bits >= TARGET_PAGE_BITS_MIN);
123 if (target_page_bits == 0 || target_page_bits > bits) {
124 if (target_page_bits_decided) {
125 return false;
127 target_page_bits = bits;
129 #endif
130 return true;
133 #if !defined(CONFIG_USER_ONLY)
135 static void finalize_target_page_bits(void)
137 #ifdef TARGET_PAGE_BITS_VARY
138 if (target_page_bits == 0) {
139 target_page_bits = TARGET_PAGE_BITS_MIN;
141 target_page_bits_decided = true;
142 #endif
145 typedef struct PhysPageEntry PhysPageEntry;
147 struct PhysPageEntry {
148 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
149 uint32_t skip : 6;
150 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
151 uint32_t ptr : 26;
154 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
156 /* Size of the L2 (and L3, etc) page tables. */
157 #define ADDR_SPACE_BITS 64
159 #define P_L2_BITS 9
160 #define P_L2_SIZE (1 << P_L2_BITS)
162 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
164 typedef PhysPageEntry Node[P_L2_SIZE];
166 typedef struct PhysPageMap {
167 struct rcu_head rcu;
169 unsigned sections_nb;
170 unsigned sections_nb_alloc;
171 unsigned nodes_nb;
172 unsigned nodes_nb_alloc;
173 Node *nodes;
174 MemoryRegionSection *sections;
175 } PhysPageMap;
177 struct AddressSpaceDispatch {
178 MemoryRegionSection *mru_section;
179 /* This is a multi-level map on the physical address space.
180 * The bottom level has pointers to MemoryRegionSections.
182 PhysPageEntry phys_map;
183 PhysPageMap map;
186 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
187 typedef struct subpage_t {
188 MemoryRegion iomem;
189 FlatView *fv;
190 hwaddr base;
191 uint16_t sub_section[];
192 } subpage_t;
194 #define PHYS_SECTION_UNASSIGNED 0
195 #define PHYS_SECTION_NOTDIRTY 1
196 #define PHYS_SECTION_ROM 2
197 #define PHYS_SECTION_WATCH 3
199 static void io_mem_init(void);
200 static void memory_map_init(void);
201 static void tcg_commit(MemoryListener *listener);
203 static MemoryRegion io_mem_watch;
206 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
207 * @cpu: the CPU whose AddressSpace this is
208 * @as: the AddressSpace itself
209 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
210 * @tcg_as_listener: listener for tracking changes to the AddressSpace
212 struct CPUAddressSpace {
213 CPUState *cpu;
214 AddressSpace *as;
215 struct AddressSpaceDispatch *memory_dispatch;
216 MemoryListener tcg_as_listener;
219 struct DirtyBitmapSnapshot {
220 ram_addr_t start;
221 ram_addr_t end;
222 unsigned long dirty[];
225 #endif
227 #if !defined(CONFIG_USER_ONLY)
229 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
231 static unsigned alloc_hint = 16;
232 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
233 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, alloc_hint);
234 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, map->nodes_nb + nodes);
235 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
236 alloc_hint = map->nodes_nb_alloc;
240 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
242 unsigned i;
243 uint32_t ret;
244 PhysPageEntry e;
245 PhysPageEntry *p;
247 ret = map->nodes_nb++;
248 p = map->nodes[ret];
249 assert(ret != PHYS_MAP_NODE_NIL);
250 assert(ret != map->nodes_nb_alloc);
252 e.skip = leaf ? 0 : 1;
253 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
254 for (i = 0; i < P_L2_SIZE; ++i) {
255 memcpy(&p[i], &e, sizeof(e));
257 return ret;
260 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
261 hwaddr *index, hwaddr *nb, uint16_t leaf,
262 int level)
264 PhysPageEntry *p;
265 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
267 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
268 lp->ptr = phys_map_node_alloc(map, level == 0);
270 p = map->nodes[lp->ptr];
271 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
273 while (*nb && lp < &p[P_L2_SIZE]) {
274 if ((*index & (step - 1)) == 0 && *nb >= step) {
275 lp->skip = 0;
276 lp->ptr = leaf;
277 *index += step;
278 *nb -= step;
279 } else {
280 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
282 ++lp;
286 static void phys_page_set(AddressSpaceDispatch *d,
287 hwaddr index, hwaddr nb,
288 uint16_t leaf)
290 /* Wildly overreserve - it doesn't matter much. */
291 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
293 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
296 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
297 * and update our entry so we can skip it and go directly to the destination.
299 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
301 unsigned valid_ptr = P_L2_SIZE;
302 int valid = 0;
303 PhysPageEntry *p;
304 int i;
306 if (lp->ptr == PHYS_MAP_NODE_NIL) {
307 return;
310 p = nodes[lp->ptr];
311 for (i = 0; i < P_L2_SIZE; i++) {
312 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
313 continue;
316 valid_ptr = i;
317 valid++;
318 if (p[i].skip) {
319 phys_page_compact(&p[i], nodes);
323 /* We can only compress if there's only one child. */
324 if (valid != 1) {
325 return;
328 assert(valid_ptr < P_L2_SIZE);
330 /* Don't compress if it won't fit in the # of bits we have. */
331 if (lp->skip + p[valid_ptr].skip >= (1 << 3)) {
332 return;
335 lp->ptr = p[valid_ptr].ptr;
336 if (!p[valid_ptr].skip) {
337 /* If our only child is a leaf, make this a leaf. */
338 /* By design, we should have made this node a leaf to begin with so we
339 * should never reach here.
340 * But since it's so simple to handle this, let's do it just in case we
341 * change this rule.
343 lp->skip = 0;
344 } else {
345 lp->skip += p[valid_ptr].skip;
349 void address_space_dispatch_compact(AddressSpaceDispatch *d)
351 if (d->phys_map.skip) {
352 phys_page_compact(&d->phys_map, d->map.nodes);
356 static inline bool section_covers_addr(const MemoryRegionSection *section,
357 hwaddr addr)
359 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
360 * the section must cover the entire address space.
362 return int128_gethi(section->size) ||
363 range_covers_byte(section->offset_within_address_space,
364 int128_getlo(section->size), addr);
367 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
369 PhysPageEntry lp = d->phys_map, *p;
370 Node *nodes = d->map.nodes;
371 MemoryRegionSection *sections = d->map.sections;
372 hwaddr index = addr >> TARGET_PAGE_BITS;
373 int i;
375 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
376 if (lp.ptr == PHYS_MAP_NODE_NIL) {
377 return &sections[PHYS_SECTION_UNASSIGNED];
379 p = nodes[lp.ptr];
380 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
383 if (section_covers_addr(&sections[lp.ptr], addr)) {
384 return &sections[lp.ptr];
385 } else {
386 return &sections[PHYS_SECTION_UNASSIGNED];
390 /* Called from RCU critical section */
391 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
392 hwaddr addr,
393 bool resolve_subpage)
395 MemoryRegionSection *section = atomic_read(&d->mru_section);
396 subpage_t *subpage;
398 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
399 !section_covers_addr(section, addr)) {
400 section = phys_page_find(d, addr);
401 atomic_set(&d->mru_section, section);
403 if (resolve_subpage && section->mr->subpage) {
404 subpage = container_of(section->mr, subpage_t, iomem);
405 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
407 return section;
410 /* Called from RCU critical section */
411 static MemoryRegionSection *
412 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
413 hwaddr *plen, bool resolve_subpage)
415 MemoryRegionSection *section;
416 MemoryRegion *mr;
417 Int128 diff;
419 section = address_space_lookup_region(d, addr, resolve_subpage);
420 /* Compute offset within MemoryRegionSection */
421 addr -= section->offset_within_address_space;
423 /* Compute offset within MemoryRegion */
424 *xlat = addr + section->offset_within_region;
426 mr = section->mr;
428 /* MMIO registers can be expected to perform full-width accesses based only
429 * on their address, without considering adjacent registers that could
430 * decode to completely different MemoryRegions. When such registers
431 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
432 * regions overlap wildly. For this reason we cannot clamp the accesses
433 * here.
435 * If the length is small (as is the case for address_space_ldl/stl),
436 * everything works fine. If the incoming length is large, however,
437 * the caller really has to do the clamping through memory_access_size.
439 if (memory_region_is_ram(mr)) {
440 diff = int128_sub(section->size, int128_make64(addr));
441 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
443 return section;
447 * address_space_translate_iommu - translate an address through an IOMMU
448 * memory region and then through the target address space.
450 * @iommu_mr: the IOMMU memory region that we start the translation from
451 * @addr: the address to be translated through the MMU
452 * @xlat: the translated address offset within the destination memory region.
453 * It cannot be %NULL.
454 * @plen_out: valid read/write length of the translated address. It
455 * cannot be %NULL.
456 * @page_mask_out: page mask for the translated address. This
457 * should only be meaningful for IOMMU translated
458 * addresses, since there may be huge pages that this bit
459 * would tell. It can be %NULL if we don't care about it.
460 * @is_write: whether the translation operation is for write
461 * @is_mmio: whether this can be MMIO, set true if it can
462 * @target_as: the address space targeted by the IOMMU
463 * @attrs: transaction attributes
465 * This function is called from RCU critical section. It is the common
466 * part of flatview_do_translate and address_space_translate_cached.
468 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
469 hwaddr *xlat,
470 hwaddr *plen_out,
471 hwaddr *page_mask_out,
472 bool is_write,
473 bool is_mmio,
474 AddressSpace **target_as,
475 MemTxAttrs attrs)
477 MemoryRegionSection *section;
478 hwaddr page_mask = (hwaddr)-1;
480 do {
481 hwaddr addr = *xlat;
482 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
483 int iommu_idx = 0;
484 IOMMUTLBEntry iotlb;
486 if (imrc->attrs_to_index) {
487 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
490 iotlb = imrc->translate(iommu_mr, addr, is_write ?
491 IOMMU_WO : IOMMU_RO, iommu_idx);
493 if (!(iotlb.perm & (1 << is_write))) {
494 goto unassigned;
497 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
498 | (addr & iotlb.addr_mask));
499 page_mask &= iotlb.addr_mask;
500 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
501 *target_as = iotlb.target_as;
503 section = address_space_translate_internal(
504 address_space_to_dispatch(iotlb.target_as), addr, xlat,
505 plen_out, is_mmio);
507 iommu_mr = memory_region_get_iommu(section->mr);
508 } while (unlikely(iommu_mr));
510 if (page_mask_out) {
511 *page_mask_out = page_mask;
513 return *section;
515 unassigned:
516 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
520 * flatview_do_translate - translate an address in FlatView
522 * @fv: the flat view that we want to translate on
523 * @addr: the address to be translated in above address space
524 * @xlat: the translated address offset within memory region. It
525 * cannot be @NULL.
526 * @plen_out: valid read/write length of the translated address. It
527 * can be @NULL when we don't care about it.
528 * @page_mask_out: page mask for the translated address. This
529 * should only be meaningful for IOMMU translated
530 * addresses, since there may be huge pages that this bit
531 * would tell. It can be @NULL if we don't care about it.
532 * @is_write: whether the translation operation is for write
533 * @is_mmio: whether this can be MMIO, set true if it can
534 * @target_as: the address space targeted by the IOMMU
535 * @attrs: memory transaction attributes
537 * This function is called from RCU critical section
539 static MemoryRegionSection flatview_do_translate(FlatView *fv,
540 hwaddr addr,
541 hwaddr *xlat,
542 hwaddr *plen_out,
543 hwaddr *page_mask_out,
544 bool is_write,
545 bool is_mmio,
546 AddressSpace **target_as,
547 MemTxAttrs attrs)
549 MemoryRegionSection *section;
550 IOMMUMemoryRegion *iommu_mr;
551 hwaddr plen = (hwaddr)(-1);
553 if (!plen_out) {
554 plen_out = &plen;
557 section = address_space_translate_internal(
558 flatview_to_dispatch(fv), addr, xlat,
559 plen_out, is_mmio);
561 iommu_mr = memory_region_get_iommu(section->mr);
562 if (unlikely(iommu_mr)) {
563 return address_space_translate_iommu(iommu_mr, xlat,
564 plen_out, page_mask_out,
565 is_write, is_mmio,
566 target_as, attrs);
568 if (page_mask_out) {
569 /* Not behind an IOMMU, use default page size. */
570 *page_mask_out = ~TARGET_PAGE_MASK;
573 return *section;
576 /* Called from RCU critical section */
577 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
578 bool is_write, MemTxAttrs attrs)
580 MemoryRegionSection section;
581 hwaddr xlat, page_mask;
584 * This can never be MMIO, and we don't really care about plen,
585 * but page mask.
587 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
588 NULL, &page_mask, is_write, false, &as,
589 attrs);
591 /* Illegal translation */
592 if (section.mr == &io_mem_unassigned) {
593 goto iotlb_fail;
596 /* Convert memory region offset into address space offset */
597 xlat += section.offset_within_address_space -
598 section.offset_within_region;
600 return (IOMMUTLBEntry) {
601 .target_as = as,
602 .iova = addr & ~page_mask,
603 .translated_addr = xlat & ~page_mask,
604 .addr_mask = page_mask,
605 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
606 .perm = IOMMU_RW,
609 iotlb_fail:
610 return (IOMMUTLBEntry) {0};
613 /* Called from RCU critical section */
614 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
615 hwaddr *plen, bool is_write,
616 MemTxAttrs attrs)
618 MemoryRegion *mr;
619 MemoryRegionSection section;
620 AddressSpace *as = NULL;
622 /* This can be MMIO, so setup MMIO bit. */
623 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
624 is_write, true, &as, attrs);
625 mr = section.mr;
627 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
628 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
629 *plen = MIN(page, *plen);
632 return mr;
635 typedef struct TCGIOMMUNotifier {
636 IOMMUNotifier n;
637 MemoryRegion *mr;
638 CPUState *cpu;
639 int iommu_idx;
640 bool active;
641 } TCGIOMMUNotifier;
643 static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
645 TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
647 if (!notifier->active) {
648 return;
650 tlb_flush(notifier->cpu);
651 notifier->active = false;
652 /* We leave the notifier struct on the list to avoid reallocating it later.
653 * Generally the number of IOMMUs a CPU deals with will be small.
654 * In any case we can't unregister the iommu notifier from a notify
655 * callback.
659 static void tcg_register_iommu_notifier(CPUState *cpu,
660 IOMMUMemoryRegion *iommu_mr,
661 int iommu_idx)
663 /* Make sure this CPU has an IOMMU notifier registered for this
664 * IOMMU/IOMMU index combination, so that we can flush its TLB
665 * when the IOMMU tells us the mappings we've cached have changed.
667 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
668 TCGIOMMUNotifier *notifier;
669 int i;
671 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
672 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
673 if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
674 break;
677 if (i == cpu->iommu_notifiers->len) {
678 /* Not found, add a new entry at the end of the array */
679 cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
680 notifier = g_new0(TCGIOMMUNotifier, 1);
681 g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
683 notifier->mr = mr;
684 notifier->iommu_idx = iommu_idx;
685 notifier->cpu = cpu;
686 /* Rather than trying to register interest in the specific part
687 * of the iommu's address space that we've accessed and then
688 * expand it later as subsequent accesses touch more of it, we
689 * just register interest in the whole thing, on the assumption
690 * that iommu reconfiguration will be rare.
692 iommu_notifier_init(&notifier->n,
693 tcg_iommu_unmap_notify,
694 IOMMU_NOTIFIER_UNMAP,
696 HWADDR_MAX,
697 iommu_idx);
698 memory_region_register_iommu_notifier(notifier->mr, &notifier->n);
701 if (!notifier->active) {
702 notifier->active = true;
706 static void tcg_iommu_free_notifier_list(CPUState *cpu)
708 /* Destroy the CPU's notifier list */
709 int i;
710 TCGIOMMUNotifier *notifier;
712 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
713 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
714 memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
715 g_free(notifier);
717 g_array_free(cpu->iommu_notifiers, true);
720 /* Called from RCU critical section */
721 MemoryRegionSection *
722 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
723 hwaddr *xlat, hwaddr *plen,
724 MemTxAttrs attrs, int *prot)
726 MemoryRegionSection *section;
727 IOMMUMemoryRegion *iommu_mr;
728 IOMMUMemoryRegionClass *imrc;
729 IOMMUTLBEntry iotlb;
730 int iommu_idx;
731 AddressSpaceDispatch *d = atomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
733 for (;;) {
734 section = address_space_translate_internal(d, addr, &addr, plen, false);
736 iommu_mr = memory_region_get_iommu(section->mr);
737 if (!iommu_mr) {
738 break;
741 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
743 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
744 tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
745 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
746 * doesn't short-cut its translation table walk.
748 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
749 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
750 | (addr & iotlb.addr_mask));
751 /* Update the caller's prot bits to remove permissions the IOMMU
752 * is giving us a failure response for. If we get down to no
753 * permissions left at all we can give up now.
755 if (!(iotlb.perm & IOMMU_RO)) {
756 *prot &= ~(PAGE_READ | PAGE_EXEC);
758 if (!(iotlb.perm & IOMMU_WO)) {
759 *prot &= ~PAGE_WRITE;
762 if (!*prot) {
763 goto translate_fail;
766 d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
769 assert(!memory_region_is_iommu(section->mr));
770 *xlat = addr;
771 return section;
773 translate_fail:
774 return &d->map.sections[PHYS_SECTION_UNASSIGNED];
776 #endif
778 #if !defined(CONFIG_USER_ONLY)
780 static int cpu_common_post_load(void *opaque, int version_id)
782 CPUState *cpu = opaque;
784 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
785 version_id is increased. */
786 cpu->interrupt_request &= ~0x01;
787 tlb_flush(cpu);
789 /* loadvm has just updated the content of RAM, bypassing the
790 * usual mechanisms that ensure we flush TBs for writes to
791 * memory we've translated code from. So we must flush all TBs,
792 * which will now be stale.
794 tb_flush(cpu);
796 return 0;
799 static int cpu_common_pre_load(void *opaque)
801 CPUState *cpu = opaque;
803 cpu->exception_index = -1;
805 return 0;
808 static bool cpu_common_exception_index_needed(void *opaque)
810 CPUState *cpu = opaque;
812 return tcg_enabled() && cpu->exception_index != -1;
815 static const VMStateDescription vmstate_cpu_common_exception_index = {
816 .name = "cpu_common/exception_index",
817 .version_id = 1,
818 .minimum_version_id = 1,
819 .needed = cpu_common_exception_index_needed,
820 .fields = (VMStateField[]) {
821 VMSTATE_INT32(exception_index, CPUState),
822 VMSTATE_END_OF_LIST()
826 static bool cpu_common_crash_occurred_needed(void *opaque)
828 CPUState *cpu = opaque;
830 return cpu->crash_occurred;
833 static const VMStateDescription vmstate_cpu_common_crash_occurred = {
834 .name = "cpu_common/crash_occurred",
835 .version_id = 1,
836 .minimum_version_id = 1,
837 .needed = cpu_common_crash_occurred_needed,
838 .fields = (VMStateField[]) {
839 VMSTATE_BOOL(crash_occurred, CPUState),
840 VMSTATE_END_OF_LIST()
844 const VMStateDescription vmstate_cpu_common = {
845 .name = "cpu_common",
846 .version_id = 1,
847 .minimum_version_id = 1,
848 .pre_load = cpu_common_pre_load,
849 .post_load = cpu_common_post_load,
850 .fields = (VMStateField[]) {
851 VMSTATE_UINT32(halted, CPUState),
852 VMSTATE_UINT32(interrupt_request, CPUState),
853 VMSTATE_END_OF_LIST()
855 .subsections = (const VMStateDescription*[]) {
856 &vmstate_cpu_common_exception_index,
857 &vmstate_cpu_common_crash_occurred,
858 NULL
862 #endif
864 CPUState *qemu_get_cpu(int index)
866 CPUState *cpu;
868 CPU_FOREACH(cpu) {
869 if (cpu->cpu_index == index) {
870 return cpu;
874 return NULL;
877 #if !defined(CONFIG_USER_ONLY)
878 void cpu_address_space_init(CPUState *cpu, int asidx,
879 const char *prefix, MemoryRegion *mr)
881 CPUAddressSpace *newas;
882 AddressSpace *as = g_new0(AddressSpace, 1);
883 char *as_name;
885 assert(mr);
886 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
887 address_space_init(as, mr, as_name);
888 g_free(as_name);
890 /* Target code should have set num_ases before calling us */
891 assert(asidx < cpu->num_ases);
893 if (asidx == 0) {
894 /* address space 0 gets the convenience alias */
895 cpu->as = as;
898 /* KVM cannot currently support multiple address spaces. */
899 assert(asidx == 0 || !kvm_enabled());
901 if (!cpu->cpu_ases) {
902 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
905 newas = &cpu->cpu_ases[asidx];
906 newas->cpu = cpu;
907 newas->as = as;
908 if (tcg_enabled()) {
909 newas->tcg_as_listener.commit = tcg_commit;
910 memory_listener_register(&newas->tcg_as_listener, as);
914 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
916 /* Return the AddressSpace corresponding to the specified index */
917 return cpu->cpu_ases[asidx].as;
919 #endif
921 void cpu_exec_unrealizefn(CPUState *cpu)
923 CPUClass *cc = CPU_GET_CLASS(cpu);
925 cpu_list_remove(cpu);
927 if (cc->vmsd != NULL) {
928 vmstate_unregister(NULL, cc->vmsd, cpu);
930 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
931 vmstate_unregister(NULL, &vmstate_cpu_common, cpu);
933 #ifndef CONFIG_USER_ONLY
934 tcg_iommu_free_notifier_list(cpu);
935 #endif
938 Property cpu_common_props[] = {
939 #ifndef CONFIG_USER_ONLY
940 /* Create a memory property for softmmu CPU object,
941 * so users can wire up its memory. (This can't go in qom/cpu.c
942 * because that file is compiled only once for both user-mode
943 * and system builds.) The default if no link is set up is to use
944 * the system address space.
946 DEFINE_PROP_LINK("memory", CPUState, memory, TYPE_MEMORY_REGION,
947 MemoryRegion *),
948 #endif
949 DEFINE_PROP_END_OF_LIST(),
952 void cpu_exec_initfn(CPUState *cpu)
954 #ifdef TARGET_WORDS_BIGENDIAN
955 cpu->bigendian = true;
956 #else
957 cpu->bigendian = false;
958 #endif
959 cpu->as = NULL;
960 cpu->num_ases = 0;
962 #ifndef CONFIG_USER_ONLY
963 cpu->thread_id = qemu_get_thread_id();
964 cpu->memory = system_memory;
965 object_ref(OBJECT(cpu->memory));
966 #endif
969 void cpu_exec_realizefn(CPUState *cpu, Error **errp)
971 CPUClass *cc = CPU_GET_CLASS(cpu);
972 static bool tcg_target_initialized;
974 cpu_list_add(cpu);
976 if (tcg_enabled() && !tcg_target_initialized) {
977 tcg_target_initialized = true;
978 cc->tcg_initialize();
980 tlb_init(cpu);
982 #ifndef CONFIG_USER_ONLY
983 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
984 vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
986 if (cc->vmsd != NULL) {
987 vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);
990 cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
991 #endif
994 const char *parse_cpu_option(const char *cpu_option)
996 ObjectClass *oc;
997 CPUClass *cc;
998 gchar **model_pieces;
999 const char *cpu_type;
1001 model_pieces = g_strsplit(cpu_option, ",", 2);
1002 if (!model_pieces[0]) {
1003 error_report("-cpu option cannot be empty");
1004 exit(1);
1007 oc = cpu_class_by_name(CPU_RESOLVING_TYPE, model_pieces[0]);
1008 if (oc == NULL) {
1009 error_report("unable to find CPU model '%s'", model_pieces[0]);
1010 g_strfreev(model_pieces);
1011 exit(EXIT_FAILURE);
1014 cpu_type = object_class_get_name(oc);
1015 cc = CPU_CLASS(oc);
1016 cc->parse_features(cpu_type, model_pieces[1], &error_fatal);
1017 g_strfreev(model_pieces);
1018 return cpu_type;
1021 #if defined(CONFIG_USER_ONLY)
1022 void tb_invalidate_phys_addr(target_ulong addr)
1024 mmap_lock();
1025 tb_invalidate_phys_page_range(addr, addr + 1, 0);
1026 mmap_unlock();
1029 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
1031 tb_invalidate_phys_addr(pc);
1033 #else
1034 void tb_invalidate_phys_addr(AddressSpace *as, hwaddr addr, MemTxAttrs attrs)
1036 ram_addr_t ram_addr;
1037 MemoryRegion *mr;
1038 hwaddr l = 1;
1040 if (!tcg_enabled()) {
1041 return;
1044 rcu_read_lock();
1045 mr = address_space_translate(as, addr, &addr, &l, false, attrs);
1046 if (!(memory_region_is_ram(mr)
1047 || memory_region_is_romd(mr))) {
1048 rcu_read_unlock();
1049 return;
1051 ram_addr = memory_region_get_ram_addr(mr) + addr;
1052 tb_invalidate_phys_page_range(ram_addr, ram_addr + 1, 0);
1053 rcu_read_unlock();
1056 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
1058 MemTxAttrs attrs;
1059 hwaddr phys = cpu_get_phys_page_attrs_debug(cpu, pc, &attrs);
1060 int asidx = cpu_asidx_from_attrs(cpu, attrs);
1061 if (phys != -1) {
1062 /* Locks grabbed by tb_invalidate_phys_addr */
1063 tb_invalidate_phys_addr(cpu->cpu_ases[asidx].as,
1064 phys | (pc & ~TARGET_PAGE_MASK), attrs);
1067 #endif
1069 #if defined(CONFIG_USER_ONLY)
1070 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
1075 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
1076 int flags)
1078 return -ENOSYS;
1081 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
1085 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
1086 int flags, CPUWatchpoint **watchpoint)
1088 return -ENOSYS;
1090 #else
1091 /* Add a watchpoint. */
1092 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
1093 int flags, CPUWatchpoint **watchpoint)
1095 CPUWatchpoint *wp;
1097 /* forbid ranges which are empty or run off the end of the address space */
1098 if (len == 0 || (addr + len - 1) < addr) {
1099 error_report("tried to set invalid watchpoint at %"
1100 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
1101 return -EINVAL;
1103 wp = g_malloc(sizeof(*wp));
1105 wp->vaddr = addr;
1106 wp->len = len;
1107 wp->flags = flags;
1109 /* keep all GDB-injected watchpoints in front */
1110 if (flags & BP_GDB) {
1111 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
1112 } else {
1113 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
1116 tlb_flush_page(cpu, addr);
1118 if (watchpoint)
1119 *watchpoint = wp;
1120 return 0;
1123 /* Remove a specific watchpoint. */
1124 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
1125 int flags)
1127 CPUWatchpoint *wp;
1129 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1130 if (addr == wp->vaddr && len == wp->len
1131 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
1132 cpu_watchpoint_remove_by_ref(cpu, wp);
1133 return 0;
1136 return -ENOENT;
1139 /* Remove a specific watchpoint by reference. */
1140 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
1142 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
1144 tlb_flush_page(cpu, watchpoint->vaddr);
1146 g_free(watchpoint);
1149 /* Remove all matching watchpoints. */
1150 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
1152 CPUWatchpoint *wp, *next;
1154 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
1155 if (wp->flags & mask) {
1156 cpu_watchpoint_remove_by_ref(cpu, wp);
1161 /* Return true if this watchpoint address matches the specified
1162 * access (ie the address range covered by the watchpoint overlaps
1163 * partially or completely with the address range covered by the
1164 * access).
1166 static inline bool cpu_watchpoint_address_matches(CPUWatchpoint *wp,
1167 vaddr addr,
1168 vaddr len)
1170 /* We know the lengths are non-zero, but a little caution is
1171 * required to avoid errors in the case where the range ends
1172 * exactly at the top of the address space and so addr + len
1173 * wraps round to zero.
1175 vaddr wpend = wp->vaddr + wp->len - 1;
1176 vaddr addrend = addr + len - 1;
1178 return !(addr > wpend || wp->vaddr > addrend);
1181 #endif
1183 /* Add a breakpoint. */
1184 int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
1185 CPUBreakpoint **breakpoint)
1187 CPUBreakpoint *bp;
1189 bp = g_malloc(sizeof(*bp));
1191 bp->pc = pc;
1192 bp->flags = flags;
1194 /* keep all GDB-injected breakpoints in front */
1195 if (flags & BP_GDB) {
1196 QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
1197 } else {
1198 QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
1201 breakpoint_invalidate(cpu, pc);
1203 if (breakpoint) {
1204 *breakpoint = bp;
1206 return 0;
1209 /* Remove a specific breakpoint. */
1210 int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
1212 CPUBreakpoint *bp;
1214 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
1215 if (bp->pc == pc && bp->flags == flags) {
1216 cpu_breakpoint_remove_by_ref(cpu, bp);
1217 return 0;
1220 return -ENOENT;
1223 /* Remove a specific breakpoint by reference. */
1224 void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
1226 QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);
1228 breakpoint_invalidate(cpu, breakpoint->pc);
1230 g_free(breakpoint);
1233 /* Remove all matching breakpoints. */
1234 void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
1236 CPUBreakpoint *bp, *next;
1238 QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
1239 if (bp->flags & mask) {
1240 cpu_breakpoint_remove_by_ref(cpu, bp);
1245 /* enable or disable single step mode. EXCP_DEBUG is returned by the
1246 CPU loop after each instruction */
1247 void cpu_single_step(CPUState *cpu, int enabled)
1249 if (cpu->singlestep_enabled != enabled) {
1250 cpu->singlestep_enabled = enabled;
1251 if (kvm_enabled()) {
1252 kvm_update_guest_debug(cpu, 0);
1253 } else {
1254 /* must flush all the translated code to avoid inconsistencies */
1255 /* XXX: only flush what is necessary */
1256 tb_flush(cpu);
1261 void QEMU_NORETURN cpu_abort(CPUState *cpu, const char *fmt, ...)
1263 va_list ap;
1264 va_list ap2;
1266 va_start(ap, fmt);
1267 va_copy(ap2, ap);
1268 fprintf(stderr, "qemu: fatal: ");
1269 vfprintf(stderr, fmt, ap);
1270 fprintf(stderr, "\n");
1271 cpu_dump_state(cpu, stderr, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1272 if (qemu_log_separate()) {
1273 qemu_log_lock();
1274 qemu_log("qemu: fatal: ");
1275 qemu_log_vprintf(fmt, ap2);
1276 qemu_log("\n");
1277 log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
1278 qemu_log_flush();
1279 qemu_log_unlock();
1280 qemu_log_close();
1282 va_end(ap2);
1283 va_end(ap);
1284 replay_finish();
1285 #if defined(CONFIG_USER_ONLY)
1287 struct sigaction act;
1288 sigfillset(&act.sa_mask);
1289 act.sa_handler = SIG_DFL;
1290 act.sa_flags = 0;
1291 sigaction(SIGABRT, &act, NULL);
1293 #endif
1294 abort();
1297 #if !defined(CONFIG_USER_ONLY)
1298 /* Called from RCU critical section */
1299 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
1301 RAMBlock *block;
1303 block = atomic_rcu_read(&ram_list.mru_block);
1304 if (block && addr - block->offset < block->max_length) {
1305 return block;
1307 RAMBLOCK_FOREACH(block) {
1308 if (addr - block->offset < block->max_length) {
1309 goto found;
1313 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1314 abort();
1316 found:
1317 /* It is safe to write mru_block outside the iothread lock. This
1318 * is what happens:
1320 * mru_block = xxx
1321 * rcu_read_unlock()
1322 * xxx removed from list
1323 * rcu_read_lock()
1324 * read mru_block
1325 * mru_block = NULL;
1326 * call_rcu(reclaim_ramblock, xxx);
1327 * rcu_read_unlock()
1329 * atomic_rcu_set is not needed here. The block was already published
1330 * when it was placed into the list. Here we're just making an extra
1331 * copy of the pointer.
1333 ram_list.mru_block = block;
1334 return block;
1337 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1339 CPUState *cpu;
1340 ram_addr_t start1;
1341 RAMBlock *block;
1342 ram_addr_t end;
1344 assert(tcg_enabled());
1345 end = TARGET_PAGE_ALIGN(start + length);
1346 start &= TARGET_PAGE_MASK;
1348 rcu_read_lock();
1349 block = qemu_get_ram_block(start);
1350 assert(block == qemu_get_ram_block(end - 1));
1351 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1352 CPU_FOREACH(cpu) {
1353 tlb_reset_dirty(cpu, start1, length);
1355 rcu_read_unlock();
1358 /* Note: start and end must be within the same ram block. */
1359 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1360 ram_addr_t length,
1361 unsigned client)
1363 DirtyMemoryBlocks *blocks;
1364 unsigned long end, page;
1365 bool dirty = false;
1366 RAMBlock *ramblock;
1367 uint64_t mr_offset, mr_size;
1369 if (length == 0) {
1370 return false;
1373 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1374 page = start >> TARGET_PAGE_BITS;
1376 rcu_read_lock();
1378 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1379 ramblock = qemu_get_ram_block(start);
1380 /* Range sanity check on the ramblock */
1381 assert(start >= ramblock->offset &&
1382 start + length <= ramblock->offset + ramblock->used_length);
1384 while (page < end) {
1385 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1386 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1387 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1389 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1390 offset, num);
1391 page += num;
1394 mr_offset = (ram_addr_t)(page << TARGET_PAGE_BITS) - ramblock->offset;
1395 mr_size = (end - page) << TARGET_PAGE_BITS;
1396 memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
1398 rcu_read_unlock();
1400 if (dirty && tcg_enabled()) {
1401 tlb_reset_dirty_range_all(start, length);
1404 return dirty;
1407 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1408 (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
1410 DirtyMemoryBlocks *blocks;
1411 ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
1412 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1413 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1414 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1415 DirtyBitmapSnapshot *snap;
1416 unsigned long page, end, dest;
1418 snap = g_malloc0(sizeof(*snap) +
1419 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1420 snap->start = first;
1421 snap->end = last;
1423 page = first >> TARGET_PAGE_BITS;
1424 end = last >> TARGET_PAGE_BITS;
1425 dest = 0;
1427 rcu_read_lock();
1429 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1431 while (page < end) {
1432 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1433 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1434 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1436 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1437 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1438 offset >>= BITS_PER_LEVEL;
1440 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1441 blocks->blocks[idx] + offset,
1442 num);
1443 page += num;
1444 dest += num >> BITS_PER_LEVEL;
1447 rcu_read_unlock();
1449 if (tcg_enabled()) {
1450 tlb_reset_dirty_range_all(start, length);
1453 memory_region_clear_dirty_bitmap(mr, offset, length);
1455 return snap;
1458 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1459 ram_addr_t start,
1460 ram_addr_t length)
1462 unsigned long page, end;
1464 assert(start >= snap->start);
1465 assert(start + length <= snap->end);
1467 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1468 page = (start - snap->start) >> TARGET_PAGE_BITS;
1470 while (page < end) {
1471 if (test_bit(page, snap->dirty)) {
1472 return true;
1474 page++;
1476 return false;
1479 /* Called from RCU critical section */
1480 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1481 MemoryRegionSection *section,
1482 target_ulong vaddr,
1483 hwaddr paddr, hwaddr xlat,
1484 int prot,
1485 target_ulong *address)
1487 hwaddr iotlb;
1488 CPUWatchpoint *wp;
1490 if (memory_region_is_ram(section->mr)) {
1491 /* Normal RAM. */
1492 iotlb = memory_region_get_ram_addr(section->mr) + xlat;
1493 if (!section->readonly) {
1494 iotlb |= PHYS_SECTION_NOTDIRTY;
1495 } else {
1496 iotlb |= PHYS_SECTION_ROM;
1498 } else {
1499 AddressSpaceDispatch *d;
1501 d = flatview_to_dispatch(section->fv);
1502 iotlb = section - d->map.sections;
1503 iotlb += xlat;
1506 /* Make accesses to pages with watchpoints go via the
1507 watchpoint trap routines. */
1508 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
1509 if (cpu_watchpoint_address_matches(wp, vaddr, TARGET_PAGE_SIZE)) {
1510 /* Avoid trapping reads of pages with a write breakpoint. */
1511 if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
1512 iotlb = PHYS_SECTION_WATCH + paddr;
1513 *address |= TLB_MMIO;
1514 break;
1519 return iotlb;
1521 #endif /* defined(CONFIG_USER_ONLY) */
1523 #if !defined(CONFIG_USER_ONLY)
1525 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
1526 uint16_t section);
1527 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1529 static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
1530 qemu_anon_ram_alloc;
1533 * Set a custom physical guest memory alloator.
1534 * Accelerators with unusual needs may need this. Hopefully, we can
1535 * get rid of it eventually.
1537 void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
1539 phys_mem_alloc = alloc;
1542 static uint16_t phys_section_add(PhysPageMap *map,
1543 MemoryRegionSection *section)
1545 /* The physical section number is ORed with a page-aligned
1546 * pointer to produce the iotlb entries. Thus it should
1547 * never overflow into the page-aligned value.
1549 assert(map->sections_nb < TARGET_PAGE_SIZE);
1551 if (map->sections_nb == map->sections_nb_alloc) {
1552 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1553 map->sections = g_renew(MemoryRegionSection, map->sections,
1554 map->sections_nb_alloc);
1556 map->sections[map->sections_nb] = *section;
1557 memory_region_ref(section->mr);
1558 return map->sections_nb++;
1561 static void phys_section_destroy(MemoryRegion *mr)
1563 bool have_sub_page = mr->subpage;
1565 memory_region_unref(mr);
1567 if (have_sub_page) {
1568 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1569 object_unref(OBJECT(&subpage->iomem));
1570 g_free(subpage);
1574 static void phys_sections_free(PhysPageMap *map)
1576 while (map->sections_nb > 0) {
1577 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1578 phys_section_destroy(section->mr);
1580 g_free(map->sections);
1581 g_free(map->nodes);
1584 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1586 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1587 subpage_t *subpage;
1588 hwaddr base = section->offset_within_address_space
1589 & TARGET_PAGE_MASK;
1590 MemoryRegionSection *existing = phys_page_find(d, base);
1591 MemoryRegionSection subsection = {
1592 .offset_within_address_space = base,
1593 .size = int128_make64(TARGET_PAGE_SIZE),
1595 hwaddr start, end;
1597 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1599 if (!(existing->mr->subpage)) {
1600 subpage = subpage_init(fv, base);
1601 subsection.fv = fv;
1602 subsection.mr = &subpage->iomem;
1603 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1604 phys_section_add(&d->map, &subsection));
1605 } else {
1606 subpage = container_of(existing->mr, subpage_t, iomem);
1608 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1609 end = start + int128_get64(section->size) - 1;
1610 subpage_register(subpage, start, end,
1611 phys_section_add(&d->map, section));
1615 static void register_multipage(FlatView *fv,
1616 MemoryRegionSection *section)
1618 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1619 hwaddr start_addr = section->offset_within_address_space;
1620 uint16_t section_index = phys_section_add(&d->map, section);
1621 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1622 TARGET_PAGE_BITS));
1624 assert(num_pages);
1625 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1629 * The range in *section* may look like this:
1631 * |s|PPPPPPP|s|
1633 * where s stands for subpage and P for page.
1635 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1637 MemoryRegionSection remain = *section;
1638 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1640 /* register first subpage */
1641 if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1642 uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1643 - remain.offset_within_address_space;
1645 MemoryRegionSection now = remain;
1646 now.size = int128_min(int128_make64(left), now.size);
1647 register_subpage(fv, &now);
1648 if (int128_eq(remain.size, now.size)) {
1649 return;
1651 remain.size = int128_sub(remain.size, now.size);
1652 remain.offset_within_address_space += int128_get64(now.size);
1653 remain.offset_within_region += int128_get64(now.size);
1656 /* register whole pages */
1657 if (int128_ge(remain.size, page_size)) {
1658 MemoryRegionSection now = remain;
1659 now.size = int128_and(now.size, int128_neg(page_size));
1660 register_multipage(fv, &now);
1661 if (int128_eq(remain.size, now.size)) {
1662 return;
1664 remain.size = int128_sub(remain.size, now.size);
1665 remain.offset_within_address_space += int128_get64(now.size);
1666 remain.offset_within_region += int128_get64(now.size);
1669 /* register last subpage */
1670 register_subpage(fv, &remain);
1673 void qemu_flush_coalesced_mmio_buffer(void)
1675 if (kvm_enabled())
1676 kvm_flush_coalesced_mmio_buffer();
1679 void qemu_mutex_lock_ramlist(void)
1681 qemu_mutex_lock(&ram_list.mutex);
1684 void qemu_mutex_unlock_ramlist(void)
1686 qemu_mutex_unlock(&ram_list.mutex);
1689 void ram_block_dump(Monitor *mon)
1691 RAMBlock *block;
1692 char *psize;
1694 rcu_read_lock();
1695 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1696 "Block Name", "PSize", "Offset", "Used", "Total");
1697 RAMBLOCK_FOREACH(block) {
1698 psize = size_to_str(block->page_size);
1699 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1700 " 0x%016" PRIx64 "\n", block->idstr, psize,
1701 (uint64_t)block->offset,
1702 (uint64_t)block->used_length,
1703 (uint64_t)block->max_length);
1704 g_free(psize);
1706 rcu_read_unlock();
1709 #ifdef __linux__
1711 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1712 * may or may not name the same files / on the same filesystem now as
1713 * when we actually open and map them. Iterate over the file
1714 * descriptors instead, and use qemu_fd_getpagesize().
1716 static int find_min_backend_pagesize(Object *obj, void *opaque)
1718 long *hpsize_min = opaque;
1720 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1721 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1722 long hpsize = host_memory_backend_pagesize(backend);
1724 if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
1725 *hpsize_min = hpsize;
1729 return 0;
1732 static int find_max_backend_pagesize(Object *obj, void *opaque)
1734 long *hpsize_max = opaque;
1736 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1737 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1738 long hpsize = host_memory_backend_pagesize(backend);
1740 if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1741 *hpsize_max = hpsize;
1745 return 0;
1749 * TODO: We assume right now that all mapped host memory backends are
1750 * used as RAM, however some might be used for different purposes.
1752 long qemu_minrampagesize(void)
1754 long hpsize = LONG_MAX;
1755 long mainrampagesize;
1756 Object *memdev_root;
1758 mainrampagesize = qemu_mempath_getpagesize(mem_path);
1760 /* it's possible we have memory-backend objects with
1761 * hugepage-backed RAM. these may get mapped into system
1762 * address space via -numa parameters or memory hotplug
1763 * hooks. we want to take these into account, but we
1764 * also want to make sure these supported hugepage
1765 * sizes are applicable across the entire range of memory
1766 * we may boot from, so we take the min across all
1767 * backends, and assume normal pages in cases where a
1768 * backend isn't backed by hugepages.
1770 memdev_root = object_resolve_path("/objects", NULL);
1771 if (memdev_root) {
1772 object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
1774 if (hpsize == LONG_MAX) {
1775 /* No additional memory regions found ==> Report main RAM page size */
1776 return mainrampagesize;
1779 /* If NUMA is disabled or the NUMA nodes are not backed with a
1780 * memory-backend, then there is at least one node using "normal" RAM,
1781 * so if its page size is smaller we have got to report that size instead.
1783 if (hpsize > mainrampagesize &&
1784 (nb_numa_nodes == 0 || numa_info[0].node_memdev == NULL)) {
1785 static bool warned;
1786 if (!warned) {
1787 error_report("Huge page support disabled (n/a for main memory).");
1788 warned = true;
1790 return mainrampagesize;
1793 return hpsize;
1796 long qemu_maxrampagesize(void)
1798 long pagesize = qemu_mempath_getpagesize(mem_path);
1799 Object *memdev_root = object_resolve_path("/objects", NULL);
1801 if (memdev_root) {
1802 object_child_foreach(memdev_root, find_max_backend_pagesize,
1803 &pagesize);
1805 return pagesize;
1807 #else
1808 long qemu_minrampagesize(void)
1810 return getpagesize();
1812 long qemu_maxrampagesize(void)
1814 return getpagesize();
1816 #endif
1818 #ifdef CONFIG_POSIX
1819 static int64_t get_file_size(int fd)
1821 int64_t size = lseek(fd, 0, SEEK_END);
1822 if (size < 0) {
1823 return -errno;
1825 return size;
1828 static int file_ram_open(const char *path,
1829 const char *region_name,
1830 bool *created,
1831 Error **errp)
1833 char *filename;
1834 char *sanitized_name;
1835 char *c;
1836 int fd = -1;
1838 *created = false;
1839 for (;;) {
1840 fd = open(path, O_RDWR);
1841 if (fd >= 0) {
1842 /* @path names an existing file, use it */
1843 break;
1845 if (errno == ENOENT) {
1846 /* @path names a file that doesn't exist, create it */
1847 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1848 if (fd >= 0) {
1849 *created = true;
1850 break;
1852 } else if (errno == EISDIR) {
1853 /* @path names a directory, create a file there */
1854 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1855 sanitized_name = g_strdup(region_name);
1856 for (c = sanitized_name; *c != '\0'; c++) {
1857 if (*c == '/') {
1858 *c = '_';
1862 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1863 sanitized_name);
1864 g_free(sanitized_name);
1866 fd = mkstemp(filename);
1867 if (fd >= 0) {
1868 unlink(filename);
1869 g_free(filename);
1870 break;
1872 g_free(filename);
1874 if (errno != EEXIST && errno != EINTR) {
1875 error_setg_errno(errp, errno,
1876 "can't open backing store %s for guest RAM",
1877 path);
1878 return -1;
1881 * Try again on EINTR and EEXIST. The latter happens when
1882 * something else creates the file between our two open().
1886 return fd;
1889 static void *file_ram_alloc(RAMBlock *block,
1890 ram_addr_t memory,
1891 int fd,
1892 bool truncate,
1893 Error **errp)
1895 MachineState *ms = MACHINE(qdev_get_machine());
1896 void *area;
1898 block->page_size = qemu_fd_getpagesize(fd);
1899 if (block->mr->align % block->page_size) {
1900 error_setg(errp, "alignment 0x%" PRIx64
1901 " must be multiples of page size 0x%zx",
1902 block->mr->align, block->page_size);
1903 return NULL;
1904 } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1905 error_setg(errp, "alignment 0x%" PRIx64
1906 " must be a power of two", block->mr->align);
1907 return NULL;
1909 block->mr->align = MAX(block->page_size, block->mr->align);
1910 #if defined(__s390x__)
1911 if (kvm_enabled()) {
1912 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1914 #endif
1916 if (memory < block->page_size) {
1917 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1918 "or larger than page size 0x%zx",
1919 memory, block->page_size);
1920 return NULL;
1923 memory = ROUND_UP(memory, block->page_size);
1926 * ftruncate is not supported by hugetlbfs in older
1927 * hosts, so don't bother bailing out on errors.
1928 * If anything goes wrong with it under other filesystems,
1929 * mmap will fail.
1931 * Do not truncate the non-empty backend file to avoid corrupting
1932 * the existing data in the file. Disabling shrinking is not
1933 * enough. For example, the current vNVDIMM implementation stores
1934 * the guest NVDIMM labels at the end of the backend file. If the
1935 * backend file is later extended, QEMU will not be able to find
1936 * those labels. Therefore, extending the non-empty backend file
1937 * is disabled as well.
1939 if (truncate && ftruncate(fd, memory)) {
1940 perror("ftruncate");
1943 area = qemu_ram_mmap(fd, memory, block->mr->align,
1944 block->flags & RAM_SHARED, block->flags & RAM_PMEM);
1945 if (area == MAP_FAILED) {
1946 error_setg_errno(errp, errno,
1947 "unable to map backing store for guest RAM");
1948 return NULL;
1951 if (mem_prealloc) {
1952 os_mem_prealloc(fd, area, memory, ms->smp.cpus, errp);
1953 if (errp && *errp) {
1954 qemu_ram_munmap(fd, area, memory);
1955 return NULL;
1959 block->fd = fd;
1960 return area;
1962 #endif
1964 /* Allocate space within the ram_addr_t space that governs the
1965 * dirty bitmaps.
1966 * Called with the ramlist lock held.
1968 static ram_addr_t find_ram_offset(ram_addr_t size)
1970 RAMBlock *block, *next_block;
1971 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1973 assert(size != 0); /* it would hand out same offset multiple times */
1975 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1976 return 0;
1979 RAMBLOCK_FOREACH(block) {
1980 ram_addr_t candidate, next = RAM_ADDR_MAX;
1982 /* Align blocks to start on a 'long' in the bitmap
1983 * which makes the bitmap sync'ing take the fast path.
1985 candidate = block->offset + block->max_length;
1986 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1988 /* Search for the closest following block
1989 * and find the gap.
1991 RAMBLOCK_FOREACH(next_block) {
1992 if (next_block->offset >= candidate) {
1993 next = MIN(next, next_block->offset);
1997 /* If it fits remember our place and remember the size
1998 * of gap, but keep going so that we might find a smaller
1999 * gap to fill so avoiding fragmentation.
2001 if (next - candidate >= size && next - candidate < mingap) {
2002 offset = candidate;
2003 mingap = next - candidate;
2006 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
2009 if (offset == RAM_ADDR_MAX) {
2010 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
2011 (uint64_t)size);
2012 abort();
2015 trace_find_ram_offset(size, offset);
2017 return offset;
2020 static unsigned long last_ram_page(void)
2022 RAMBlock *block;
2023 ram_addr_t last = 0;
2025 rcu_read_lock();
2026 RAMBLOCK_FOREACH(block) {
2027 last = MAX(last, block->offset + block->max_length);
2029 rcu_read_unlock();
2030 return last >> TARGET_PAGE_BITS;
2033 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
2035 int ret;
2037 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
2038 if (!machine_dump_guest_core(current_machine)) {
2039 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
2040 if (ret) {
2041 perror("qemu_madvise");
2042 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
2043 "but dump_guest_core=off specified\n");
2048 const char *qemu_ram_get_idstr(RAMBlock *rb)
2050 return rb->idstr;
2053 void *qemu_ram_get_host_addr(RAMBlock *rb)
2055 return rb->host;
2058 ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
2060 return rb->offset;
2063 ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
2065 return rb->used_length;
2068 bool qemu_ram_is_shared(RAMBlock *rb)
2070 return rb->flags & RAM_SHARED;
2073 /* Note: Only set at the start of postcopy */
2074 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
2076 return rb->flags & RAM_UF_ZEROPAGE;
2079 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
2081 rb->flags |= RAM_UF_ZEROPAGE;
2084 bool qemu_ram_is_migratable(RAMBlock *rb)
2086 return rb->flags & RAM_MIGRATABLE;
2089 void qemu_ram_set_migratable(RAMBlock *rb)
2091 rb->flags |= RAM_MIGRATABLE;
2094 void qemu_ram_unset_migratable(RAMBlock *rb)
2096 rb->flags &= ~RAM_MIGRATABLE;
2099 /* Called with iothread lock held. */
2100 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
2102 RAMBlock *block;
2104 assert(new_block);
2105 assert(!new_block->idstr[0]);
2107 if (dev) {
2108 char *id = qdev_get_dev_path(dev);
2109 if (id) {
2110 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
2111 g_free(id);
2114 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
2116 rcu_read_lock();
2117 RAMBLOCK_FOREACH(block) {
2118 if (block != new_block &&
2119 !strcmp(block->idstr, new_block->idstr)) {
2120 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
2121 new_block->idstr);
2122 abort();
2125 rcu_read_unlock();
2128 /* Called with iothread lock held. */
2129 void qemu_ram_unset_idstr(RAMBlock *block)
2131 /* FIXME: arch_init.c assumes that this is not called throughout
2132 * migration. Ignore the problem since hot-unplug during migration
2133 * does not work anyway.
2135 if (block) {
2136 memset(block->idstr, 0, sizeof(block->idstr));
2140 size_t qemu_ram_pagesize(RAMBlock *rb)
2142 return rb->page_size;
2145 /* Returns the largest size of page in use */
2146 size_t qemu_ram_pagesize_largest(void)
2148 RAMBlock *block;
2149 size_t largest = 0;
2151 RAMBLOCK_FOREACH(block) {
2152 largest = MAX(largest, qemu_ram_pagesize(block));
2155 return largest;
2158 static int memory_try_enable_merging(void *addr, size_t len)
2160 if (!machine_mem_merge(current_machine)) {
2161 /* disabled by the user */
2162 return 0;
2165 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
2168 /* Only legal before guest might have detected the memory size: e.g. on
2169 * incoming migration, or right after reset.
2171 * As memory core doesn't know how is memory accessed, it is up to
2172 * resize callback to update device state and/or add assertions to detect
2173 * misuse, if necessary.
2175 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
2177 assert(block);
2179 newsize = HOST_PAGE_ALIGN(newsize);
2181 if (block->used_length == newsize) {
2182 return 0;
2185 if (!(block->flags & RAM_RESIZEABLE)) {
2186 error_setg_errno(errp, EINVAL,
2187 "Length mismatch: %s: 0x" RAM_ADDR_FMT
2188 " in != 0x" RAM_ADDR_FMT, block->idstr,
2189 newsize, block->used_length);
2190 return -EINVAL;
2193 if (block->max_length < newsize) {
2194 error_setg_errno(errp, EINVAL,
2195 "Length too large: %s: 0x" RAM_ADDR_FMT
2196 " > 0x" RAM_ADDR_FMT, block->idstr,
2197 newsize, block->max_length);
2198 return -EINVAL;
2201 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
2202 block->used_length = newsize;
2203 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
2204 DIRTY_CLIENTS_ALL);
2205 memory_region_set_size(block->mr, newsize);
2206 if (block->resized) {
2207 block->resized(block->idstr, newsize, block->host);
2209 return 0;
2212 /* Called with ram_list.mutex held */
2213 static void dirty_memory_extend(ram_addr_t old_ram_size,
2214 ram_addr_t new_ram_size)
2216 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
2217 DIRTY_MEMORY_BLOCK_SIZE);
2218 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
2219 DIRTY_MEMORY_BLOCK_SIZE);
2220 int i;
2222 /* Only need to extend if block count increased */
2223 if (new_num_blocks <= old_num_blocks) {
2224 return;
2227 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
2228 DirtyMemoryBlocks *old_blocks;
2229 DirtyMemoryBlocks *new_blocks;
2230 int j;
2232 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
2233 new_blocks = g_malloc(sizeof(*new_blocks) +
2234 sizeof(new_blocks->blocks[0]) * new_num_blocks);
2236 if (old_num_blocks) {
2237 memcpy(new_blocks->blocks, old_blocks->blocks,
2238 old_num_blocks * sizeof(old_blocks->blocks[0]));
2241 for (j = old_num_blocks; j < new_num_blocks; j++) {
2242 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
2245 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
2247 if (old_blocks) {
2248 g_free_rcu(old_blocks, rcu);
2253 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
2255 RAMBlock *block;
2256 RAMBlock *last_block = NULL;
2257 ram_addr_t old_ram_size, new_ram_size;
2258 Error *err = NULL;
2260 old_ram_size = last_ram_page();
2262 qemu_mutex_lock_ramlist();
2263 new_block->offset = find_ram_offset(new_block->max_length);
2265 if (!new_block->host) {
2266 if (xen_enabled()) {
2267 xen_ram_alloc(new_block->offset, new_block->max_length,
2268 new_block->mr, &err);
2269 if (err) {
2270 error_propagate(errp, err);
2271 qemu_mutex_unlock_ramlist();
2272 return;
2274 } else {
2275 new_block->host = phys_mem_alloc(new_block->max_length,
2276 &new_block->mr->align, shared);
2277 if (!new_block->host) {
2278 error_setg_errno(errp, errno,
2279 "cannot set up guest memory '%s'",
2280 memory_region_name(new_block->mr));
2281 qemu_mutex_unlock_ramlist();
2282 return;
2284 memory_try_enable_merging(new_block->host, new_block->max_length);
2288 new_ram_size = MAX(old_ram_size,
2289 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
2290 if (new_ram_size > old_ram_size) {
2291 dirty_memory_extend(old_ram_size, new_ram_size);
2293 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2294 * QLIST (which has an RCU-friendly variant) does not have insertion at
2295 * tail, so save the last element in last_block.
2297 RAMBLOCK_FOREACH(block) {
2298 last_block = block;
2299 if (block->max_length < new_block->max_length) {
2300 break;
2303 if (block) {
2304 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
2305 } else if (last_block) {
2306 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
2307 } else { /* list is empty */
2308 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
2310 ram_list.mru_block = NULL;
2312 /* Write list before version */
2313 smp_wmb();
2314 ram_list.version++;
2315 qemu_mutex_unlock_ramlist();
2317 cpu_physical_memory_set_dirty_range(new_block->offset,
2318 new_block->used_length,
2319 DIRTY_CLIENTS_ALL);
2321 if (new_block->host) {
2322 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2323 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2324 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
2325 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
2326 ram_block_notify_add(new_block->host, new_block->max_length);
2330 #ifdef CONFIG_POSIX
2331 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2332 uint32_t ram_flags, int fd,
2333 Error **errp)
2335 RAMBlock *new_block;
2336 Error *local_err = NULL;
2337 int64_t file_size;
2339 /* Just support these ram flags by now. */
2340 assert((ram_flags & ~(RAM_SHARED | RAM_PMEM)) == 0);
2342 if (xen_enabled()) {
2343 error_setg(errp, "-mem-path not supported with Xen");
2344 return NULL;
2347 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2348 error_setg(errp,
2349 "host lacks kvm mmu notifiers, -mem-path unsupported");
2350 return NULL;
2353 if (phys_mem_alloc != qemu_anon_ram_alloc) {
2355 * file_ram_alloc() needs to allocate just like
2356 * phys_mem_alloc, but we haven't bothered to provide
2357 * a hook there.
2359 error_setg(errp,
2360 "-mem-path not supported with this accelerator");
2361 return NULL;
2364 size = HOST_PAGE_ALIGN(size);
2365 file_size = get_file_size(fd);
2366 if (file_size > 0 && file_size < size) {
2367 error_setg(errp, "backing store %s size 0x%" PRIx64
2368 " does not match 'size' option 0x" RAM_ADDR_FMT,
2369 mem_path, file_size, size);
2370 return NULL;
2373 new_block = g_malloc0(sizeof(*new_block));
2374 new_block->mr = mr;
2375 new_block->used_length = size;
2376 new_block->max_length = size;
2377 new_block->flags = ram_flags;
2378 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
2379 if (!new_block->host) {
2380 g_free(new_block);
2381 return NULL;
2384 ram_block_add(new_block, &local_err, ram_flags & RAM_SHARED);
2385 if (local_err) {
2386 g_free(new_block);
2387 error_propagate(errp, local_err);
2388 return NULL;
2390 return new_block;
2395 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2396 uint32_t ram_flags, const char *mem_path,
2397 Error **errp)
2399 int fd;
2400 bool created;
2401 RAMBlock *block;
2403 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2404 if (fd < 0) {
2405 return NULL;
2408 block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, errp);
2409 if (!block) {
2410 if (created) {
2411 unlink(mem_path);
2413 close(fd);
2414 return NULL;
2417 return block;
2419 #endif
2421 static
2422 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2423 void (*resized)(const char*,
2424 uint64_t length,
2425 void *host),
2426 void *host, bool resizeable, bool share,
2427 MemoryRegion *mr, Error **errp)
2429 RAMBlock *new_block;
2430 Error *local_err = NULL;
2432 size = HOST_PAGE_ALIGN(size);
2433 max_size = HOST_PAGE_ALIGN(max_size);
2434 new_block = g_malloc0(sizeof(*new_block));
2435 new_block->mr = mr;
2436 new_block->resized = resized;
2437 new_block->used_length = size;
2438 new_block->max_length = max_size;
2439 assert(max_size >= size);
2440 new_block->fd = -1;
2441 new_block->page_size = getpagesize();
2442 new_block->host = host;
2443 if (host) {
2444 new_block->flags |= RAM_PREALLOC;
2446 if (resizeable) {
2447 new_block->flags |= RAM_RESIZEABLE;
2449 ram_block_add(new_block, &local_err, share);
2450 if (local_err) {
2451 g_free(new_block);
2452 error_propagate(errp, local_err);
2453 return NULL;
2455 return new_block;
2458 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2459 MemoryRegion *mr, Error **errp)
2461 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2462 false, mr, errp);
2465 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2466 MemoryRegion *mr, Error **errp)
2468 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2469 share, mr, errp);
2472 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2473 void (*resized)(const char*,
2474 uint64_t length,
2475 void *host),
2476 MemoryRegion *mr, Error **errp)
2478 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2479 false, mr, errp);
2482 static void reclaim_ramblock(RAMBlock *block)
2484 if (block->flags & RAM_PREALLOC) {
2486 } else if (xen_enabled()) {
2487 xen_invalidate_map_cache_entry(block->host);
2488 #ifndef _WIN32
2489 } else if (block->fd >= 0) {
2490 qemu_ram_munmap(block->fd, block->host, block->max_length);
2491 close(block->fd);
2492 #endif
2493 } else {
2494 qemu_anon_ram_free(block->host, block->max_length);
2496 g_free(block);
2499 void qemu_ram_free(RAMBlock *block)
2501 if (!block) {
2502 return;
2505 if (block->host) {
2506 ram_block_notify_remove(block->host, block->max_length);
2509 qemu_mutex_lock_ramlist();
2510 QLIST_REMOVE_RCU(block, next);
2511 ram_list.mru_block = NULL;
2512 /* Write list before version */
2513 smp_wmb();
2514 ram_list.version++;
2515 call_rcu(block, reclaim_ramblock, rcu);
2516 qemu_mutex_unlock_ramlist();
2519 #ifndef _WIN32
2520 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2522 RAMBlock *block;
2523 ram_addr_t offset;
2524 int flags;
2525 void *area, *vaddr;
2527 RAMBLOCK_FOREACH(block) {
2528 offset = addr - block->offset;
2529 if (offset < block->max_length) {
2530 vaddr = ramblock_ptr(block, offset);
2531 if (block->flags & RAM_PREALLOC) {
2533 } else if (xen_enabled()) {
2534 abort();
2535 } else {
2536 flags = MAP_FIXED;
2537 if (block->fd >= 0) {
2538 flags |= (block->flags & RAM_SHARED ?
2539 MAP_SHARED : MAP_PRIVATE);
2540 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2541 flags, block->fd, offset);
2542 } else {
2544 * Remap needs to match alloc. Accelerators that
2545 * set phys_mem_alloc never remap. If they did,
2546 * we'd need a remap hook here.
2548 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2550 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2551 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2552 flags, -1, 0);
2554 if (area != vaddr) {
2555 error_report("Could not remap addr: "
2556 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2557 length, addr);
2558 exit(1);
2560 memory_try_enable_merging(vaddr, length);
2561 qemu_ram_setup_dump(vaddr, length);
2566 #endif /* !_WIN32 */
2568 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2569 * This should not be used for general purpose DMA. Use address_space_map
2570 * or address_space_rw instead. For local memory (e.g. video ram) that the
2571 * device owns, use memory_region_get_ram_ptr.
2573 * Called within RCU critical section.
2575 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2577 RAMBlock *block = ram_block;
2579 if (block == NULL) {
2580 block = qemu_get_ram_block(addr);
2581 addr -= block->offset;
2584 if (xen_enabled() && block->host == NULL) {
2585 /* We need to check if the requested address is in the RAM
2586 * because we don't want to map the entire memory in QEMU.
2587 * In that case just map until the end of the page.
2589 if (block->offset == 0) {
2590 return xen_map_cache(addr, 0, 0, false);
2593 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2595 return ramblock_ptr(block, addr);
2598 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2599 * but takes a size argument.
2601 * Called within RCU critical section.
2603 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2604 hwaddr *size, bool lock)
2606 RAMBlock *block = ram_block;
2607 if (*size == 0) {
2608 return NULL;
2611 if (block == NULL) {
2612 block = qemu_get_ram_block(addr);
2613 addr -= block->offset;
2615 *size = MIN(*size, block->max_length - addr);
2617 if (xen_enabled() && block->host == NULL) {
2618 /* We need to check if the requested address is in the RAM
2619 * because we don't want to map the entire memory in QEMU.
2620 * In that case just map the requested area.
2622 if (block->offset == 0) {
2623 return xen_map_cache(addr, *size, lock, lock);
2626 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2629 return ramblock_ptr(block, addr);
2632 /* Return the offset of a hostpointer within a ramblock */
2633 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2635 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2636 assert((uintptr_t)host >= (uintptr_t)rb->host);
2637 assert(res < rb->max_length);
2639 return res;
2643 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2644 * in that RAMBlock.
2646 * ptr: Host pointer to look up
2647 * round_offset: If true round the result offset down to a page boundary
2648 * *ram_addr: set to result ram_addr
2649 * *offset: set to result offset within the RAMBlock
2651 * Returns: RAMBlock (or NULL if not found)
2653 * By the time this function returns, the returned pointer is not protected
2654 * by RCU anymore. If the caller is not within an RCU critical section and
2655 * does not hold the iothread lock, it must have other means of protecting the
2656 * pointer, such as a reference to the region that includes the incoming
2657 * ram_addr_t.
2659 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2660 ram_addr_t *offset)
2662 RAMBlock *block;
2663 uint8_t *host = ptr;
2665 if (xen_enabled()) {
2666 ram_addr_t ram_addr;
2667 rcu_read_lock();
2668 ram_addr = xen_ram_addr_from_mapcache(ptr);
2669 block = qemu_get_ram_block(ram_addr);
2670 if (block) {
2671 *offset = ram_addr - block->offset;
2673 rcu_read_unlock();
2674 return block;
2677 rcu_read_lock();
2678 block = atomic_rcu_read(&ram_list.mru_block);
2679 if (block && block->host && host - block->host < block->max_length) {
2680 goto found;
2683 RAMBLOCK_FOREACH(block) {
2684 /* This case append when the block is not mapped. */
2685 if (block->host == NULL) {
2686 continue;
2688 if (host - block->host < block->max_length) {
2689 goto found;
2693 rcu_read_unlock();
2694 return NULL;
2696 found:
2697 *offset = (host - block->host);
2698 if (round_offset) {
2699 *offset &= TARGET_PAGE_MASK;
2701 rcu_read_unlock();
2702 return block;
2706 * Finds the named RAMBlock
2708 * name: The name of RAMBlock to find
2710 * Returns: RAMBlock (or NULL if not found)
2712 RAMBlock *qemu_ram_block_by_name(const char *name)
2714 RAMBlock *block;
2716 RAMBLOCK_FOREACH(block) {
2717 if (!strcmp(name, block->idstr)) {
2718 return block;
2722 return NULL;
2725 /* Some of the softmmu routines need to translate from a host pointer
2726 (typically a TLB entry) back to a ram offset. */
2727 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2729 RAMBlock *block;
2730 ram_addr_t offset;
2732 block = qemu_ram_block_from_host(ptr, false, &offset);
2733 if (!block) {
2734 return RAM_ADDR_INVALID;
2737 return block->offset + offset;
2740 /* Called within RCU critical section. */
2741 void memory_notdirty_write_prepare(NotDirtyInfo *ndi,
2742 CPUState *cpu,
2743 vaddr mem_vaddr,
2744 ram_addr_t ram_addr,
2745 unsigned size)
2747 ndi->cpu = cpu;
2748 ndi->ram_addr = ram_addr;
2749 ndi->mem_vaddr = mem_vaddr;
2750 ndi->size = size;
2751 ndi->pages = NULL;
2753 assert(tcg_enabled());
2754 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
2755 ndi->pages = page_collection_lock(ram_addr, ram_addr + size);
2756 tb_invalidate_phys_page_fast(ndi->pages, ram_addr, size);
2760 /* Called within RCU critical section. */
2761 void memory_notdirty_write_complete(NotDirtyInfo *ndi)
2763 if (ndi->pages) {
2764 assert(tcg_enabled());
2765 page_collection_unlock(ndi->pages);
2766 ndi->pages = NULL;
2769 /* Set both VGA and migration bits for simplicity and to remove
2770 * the notdirty callback faster.
2772 cpu_physical_memory_set_dirty_range(ndi->ram_addr, ndi->size,
2773 DIRTY_CLIENTS_NOCODE);
2774 /* we remove the notdirty callback only if the code has been
2775 flushed */
2776 if (!cpu_physical_memory_is_clean(ndi->ram_addr)) {
2777 tlb_set_dirty(ndi->cpu, ndi->mem_vaddr);
2781 /* Called within RCU critical section. */
2782 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2783 uint64_t val, unsigned size)
2785 NotDirtyInfo ndi;
2787 memory_notdirty_write_prepare(&ndi, current_cpu, current_cpu->mem_io_vaddr,
2788 ram_addr, size);
2790 stn_p(qemu_map_ram_ptr(NULL, ram_addr), size, val);
2791 memory_notdirty_write_complete(&ndi);
2794 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
2795 unsigned size, bool is_write,
2796 MemTxAttrs attrs)
2798 return is_write;
2801 static const MemoryRegionOps notdirty_mem_ops = {
2802 .write = notdirty_mem_write,
2803 .valid.accepts = notdirty_mem_accepts,
2804 .endianness = DEVICE_NATIVE_ENDIAN,
2805 .valid = {
2806 .min_access_size = 1,
2807 .max_access_size = 8,
2808 .unaligned = false,
2810 .impl = {
2811 .min_access_size = 1,
2812 .max_access_size = 8,
2813 .unaligned = false,
2817 /* Generate a debug exception if a watchpoint has been hit. */
2818 static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
2820 CPUState *cpu = current_cpu;
2821 CPUClass *cc = CPU_GET_CLASS(cpu);
2822 target_ulong vaddr;
2823 CPUWatchpoint *wp;
2825 assert(tcg_enabled());
2826 if (cpu->watchpoint_hit) {
2827 /* We re-entered the check after replacing the TB. Now raise
2828 * the debug interrupt so that is will trigger after the
2829 * current instruction. */
2830 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2831 return;
2833 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
2834 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
2835 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2836 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2837 && (wp->flags & flags)) {
2838 if (flags == BP_MEM_READ) {
2839 wp->flags |= BP_WATCHPOINT_HIT_READ;
2840 } else {
2841 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2843 wp->hitaddr = vaddr;
2844 wp->hitattrs = attrs;
2845 if (!cpu->watchpoint_hit) {
2846 if (wp->flags & BP_CPU &&
2847 !cc->debug_check_watchpoint(cpu, wp)) {
2848 wp->flags &= ~BP_WATCHPOINT_HIT;
2849 continue;
2851 cpu->watchpoint_hit = wp;
2853 mmap_lock();
2854 tb_check_watchpoint(cpu);
2855 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2856 cpu->exception_index = EXCP_DEBUG;
2857 mmap_unlock();
2858 cpu_loop_exit(cpu);
2859 } else {
2860 /* Force execution of one insn next time. */
2861 cpu->cflags_next_tb = 1 | curr_cflags();
2862 mmap_unlock();
2863 cpu_loop_exit_noexc(cpu);
2866 } else {
2867 wp->flags &= ~BP_WATCHPOINT_HIT;
2872 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2873 so these check for a hit then pass through to the normal out-of-line
2874 phys routines. */
2875 static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2876 unsigned size, MemTxAttrs attrs)
2878 MemTxResult res;
2879 uint64_t data;
2880 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2881 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2883 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2884 switch (size) {
2885 case 1:
2886 data = address_space_ldub(as, addr, attrs, &res);
2887 break;
2888 case 2:
2889 data = address_space_lduw(as, addr, attrs, &res);
2890 break;
2891 case 4:
2892 data = address_space_ldl(as, addr, attrs, &res);
2893 break;
2894 case 8:
2895 data = address_space_ldq(as, addr, attrs, &res);
2896 break;
2897 default: abort();
2899 *pdata = data;
2900 return res;
2903 static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2904 uint64_t val, unsigned size,
2905 MemTxAttrs attrs)
2907 MemTxResult res;
2908 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2909 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2911 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2912 switch (size) {
2913 case 1:
2914 address_space_stb(as, addr, val, attrs, &res);
2915 break;
2916 case 2:
2917 address_space_stw(as, addr, val, attrs, &res);
2918 break;
2919 case 4:
2920 address_space_stl(as, addr, val, attrs, &res);
2921 break;
2922 case 8:
2923 address_space_stq(as, addr, val, attrs, &res);
2924 break;
2925 default: abort();
2927 return res;
2930 static const MemoryRegionOps watch_mem_ops = {
2931 .read_with_attrs = watch_mem_read,
2932 .write_with_attrs = watch_mem_write,
2933 .endianness = DEVICE_NATIVE_ENDIAN,
2934 .valid = {
2935 .min_access_size = 1,
2936 .max_access_size = 8,
2937 .unaligned = false,
2939 .impl = {
2940 .min_access_size = 1,
2941 .max_access_size = 8,
2942 .unaligned = false,
2946 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2947 MemTxAttrs attrs, uint8_t *buf, hwaddr len);
2948 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2949 const uint8_t *buf, hwaddr len);
2950 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2951 bool is_write, MemTxAttrs attrs);
2953 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2954 unsigned len, MemTxAttrs attrs)
2956 subpage_t *subpage = opaque;
2957 uint8_t buf[8];
2958 MemTxResult res;
2960 #if defined(DEBUG_SUBPAGE)
2961 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2962 subpage, len, addr);
2963 #endif
2964 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2965 if (res) {
2966 return res;
2968 *data = ldn_p(buf, len);
2969 return MEMTX_OK;
2972 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2973 uint64_t value, unsigned len, MemTxAttrs attrs)
2975 subpage_t *subpage = opaque;
2976 uint8_t buf[8];
2978 #if defined(DEBUG_SUBPAGE)
2979 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2980 " value %"PRIx64"\n",
2981 __func__, subpage, len, addr, value);
2982 #endif
2983 stn_p(buf, len, value);
2984 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2987 static bool subpage_accepts(void *opaque, hwaddr addr,
2988 unsigned len, bool is_write,
2989 MemTxAttrs attrs)
2991 subpage_t *subpage = opaque;
2992 #if defined(DEBUG_SUBPAGE)
2993 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2994 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2995 #endif
2997 return flatview_access_valid(subpage->fv, addr + subpage->base,
2998 len, is_write, attrs);
3001 static const MemoryRegionOps subpage_ops = {
3002 .read_with_attrs = subpage_read,
3003 .write_with_attrs = subpage_write,
3004 .impl.min_access_size = 1,
3005 .impl.max_access_size = 8,
3006 .valid.min_access_size = 1,
3007 .valid.max_access_size = 8,
3008 .valid.accepts = subpage_accepts,
3009 .endianness = DEVICE_NATIVE_ENDIAN,
3012 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
3013 uint16_t section)
3015 int idx, eidx;
3017 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
3018 return -1;
3019 idx = SUBPAGE_IDX(start);
3020 eidx = SUBPAGE_IDX(end);
3021 #if defined(DEBUG_SUBPAGE)
3022 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
3023 __func__, mmio, start, end, idx, eidx, section);
3024 #endif
3025 for (; idx <= eidx; idx++) {
3026 mmio->sub_section[idx] = section;
3029 return 0;
3032 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
3034 subpage_t *mmio;
3036 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
3037 mmio->fv = fv;
3038 mmio->base = base;
3039 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
3040 NULL, TARGET_PAGE_SIZE);
3041 mmio->iomem.subpage = true;
3042 #if defined(DEBUG_SUBPAGE)
3043 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
3044 mmio, base, TARGET_PAGE_SIZE);
3045 #endif
3046 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
3048 return mmio;
3051 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
3053 assert(fv);
3054 MemoryRegionSection section = {
3055 .fv = fv,
3056 .mr = mr,
3057 .offset_within_address_space = 0,
3058 .offset_within_region = 0,
3059 .size = int128_2_64(),
3062 return phys_section_add(map, &section);
3065 static void readonly_mem_write(void *opaque, hwaddr addr,
3066 uint64_t val, unsigned size)
3068 /* Ignore any write to ROM. */
3071 static bool readonly_mem_accepts(void *opaque, hwaddr addr,
3072 unsigned size, bool is_write,
3073 MemTxAttrs attrs)
3075 return is_write;
3078 /* This will only be used for writes, because reads are special cased
3079 * to directly access the underlying host ram.
3081 static const MemoryRegionOps readonly_mem_ops = {
3082 .write = readonly_mem_write,
3083 .valid.accepts = readonly_mem_accepts,
3084 .endianness = DEVICE_NATIVE_ENDIAN,
3085 .valid = {
3086 .min_access_size = 1,
3087 .max_access_size = 8,
3088 .unaligned = false,
3090 .impl = {
3091 .min_access_size = 1,
3092 .max_access_size = 8,
3093 .unaligned = false,
3097 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
3098 hwaddr index, MemTxAttrs attrs)
3100 int asidx = cpu_asidx_from_attrs(cpu, attrs);
3101 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
3102 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
3103 MemoryRegionSection *sections = d->map.sections;
3105 return &sections[index & ~TARGET_PAGE_MASK];
3108 static void io_mem_init(void)
3110 memory_region_init_io(&io_mem_rom, NULL, &readonly_mem_ops,
3111 NULL, NULL, UINT64_MAX);
3112 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
3113 NULL, UINT64_MAX);
3115 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
3116 * which can be called without the iothread mutex.
3118 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
3119 NULL, UINT64_MAX);
3120 memory_region_clear_global_locking(&io_mem_notdirty);
3122 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
3123 NULL, UINT64_MAX);
3126 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
3128 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
3129 uint16_t n;
3131 n = dummy_section(&d->map, fv, &io_mem_unassigned);
3132 assert(n == PHYS_SECTION_UNASSIGNED);
3133 n = dummy_section(&d->map, fv, &io_mem_notdirty);
3134 assert(n == PHYS_SECTION_NOTDIRTY);
3135 n = dummy_section(&d->map, fv, &io_mem_rom);
3136 assert(n == PHYS_SECTION_ROM);
3137 n = dummy_section(&d->map, fv, &io_mem_watch);
3138 assert(n == PHYS_SECTION_WATCH);
3140 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
3142 return d;
3145 void address_space_dispatch_free(AddressSpaceDispatch *d)
3147 phys_sections_free(&d->map);
3148 g_free(d);
3151 static void tcg_commit(MemoryListener *listener)
3153 CPUAddressSpace *cpuas;
3154 AddressSpaceDispatch *d;
3156 assert(tcg_enabled());
3157 /* since each CPU stores ram addresses in its TLB cache, we must
3158 reset the modified entries */
3159 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
3160 cpu_reloading_memory_map();
3161 /* The CPU and TLB are protected by the iothread lock.
3162 * We reload the dispatch pointer now because cpu_reloading_memory_map()
3163 * may have split the RCU critical section.
3165 d = address_space_to_dispatch(cpuas->as);
3166 atomic_rcu_set(&cpuas->memory_dispatch, d);
3167 tlb_flush(cpuas->cpu);
3170 static void memory_map_init(void)
3172 system_memory = g_malloc(sizeof(*system_memory));
3174 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
3175 address_space_init(&address_space_memory, system_memory, "memory");
3177 system_io = g_malloc(sizeof(*system_io));
3178 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
3179 65536);
3180 address_space_init(&address_space_io, system_io, "I/O");
3183 MemoryRegion *get_system_memory(void)
3185 return system_memory;
3188 MemoryRegion *get_system_io(void)
3190 return system_io;
3193 #endif /* !defined(CONFIG_USER_ONLY) */
3195 /* physical memory access (slow version, mainly for debug) */
3196 #if defined(CONFIG_USER_ONLY)
3197 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3198 uint8_t *buf, target_ulong len, int is_write)
3200 int flags;
3201 target_ulong l, page;
3202 void * p;
3204 while (len > 0) {
3205 page = addr & TARGET_PAGE_MASK;
3206 l = (page + TARGET_PAGE_SIZE) - addr;
3207 if (l > len)
3208 l = len;
3209 flags = page_get_flags(page);
3210 if (!(flags & PAGE_VALID))
3211 return -1;
3212 if (is_write) {
3213 if (!(flags & PAGE_WRITE))
3214 return -1;
3215 /* XXX: this code should not depend on lock_user */
3216 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
3217 return -1;
3218 memcpy(p, buf, l);
3219 unlock_user(p, addr, l);
3220 } else {
3221 if (!(flags & PAGE_READ))
3222 return -1;
3223 /* XXX: this code should not depend on lock_user */
3224 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
3225 return -1;
3226 memcpy(buf, p, l);
3227 unlock_user(p, addr, 0);
3229 len -= l;
3230 buf += l;
3231 addr += l;
3233 return 0;
3236 #else
3238 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
3239 hwaddr length)
3241 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
3242 addr += memory_region_get_ram_addr(mr);
3244 /* No early return if dirty_log_mask is or becomes 0, because
3245 * cpu_physical_memory_set_dirty_range will still call
3246 * xen_modified_memory.
3248 if (dirty_log_mask) {
3249 dirty_log_mask =
3250 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
3252 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
3253 assert(tcg_enabled());
3254 tb_invalidate_phys_range(addr, addr + length);
3255 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
3257 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
3260 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
3263 * In principle this function would work on other memory region types too,
3264 * but the ROM device use case is the only one where this operation is
3265 * necessary. Other memory regions should use the
3266 * address_space_read/write() APIs.
3268 assert(memory_region_is_romd(mr));
3270 invalidate_and_set_dirty(mr, addr, size);
3273 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
3275 unsigned access_size_max = mr->ops->valid.max_access_size;
3277 /* Regions are assumed to support 1-4 byte accesses unless
3278 otherwise specified. */
3279 if (access_size_max == 0) {
3280 access_size_max = 4;
3283 /* Bound the maximum access by the alignment of the address. */
3284 if (!mr->ops->impl.unaligned) {
3285 unsigned align_size_max = addr & -addr;
3286 if (align_size_max != 0 && align_size_max < access_size_max) {
3287 access_size_max = align_size_max;
3291 /* Don't attempt accesses larger than the maximum. */
3292 if (l > access_size_max) {
3293 l = access_size_max;
3295 l = pow2floor(l);
3297 return l;
3300 static bool prepare_mmio_access(MemoryRegion *mr)
3302 bool unlocked = !qemu_mutex_iothread_locked();
3303 bool release_lock = false;
3305 if (unlocked && mr->global_locking) {
3306 qemu_mutex_lock_iothread();
3307 unlocked = false;
3308 release_lock = true;
3310 if (mr->flush_coalesced_mmio) {
3311 if (unlocked) {
3312 qemu_mutex_lock_iothread();
3314 qemu_flush_coalesced_mmio_buffer();
3315 if (unlocked) {
3316 qemu_mutex_unlock_iothread();
3320 return release_lock;
3323 /* Called within RCU critical section. */
3324 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
3325 MemTxAttrs attrs,
3326 const uint8_t *buf,
3327 hwaddr len, hwaddr addr1,
3328 hwaddr l, MemoryRegion *mr)
3330 uint8_t *ptr;
3331 uint64_t val;
3332 MemTxResult result = MEMTX_OK;
3333 bool release_lock = false;
3335 for (;;) {
3336 if (!memory_access_is_direct(mr, true)) {
3337 release_lock |= prepare_mmio_access(mr);
3338 l = memory_access_size(mr, l, addr1);
3339 /* XXX: could force current_cpu to NULL to avoid
3340 potential bugs */
3341 val = ldn_p(buf, l);
3342 result |= memory_region_dispatch_write(mr, addr1, val, l, attrs);
3343 } else {
3344 /* RAM case */
3345 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3346 memcpy(ptr, buf, l);
3347 invalidate_and_set_dirty(mr, addr1, l);
3350 if (release_lock) {
3351 qemu_mutex_unlock_iothread();
3352 release_lock = false;
3355 len -= l;
3356 buf += l;
3357 addr += l;
3359 if (!len) {
3360 break;
3363 l = len;
3364 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
3367 return result;
3370 /* Called from RCU critical section. */
3371 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
3372 const uint8_t *buf, hwaddr len)
3374 hwaddr l;
3375 hwaddr addr1;
3376 MemoryRegion *mr;
3377 MemTxResult result = MEMTX_OK;
3379 l = len;
3380 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
3381 result = flatview_write_continue(fv, addr, attrs, buf, len,
3382 addr1, l, mr);
3384 return result;
3387 /* Called within RCU critical section. */
3388 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
3389 MemTxAttrs attrs, uint8_t *buf,
3390 hwaddr len, hwaddr addr1, hwaddr l,
3391 MemoryRegion *mr)
3393 uint8_t *ptr;
3394 uint64_t val;
3395 MemTxResult result = MEMTX_OK;
3396 bool release_lock = false;
3398 for (;;) {
3399 if (!memory_access_is_direct(mr, false)) {
3400 /* I/O case */
3401 release_lock |= prepare_mmio_access(mr);
3402 l = memory_access_size(mr, l, addr1);
3403 result |= memory_region_dispatch_read(mr, addr1, &val, l, attrs);
3404 stn_p(buf, l, val);
3405 } else {
3406 /* RAM case */
3407 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3408 memcpy(buf, ptr, l);
3411 if (release_lock) {
3412 qemu_mutex_unlock_iothread();
3413 release_lock = false;
3416 len -= l;
3417 buf += l;
3418 addr += l;
3420 if (!len) {
3421 break;
3424 l = len;
3425 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3428 return result;
3431 /* Called from RCU critical section. */
3432 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
3433 MemTxAttrs attrs, uint8_t *buf, hwaddr len)
3435 hwaddr l;
3436 hwaddr addr1;
3437 MemoryRegion *mr;
3439 l = len;
3440 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3441 return flatview_read_continue(fv, addr, attrs, buf, len,
3442 addr1, l, mr);
3445 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3446 MemTxAttrs attrs, uint8_t *buf, hwaddr len)
3448 MemTxResult result = MEMTX_OK;
3449 FlatView *fv;
3451 if (len > 0) {
3452 rcu_read_lock();
3453 fv = address_space_to_flatview(as);
3454 result = flatview_read(fv, addr, attrs, buf, len);
3455 rcu_read_unlock();
3458 return result;
3461 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
3462 MemTxAttrs attrs,
3463 const uint8_t *buf, hwaddr len)
3465 MemTxResult result = MEMTX_OK;
3466 FlatView *fv;
3468 if (len > 0) {
3469 rcu_read_lock();
3470 fv = address_space_to_flatview(as);
3471 result = flatview_write(fv, addr, attrs, buf, len);
3472 rcu_read_unlock();
3475 return result;
3478 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3479 uint8_t *buf, hwaddr len, bool is_write)
3481 if (is_write) {
3482 return address_space_write(as, addr, attrs, buf, len);
3483 } else {
3484 return address_space_read_full(as, addr, attrs, buf, len);
3488 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
3489 hwaddr len, int is_write)
3491 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3492 buf, len, is_write);
3495 enum write_rom_type {
3496 WRITE_DATA,
3497 FLUSH_CACHE,
3500 static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
3501 hwaddr addr,
3502 MemTxAttrs attrs,
3503 const uint8_t *buf,
3504 hwaddr len,
3505 enum write_rom_type type)
3507 hwaddr l;
3508 uint8_t *ptr;
3509 hwaddr addr1;
3510 MemoryRegion *mr;
3512 rcu_read_lock();
3513 while (len > 0) {
3514 l = len;
3515 mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
3517 if (!(memory_region_is_ram(mr) ||
3518 memory_region_is_romd(mr))) {
3519 l = memory_access_size(mr, l, addr1);
3520 } else {
3521 /* ROM/RAM case */
3522 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3523 switch (type) {
3524 case WRITE_DATA:
3525 memcpy(ptr, buf, l);
3526 invalidate_and_set_dirty(mr, addr1, l);
3527 break;
3528 case FLUSH_CACHE:
3529 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
3530 break;
3533 len -= l;
3534 buf += l;
3535 addr += l;
3537 rcu_read_unlock();
3538 return MEMTX_OK;
3541 /* used for ROM loading : can write in RAM and ROM */
3542 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
3543 MemTxAttrs attrs,
3544 const uint8_t *buf, hwaddr len)
3546 return address_space_write_rom_internal(as, addr, attrs,
3547 buf, len, WRITE_DATA);
3550 void cpu_flush_icache_range(hwaddr start, hwaddr len)
3553 * This function should do the same thing as an icache flush that was
3554 * triggered from within the guest. For TCG we are always cache coherent,
3555 * so there is no need to flush anything. For KVM / Xen we need to flush
3556 * the host's instruction cache at least.
3558 if (tcg_enabled()) {
3559 return;
3562 address_space_write_rom_internal(&address_space_memory,
3563 start, MEMTXATTRS_UNSPECIFIED,
3564 NULL, len, FLUSH_CACHE);
3567 typedef struct {
3568 MemoryRegion *mr;
3569 void *buffer;
3570 hwaddr addr;
3571 hwaddr len;
3572 bool in_use;
3573 } BounceBuffer;
3575 static BounceBuffer bounce;
3577 typedef struct MapClient {
3578 QEMUBH *bh;
3579 QLIST_ENTRY(MapClient) link;
3580 } MapClient;
3582 QemuMutex map_client_list_lock;
3583 static QLIST_HEAD(, MapClient) map_client_list
3584 = QLIST_HEAD_INITIALIZER(map_client_list);
3586 static void cpu_unregister_map_client_do(MapClient *client)
3588 QLIST_REMOVE(client, link);
3589 g_free(client);
3592 static void cpu_notify_map_clients_locked(void)
3594 MapClient *client;
3596 while (!QLIST_EMPTY(&map_client_list)) {
3597 client = QLIST_FIRST(&map_client_list);
3598 qemu_bh_schedule(client->bh);
3599 cpu_unregister_map_client_do(client);
3603 void cpu_register_map_client(QEMUBH *bh)
3605 MapClient *client = g_malloc(sizeof(*client));
3607 qemu_mutex_lock(&map_client_list_lock);
3608 client->bh = bh;
3609 QLIST_INSERT_HEAD(&map_client_list, client, link);
3610 if (!atomic_read(&bounce.in_use)) {
3611 cpu_notify_map_clients_locked();
3613 qemu_mutex_unlock(&map_client_list_lock);
3616 void cpu_exec_init_all(void)
3618 qemu_mutex_init(&ram_list.mutex);
3619 /* The data structures we set up here depend on knowing the page size,
3620 * so no more changes can be made after this point.
3621 * In an ideal world, nothing we did before we had finished the
3622 * machine setup would care about the target page size, and we could
3623 * do this much later, rather than requiring board models to state
3624 * up front what their requirements are.
3626 finalize_target_page_bits();
3627 io_mem_init();
3628 memory_map_init();
3629 qemu_mutex_init(&map_client_list_lock);
3632 void cpu_unregister_map_client(QEMUBH *bh)
3634 MapClient *client;
3636 qemu_mutex_lock(&map_client_list_lock);
3637 QLIST_FOREACH(client, &map_client_list, link) {
3638 if (client->bh == bh) {
3639 cpu_unregister_map_client_do(client);
3640 break;
3643 qemu_mutex_unlock(&map_client_list_lock);
3646 static void cpu_notify_map_clients(void)
3648 qemu_mutex_lock(&map_client_list_lock);
3649 cpu_notify_map_clients_locked();
3650 qemu_mutex_unlock(&map_client_list_lock);
3653 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
3654 bool is_write, MemTxAttrs attrs)
3656 MemoryRegion *mr;
3657 hwaddr l, xlat;
3659 while (len > 0) {
3660 l = len;
3661 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3662 if (!memory_access_is_direct(mr, is_write)) {
3663 l = memory_access_size(mr, l, addr);
3664 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3665 return false;
3669 len -= l;
3670 addr += l;
3672 return true;
3675 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3676 hwaddr len, bool is_write,
3677 MemTxAttrs attrs)
3679 FlatView *fv;
3680 bool result;
3682 rcu_read_lock();
3683 fv = address_space_to_flatview(as);
3684 result = flatview_access_valid(fv, addr, len, is_write, attrs);
3685 rcu_read_unlock();
3686 return result;
3689 static hwaddr
3690 flatview_extend_translation(FlatView *fv, hwaddr addr,
3691 hwaddr target_len,
3692 MemoryRegion *mr, hwaddr base, hwaddr len,
3693 bool is_write, MemTxAttrs attrs)
3695 hwaddr done = 0;
3696 hwaddr xlat;
3697 MemoryRegion *this_mr;
3699 for (;;) {
3700 target_len -= len;
3701 addr += len;
3702 done += len;
3703 if (target_len == 0) {
3704 return done;
3707 len = target_len;
3708 this_mr = flatview_translate(fv, addr, &xlat,
3709 &len, is_write, attrs);
3710 if (this_mr != mr || xlat != base + done) {
3711 return done;
3716 /* Map a physical memory region into a host virtual address.
3717 * May map a subset of the requested range, given by and returned in *plen.
3718 * May return NULL if resources needed to perform the mapping are exhausted.
3719 * Use only for reads OR writes - not for read-modify-write operations.
3720 * Use cpu_register_map_client() to know when retrying the map operation is
3721 * likely to succeed.
3723 void *address_space_map(AddressSpace *as,
3724 hwaddr addr,
3725 hwaddr *plen,
3726 bool is_write,
3727 MemTxAttrs attrs)
3729 hwaddr len = *plen;
3730 hwaddr l, xlat;
3731 MemoryRegion *mr;
3732 void *ptr;
3733 FlatView *fv;
3735 if (len == 0) {
3736 return NULL;
3739 l = len;
3740 rcu_read_lock();
3741 fv = address_space_to_flatview(as);
3742 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3744 if (!memory_access_is_direct(mr, is_write)) {
3745 if (atomic_xchg(&bounce.in_use, true)) {
3746 rcu_read_unlock();
3747 return NULL;
3749 /* Avoid unbounded allocations */
3750 l = MIN(l, TARGET_PAGE_SIZE);
3751 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3752 bounce.addr = addr;
3753 bounce.len = l;
3755 memory_region_ref(mr);
3756 bounce.mr = mr;
3757 if (!is_write) {
3758 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3759 bounce.buffer, l);
3762 rcu_read_unlock();
3763 *plen = l;
3764 return bounce.buffer;
3768 memory_region_ref(mr);
3769 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3770 l, is_write, attrs);
3771 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3772 rcu_read_unlock();
3774 return ptr;
3777 /* Unmaps a memory region previously mapped by address_space_map().
3778 * Will also mark the memory as dirty if is_write == 1. access_len gives
3779 * the amount of memory that was actually read or written by the caller.
3781 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3782 int is_write, hwaddr access_len)
3784 if (buffer != bounce.buffer) {
3785 MemoryRegion *mr;
3786 ram_addr_t addr1;
3788 mr = memory_region_from_host(buffer, &addr1);
3789 assert(mr != NULL);
3790 if (is_write) {
3791 invalidate_and_set_dirty(mr, addr1, access_len);
3793 if (xen_enabled()) {
3794 xen_invalidate_map_cache_entry(buffer);
3796 memory_region_unref(mr);
3797 return;
3799 if (is_write) {
3800 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3801 bounce.buffer, access_len);
3803 qemu_vfree(bounce.buffer);
3804 bounce.buffer = NULL;
3805 memory_region_unref(bounce.mr);
3806 atomic_mb_set(&bounce.in_use, false);
3807 cpu_notify_map_clients();
3810 void *cpu_physical_memory_map(hwaddr addr,
3811 hwaddr *plen,
3812 int is_write)
3814 return address_space_map(&address_space_memory, addr, plen, is_write,
3815 MEMTXATTRS_UNSPECIFIED);
3818 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3819 int is_write, hwaddr access_len)
3821 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3824 #define ARG1_DECL AddressSpace *as
3825 #define ARG1 as
3826 #define SUFFIX
3827 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3828 #define RCU_READ_LOCK(...) rcu_read_lock()
3829 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3830 #include "memory_ldst.inc.c"
3832 int64_t address_space_cache_init(MemoryRegionCache *cache,
3833 AddressSpace *as,
3834 hwaddr addr,
3835 hwaddr len,
3836 bool is_write)
3838 AddressSpaceDispatch *d;
3839 hwaddr l;
3840 MemoryRegion *mr;
3842 assert(len > 0);
3844 l = len;
3845 cache->fv = address_space_get_flatview(as);
3846 d = flatview_to_dispatch(cache->fv);
3847 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3849 mr = cache->mrs.mr;
3850 memory_region_ref(mr);
3851 if (memory_access_is_direct(mr, is_write)) {
3852 /* We don't care about the memory attributes here as we're only
3853 * doing this if we found actual RAM, which behaves the same
3854 * regardless of attributes; so UNSPECIFIED is fine.
3856 l = flatview_extend_translation(cache->fv, addr, len, mr,
3857 cache->xlat, l, is_write,
3858 MEMTXATTRS_UNSPECIFIED);
3859 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3860 } else {
3861 cache->ptr = NULL;
3864 cache->len = l;
3865 cache->is_write = is_write;
3866 return l;
3869 void address_space_cache_invalidate(MemoryRegionCache *cache,
3870 hwaddr addr,
3871 hwaddr access_len)
3873 assert(cache->is_write);
3874 if (likely(cache->ptr)) {
3875 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3879 void address_space_cache_destroy(MemoryRegionCache *cache)
3881 if (!cache->mrs.mr) {
3882 return;
3885 if (xen_enabled()) {
3886 xen_invalidate_map_cache_entry(cache->ptr);
3888 memory_region_unref(cache->mrs.mr);
3889 flatview_unref(cache->fv);
3890 cache->mrs.mr = NULL;
3891 cache->fv = NULL;
3894 /* Called from RCU critical section. This function has the same
3895 * semantics as address_space_translate, but it only works on a
3896 * predefined range of a MemoryRegion that was mapped with
3897 * address_space_cache_init.
3899 static inline MemoryRegion *address_space_translate_cached(
3900 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3901 hwaddr *plen, bool is_write, MemTxAttrs attrs)
3903 MemoryRegionSection section;
3904 MemoryRegion *mr;
3905 IOMMUMemoryRegion *iommu_mr;
3906 AddressSpace *target_as;
3908 assert(!cache->ptr);
3909 *xlat = addr + cache->xlat;
3911 mr = cache->mrs.mr;
3912 iommu_mr = memory_region_get_iommu(mr);
3913 if (!iommu_mr) {
3914 /* MMIO region. */
3915 return mr;
3918 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3919 NULL, is_write, true,
3920 &target_as, attrs);
3921 return section.mr;
3924 /* Called from RCU critical section. address_space_read_cached uses this
3925 * out of line function when the target is an MMIO or IOMMU region.
3927 void
3928 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3929 void *buf, hwaddr len)
3931 hwaddr addr1, l;
3932 MemoryRegion *mr;
3934 l = len;
3935 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3936 MEMTXATTRS_UNSPECIFIED);
3937 flatview_read_continue(cache->fv,
3938 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3939 addr1, l, mr);
3942 /* Called from RCU critical section. address_space_write_cached uses this
3943 * out of line function when the target is an MMIO or IOMMU region.
3945 void
3946 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3947 const void *buf, hwaddr len)
3949 hwaddr addr1, l;
3950 MemoryRegion *mr;
3952 l = len;
3953 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3954 MEMTXATTRS_UNSPECIFIED);
3955 flatview_write_continue(cache->fv,
3956 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3957 addr1, l, mr);
3960 #define ARG1_DECL MemoryRegionCache *cache
3961 #define ARG1 cache
3962 #define SUFFIX _cached_slow
3963 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3964 #define RCU_READ_LOCK() ((void)0)
3965 #define RCU_READ_UNLOCK() ((void)0)
3966 #include "memory_ldst.inc.c"
3968 /* virtual memory access for debug (includes writing to ROM) */
3969 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3970 uint8_t *buf, target_ulong len, int is_write)
3972 hwaddr phys_addr;
3973 target_ulong l, page;
3975 cpu_synchronize_state(cpu);
3976 while (len > 0) {
3977 int asidx;
3978 MemTxAttrs attrs;
3980 page = addr & TARGET_PAGE_MASK;
3981 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3982 asidx = cpu_asidx_from_attrs(cpu, attrs);
3983 /* if no physical page mapped, return an error */
3984 if (phys_addr == -1)
3985 return -1;
3986 l = (page + TARGET_PAGE_SIZE) - addr;
3987 if (l > len)
3988 l = len;
3989 phys_addr += (addr & ~TARGET_PAGE_MASK);
3990 if (is_write) {
3991 address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3992 attrs, buf, l);
3993 } else {
3994 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3995 attrs, buf, l, 0);
3997 len -= l;
3998 buf += l;
3999 addr += l;
4001 return 0;
4005 * Allows code that needs to deal with migration bitmaps etc to still be built
4006 * target independent.
4008 size_t qemu_target_page_size(void)
4010 return TARGET_PAGE_SIZE;
4013 int qemu_target_page_bits(void)
4015 return TARGET_PAGE_BITS;
4018 int qemu_target_page_bits_min(void)
4020 return TARGET_PAGE_BITS_MIN;
4022 #endif
4024 bool target_words_bigendian(void)
4026 #if defined(TARGET_WORDS_BIGENDIAN)
4027 return true;
4028 #else
4029 return false;
4030 #endif
4033 #ifndef CONFIG_USER_ONLY
4034 bool cpu_physical_memory_is_io(hwaddr phys_addr)
4036 MemoryRegion*mr;
4037 hwaddr l = 1;
4038 bool res;
4040 rcu_read_lock();
4041 mr = address_space_translate(&address_space_memory,
4042 phys_addr, &phys_addr, &l, false,
4043 MEMTXATTRS_UNSPECIFIED);
4045 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
4046 rcu_read_unlock();
4047 return res;
4050 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
4052 RAMBlock *block;
4053 int ret = 0;
4055 rcu_read_lock();
4056 RAMBLOCK_FOREACH(block) {
4057 ret = func(block, opaque);
4058 if (ret) {
4059 break;
4062 rcu_read_unlock();
4063 return ret;
4067 * Unmap pages of memory from start to start+length such that
4068 * they a) read as 0, b) Trigger whatever fault mechanism
4069 * the OS provides for postcopy.
4070 * The pages must be unmapped by the end of the function.
4071 * Returns: 0 on success, none-0 on failure
4074 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
4076 int ret = -1;
4078 uint8_t *host_startaddr = rb->host + start;
4080 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
4081 error_report("ram_block_discard_range: Unaligned start address: %p",
4082 host_startaddr);
4083 goto err;
4086 if ((start + length) <= rb->used_length) {
4087 bool need_madvise, need_fallocate;
4088 uint8_t *host_endaddr = host_startaddr + length;
4089 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
4090 error_report("ram_block_discard_range: Unaligned end address: %p",
4091 host_endaddr);
4092 goto err;
4095 errno = ENOTSUP; /* If we are missing MADVISE etc */
4097 /* The logic here is messy;
4098 * madvise DONTNEED fails for hugepages
4099 * fallocate works on hugepages and shmem
4101 need_madvise = (rb->page_size == qemu_host_page_size);
4102 need_fallocate = rb->fd != -1;
4103 if (need_fallocate) {
4104 /* For a file, this causes the area of the file to be zero'd
4105 * if read, and for hugetlbfs also causes it to be unmapped
4106 * so a userfault will trigger.
4108 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
4109 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
4110 start, length);
4111 if (ret) {
4112 ret = -errno;
4113 error_report("ram_block_discard_range: Failed to fallocate "
4114 "%s:%" PRIx64 " +%zx (%d)",
4115 rb->idstr, start, length, ret);
4116 goto err;
4118 #else
4119 ret = -ENOSYS;
4120 error_report("ram_block_discard_range: fallocate not available/file"
4121 "%s:%" PRIx64 " +%zx (%d)",
4122 rb->idstr, start, length, ret);
4123 goto err;
4124 #endif
4126 if (need_madvise) {
4127 /* For normal RAM this causes it to be unmapped,
4128 * for shared memory it causes the local mapping to disappear
4129 * and to fall back on the file contents (which we just
4130 * fallocate'd away).
4132 #if defined(CONFIG_MADVISE)
4133 ret = madvise(host_startaddr, length, MADV_DONTNEED);
4134 if (ret) {
4135 ret = -errno;
4136 error_report("ram_block_discard_range: Failed to discard range "
4137 "%s:%" PRIx64 " +%zx (%d)",
4138 rb->idstr, start, length, ret);
4139 goto err;
4141 #else
4142 ret = -ENOSYS;
4143 error_report("ram_block_discard_range: MADVISE not available"
4144 "%s:%" PRIx64 " +%zx (%d)",
4145 rb->idstr, start, length, ret);
4146 goto err;
4147 #endif
4149 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
4150 need_madvise, need_fallocate, ret);
4151 } else {
4152 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
4153 "/%zx/" RAM_ADDR_FMT")",
4154 rb->idstr, start, length, rb->used_length);
4157 err:
4158 return ret;
4161 bool ramblock_is_pmem(RAMBlock *rb)
4163 return rb->flags & RAM_PMEM;
4166 #endif
4168 void page_size_init(void)
4170 /* NOTE: we can always suppose that qemu_host_page_size >=
4171 TARGET_PAGE_SIZE */
4172 if (qemu_host_page_size == 0) {
4173 qemu_host_page_size = qemu_real_host_page_size;
4175 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
4176 qemu_host_page_size = TARGET_PAGE_SIZE;
4178 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;
4181 #if !defined(CONFIG_USER_ONLY)
4183 static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
4185 if (start == end - 1) {
4186 qemu_printf("\t%3d ", start);
4187 } else {
4188 qemu_printf("\t%3d..%-3d ", start, end - 1);
4190 qemu_printf(" skip=%d ", skip);
4191 if (ptr == PHYS_MAP_NODE_NIL) {
4192 qemu_printf(" ptr=NIL");
4193 } else if (!skip) {
4194 qemu_printf(" ptr=#%d", ptr);
4195 } else {
4196 qemu_printf(" ptr=[%d]", ptr);
4198 qemu_printf("\n");
4201 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
4202 int128_sub((size), int128_one())) : 0)
4204 void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
4206 int i;
4208 qemu_printf(" Dispatch\n");
4209 qemu_printf(" Physical sections\n");
4211 for (i = 0; i < d->map.sections_nb; ++i) {
4212 MemoryRegionSection *s = d->map.sections + i;
4213 const char *names[] = { " [unassigned]", " [not dirty]",
4214 " [ROM]", " [watch]" };
4216 qemu_printf(" #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx
4217 " %s%s%s%s%s",
4219 s->offset_within_address_space,
4220 s->offset_within_address_space + MR_SIZE(s->mr->size),
4221 s->mr->name ? s->mr->name : "(noname)",
4222 i < ARRAY_SIZE(names) ? names[i] : "",
4223 s->mr == root ? " [ROOT]" : "",
4224 s == d->mru_section ? " [MRU]" : "",
4225 s->mr->is_iommu ? " [iommu]" : "");
4227 if (s->mr->alias) {
4228 qemu_printf(" alias=%s", s->mr->alias->name ?
4229 s->mr->alias->name : "noname");
4231 qemu_printf("\n");
4234 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
4235 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
4236 for (i = 0; i < d->map.nodes_nb; ++i) {
4237 int j, jprev;
4238 PhysPageEntry prev;
4239 Node *n = d->map.nodes + i;
4241 qemu_printf(" [%d]\n", i);
4243 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
4244 PhysPageEntry *pe = *n + j;
4246 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
4247 continue;
4250 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
4252 jprev = j;
4253 prev = *pe;
4256 if (jprev != ARRAY_SIZE(*n)) {
4257 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
4262 #endif