]> git.ipfire.org Git - thirdparty/qemu.git/blame - exec.c
exec.c: Use stn_p() and ldn_p() instead of explicit switches
[thirdparty/qemu.git] / exec.c
CommitLineData
54936004 1/*
5b6dd868 2 * Virtual page mapping
5fafdf24 3 *
54936004
FB
4 * Copyright (c) 2003 Fabrice Bellard
5 *
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.
10 *
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.
15 *
16 * You should have received a copy of the GNU Lesser General Public
8167ee88 17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
54936004 18 */
7b31bbc2 19#include "qemu/osdep.h"
da34e65c 20#include "qapi/error.h"
54936004 21
f348b6d1 22#include "qemu/cutils.h"
6180a181 23#include "cpu.h"
63c91552 24#include "exec/exec-all.h"
51180423 25#include "exec/target_page.h"
b67d9a52 26#include "tcg.h"
741da0d3 27#include "hw/qdev-core.h"
c7e002c5 28#include "hw/qdev-properties.h"
4485bd26 29#if !defined(CONFIG_USER_ONLY)
47c8ca53 30#include "hw/boards.h"
33c11879 31#include "hw/xen/xen.h"
4485bd26 32#endif
9c17d615 33#include "sysemu/kvm.h"
2ff3de68 34#include "sysemu/sysemu.h"
1de7afc9
PB
35#include "qemu/timer.h"
36#include "qemu/config-file.h"
75a34036 37#include "qemu/error-report.h"
53a5960a 38#if defined(CONFIG_USER_ONLY)
a9c94277 39#include "qemu.h"
432d268c 40#else /* !CONFIG_USER_ONLY */
741da0d3
PB
41#include "hw/hw.h"
42#include "exec/memory.h"
df43d49c 43#include "exec/ioport.h"
741da0d3 44#include "sysemu/dma.h"
9c607668 45#include "sysemu/numa.h"
79ca7a1b 46#include "sysemu/hw_accel.h"
741da0d3 47#include "exec/address-spaces.h"
9c17d615 48#include "sysemu/xen-mapcache.h"
0ab8ed18 49#include "trace-root.h"
d3a5038c 50
e2fa71f5 51#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
e2fa71f5
DDAG
52#include <linux/falloc.h>
53#endif
54
53a5960a 55#endif
0dc3f44a 56#include "qemu/rcu_queue.h"
4840f10e 57#include "qemu/main-loop.h"
5b6dd868 58#include "translate-all.h"
7615936e 59#include "sysemu/replay.h"
0cac1b66 60
022c62cb 61#include "exec/memory-internal.h"
220c3ebd 62#include "exec/ram_addr.h"
508127e2 63#include "exec/log.h"
67d95c15 64
9dfeca7c
BR
65#include "migration/vmstate.h"
66
b35ba30f 67#include "qemu/range.h"
794e8f30
MT
68#ifndef _WIN32
69#include "qemu/mmap-alloc.h"
70#endif
b35ba30f 71
be9b23c4
PX
72#include "monitor/monitor.h"
73
db7b5426 74//#define DEBUG_SUBPAGE
1196be37 75
e2eef170 76#if !defined(CONFIG_USER_ONLY)
0dc3f44a
MD
77/* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
78 * are protected by the ramlist lock.
79 */
0d53d9fe 80RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
62152b8a
AK
81
82static MemoryRegion *system_memory;
309cb471 83static MemoryRegion *system_io;
62152b8a 84
f6790af6
AK
85AddressSpace address_space_io;
86AddressSpace address_space_memory;
2673a5da 87
0844e007 88MemoryRegion io_mem_rom, io_mem_notdirty;
acc9d80b 89static MemoryRegion io_mem_unassigned;
0e0df1e2 90
7bd4f430
PB
91/* RAM is pre-allocated and passed into qemu_ram_alloc_from_ptr */
92#define RAM_PREALLOC (1 << 0)
93
dbcb8981
PB
94/* RAM is mmap-ed with MAP_SHARED */
95#define RAM_SHARED (1 << 1)
96
62be4e3a
MT
97/* Only a portion of RAM (used_length) is actually used, and migrated.
98 * This used_length size can change across reboots.
99 */
100#define RAM_RESIZEABLE (1 << 2)
101
2ce16640
DDAG
102/* UFFDIO_ZEROPAGE is available on this RAMBlock to atomically
103 * zero the page and wake waiting processes.
104 * (Set during postcopy)
105 */
106#define RAM_UF_ZEROPAGE (1 << 3)
b895de50
CLG
107
108/* RAM can be migrated */
109#define RAM_MIGRATABLE (1 << 4)
e2eef170 110#endif
9fa3e853 111
20bccb82
PM
112#ifdef TARGET_PAGE_BITS_VARY
113int target_page_bits;
114bool target_page_bits_decided;
115#endif
116
bdc44640 117struct CPUTailQ cpus = QTAILQ_HEAD_INITIALIZER(cpus);
6a00d601
FB
118/* current CPU in the current thread. It is only valid inside
119 cpu_exec() */
f240eb6f 120__thread CPUState *current_cpu;
2e70f6ef 121/* 0 = Do not count executed instructions.
bf20dc07 122 1 = Precise instruction counting.
2e70f6ef 123 2 = Adaptive rate instruction counting. */
5708fc66 124int use_icount;
6a00d601 125
a0be0c58
YZ
126uintptr_t qemu_host_page_size;
127intptr_t qemu_host_page_mask;
a0be0c58 128
20bccb82
PM
129bool set_preferred_target_page_bits(int bits)
130{
131 /* The target page size is the lowest common denominator for all
132 * the CPUs in the system, so we can only make it smaller, never
133 * larger. And we can't make it smaller once we've committed to
134 * a particular size.
135 */
136#ifdef TARGET_PAGE_BITS_VARY
137 assert(bits >= TARGET_PAGE_BITS_MIN);
138 if (target_page_bits == 0 || target_page_bits > bits) {
139 if (target_page_bits_decided) {
140 return false;
141 }
142 target_page_bits = bits;
143 }
144#endif
145 return true;
146}
147
e2eef170 148#if !defined(CONFIG_USER_ONLY)
4346ae3e 149
20bccb82
PM
150static void finalize_target_page_bits(void)
151{
152#ifdef TARGET_PAGE_BITS_VARY
153 if (target_page_bits == 0) {
154 target_page_bits = TARGET_PAGE_BITS_MIN;
155 }
156 target_page_bits_decided = true;
157#endif
158}
159
1db8abb1
PB
160typedef struct PhysPageEntry PhysPageEntry;
161
162struct PhysPageEntry {
9736e55b 163 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
8b795765 164 uint32_t skip : 6;
9736e55b 165 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
8b795765 166 uint32_t ptr : 26;
1db8abb1
PB
167};
168
8b795765
MT
169#define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
170
03f49957 171/* Size of the L2 (and L3, etc) page tables. */
57271d63 172#define ADDR_SPACE_BITS 64
03f49957 173
026736ce 174#define P_L2_BITS 9
03f49957
PB
175#define P_L2_SIZE (1 << P_L2_BITS)
176
177#define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
178
179typedef PhysPageEntry Node[P_L2_SIZE];
0475d94f 180
53cb28cb 181typedef struct PhysPageMap {
79e2b9ae
PB
182 struct rcu_head rcu;
183
53cb28cb
MA
184 unsigned sections_nb;
185 unsigned sections_nb_alloc;
186 unsigned nodes_nb;
187 unsigned nodes_nb_alloc;
188 Node *nodes;
189 MemoryRegionSection *sections;
190} PhysPageMap;
191
1db8abb1 192struct AddressSpaceDispatch {
729633c2 193 MemoryRegionSection *mru_section;
1db8abb1
PB
194 /* This is a multi-level map on the physical address space.
195 * The bottom level has pointers to MemoryRegionSections.
196 */
197 PhysPageEntry phys_map;
53cb28cb 198 PhysPageMap map;
1db8abb1
PB
199};
200
90260c6c
JK
201#define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
202typedef struct subpage_t {
203 MemoryRegion iomem;
16620684 204 FlatView *fv;
90260c6c 205 hwaddr base;
2615fabd 206 uint16_t sub_section[];
90260c6c
JK
207} subpage_t;
208
b41aac4f
LPF
209#define PHYS_SECTION_UNASSIGNED 0
210#define PHYS_SECTION_NOTDIRTY 1
211#define PHYS_SECTION_ROM 2
212#define PHYS_SECTION_WATCH 3
5312bd8b 213
e2eef170 214static void io_mem_init(void);
62152b8a 215static void memory_map_init(void);
09daed84 216static void tcg_commit(MemoryListener *listener);
e2eef170 217
1ec9b909 218static MemoryRegion io_mem_watch;
32857f4d
PM
219
220/**
221 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
222 * @cpu: the CPU whose AddressSpace this is
223 * @as: the AddressSpace itself
224 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
225 * @tcg_as_listener: listener for tracking changes to the AddressSpace
226 */
227struct CPUAddressSpace {
228 CPUState *cpu;
229 AddressSpace *as;
230 struct AddressSpaceDispatch *memory_dispatch;
231 MemoryListener tcg_as_listener;
232};
233
8deaf12c
GH
234struct DirtyBitmapSnapshot {
235 ram_addr_t start;
236 ram_addr_t end;
237 unsigned long dirty[];
238};
239
6658ffb8 240#endif
fd6ce8f6 241
6d9a1304 242#if !defined(CONFIG_USER_ONLY)
d6f2ea22 243
53cb28cb 244static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
d6f2ea22 245{
101420b8 246 static unsigned alloc_hint = 16;
53cb28cb 247 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
101420b8 248 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, alloc_hint);
53cb28cb
MA
249 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, map->nodes_nb + nodes);
250 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
101420b8 251 alloc_hint = map->nodes_nb_alloc;
d6f2ea22 252 }
f7bf5461
AK
253}
254
db94604b 255static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
f7bf5461
AK
256{
257 unsigned i;
8b795765 258 uint32_t ret;
db94604b
PB
259 PhysPageEntry e;
260 PhysPageEntry *p;
f7bf5461 261
53cb28cb 262 ret = map->nodes_nb++;
db94604b 263 p = map->nodes[ret];
f7bf5461 264 assert(ret != PHYS_MAP_NODE_NIL);
53cb28cb 265 assert(ret != map->nodes_nb_alloc);
db94604b
PB
266
267 e.skip = leaf ? 0 : 1;
268 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
03f49957 269 for (i = 0; i < P_L2_SIZE; ++i) {
db94604b 270 memcpy(&p[i], &e, sizeof(e));
d6f2ea22 271 }
f7bf5461 272 return ret;
d6f2ea22
AK
273}
274
53cb28cb
MA
275static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
276 hwaddr *index, hwaddr *nb, uint16_t leaf,
2999097b 277 int level)
f7bf5461
AK
278{
279 PhysPageEntry *p;
03f49957 280 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
108c49b8 281
9736e55b 282 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
db94604b 283 lp->ptr = phys_map_node_alloc(map, level == 0);
92e873b9 284 }
db94604b 285 p = map->nodes[lp->ptr];
03f49957 286 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
f7bf5461 287
03f49957 288 while (*nb && lp < &p[P_L2_SIZE]) {
07f07b31 289 if ((*index & (step - 1)) == 0 && *nb >= step) {
9736e55b 290 lp->skip = 0;
c19e8800 291 lp->ptr = leaf;
07f07b31
AK
292 *index += step;
293 *nb -= step;
2999097b 294 } else {
53cb28cb 295 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
2999097b
AK
296 }
297 ++lp;
f7bf5461
AK
298 }
299}
300
ac1970fb 301static void phys_page_set(AddressSpaceDispatch *d,
a8170e5e 302 hwaddr index, hwaddr nb,
2999097b 303 uint16_t leaf)
f7bf5461 304{
2999097b 305 /* Wildly overreserve - it doesn't matter much. */
53cb28cb 306 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
5cd2c5b6 307
53cb28cb 308 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
92e873b9
FB
309}
310
b35ba30f
MT
311/* Compact a non leaf page entry. Simply detect that the entry has a single child,
312 * and update our entry so we can skip it and go directly to the destination.
313 */
efee678d 314static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
b35ba30f
MT
315{
316 unsigned valid_ptr = P_L2_SIZE;
317 int valid = 0;
318 PhysPageEntry *p;
319 int i;
320
321 if (lp->ptr == PHYS_MAP_NODE_NIL) {
322 return;
323 }
324
325 p = nodes[lp->ptr];
326 for (i = 0; i < P_L2_SIZE; i++) {
327 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
328 continue;
329 }
330
331 valid_ptr = i;
332 valid++;
333 if (p[i].skip) {
efee678d 334 phys_page_compact(&p[i], nodes);
b35ba30f
MT
335 }
336 }
337
338 /* We can only compress if there's only one child. */
339 if (valid != 1) {
340 return;
341 }
342
343 assert(valid_ptr < P_L2_SIZE);
344
345 /* Don't compress if it won't fit in the # of bits we have. */
346 if (lp->skip + p[valid_ptr].skip >= (1 << 3)) {
347 return;
348 }
349
350 lp->ptr = p[valid_ptr].ptr;
351 if (!p[valid_ptr].skip) {
352 /* If our only child is a leaf, make this a leaf. */
353 /* By design, we should have made this node a leaf to begin with so we
354 * should never reach here.
355 * But since it's so simple to handle this, let's do it just in case we
356 * change this rule.
357 */
358 lp->skip = 0;
359 } else {
360 lp->skip += p[valid_ptr].skip;
361 }
362}
363
8629d3fc 364void address_space_dispatch_compact(AddressSpaceDispatch *d)
b35ba30f 365{
b35ba30f 366 if (d->phys_map.skip) {
efee678d 367 phys_page_compact(&d->phys_map, d->map.nodes);
b35ba30f
MT
368 }
369}
370
29cb533d
FZ
371static inline bool section_covers_addr(const MemoryRegionSection *section,
372 hwaddr addr)
373{
374 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
375 * the section must cover the entire address space.
376 */
258dfaaa 377 return int128_gethi(section->size) ||
29cb533d 378 range_covers_byte(section->offset_within_address_space,
258dfaaa 379 int128_getlo(section->size), addr);
29cb533d
FZ
380}
381
003a0cf2 382static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
92e873b9 383{
003a0cf2
PX
384 PhysPageEntry lp = d->phys_map, *p;
385 Node *nodes = d->map.nodes;
386 MemoryRegionSection *sections = d->map.sections;
97115a8d 387 hwaddr index = addr >> TARGET_PAGE_BITS;
31ab2b4a 388 int i;
f1f6e3b8 389
9736e55b 390 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
c19e8800 391 if (lp.ptr == PHYS_MAP_NODE_NIL) {
9affd6fc 392 return &sections[PHYS_SECTION_UNASSIGNED];
31ab2b4a 393 }
9affd6fc 394 p = nodes[lp.ptr];
03f49957 395 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
5312bd8b 396 }
b35ba30f 397
29cb533d 398 if (section_covers_addr(&sections[lp.ptr], addr)) {
b35ba30f
MT
399 return &sections[lp.ptr];
400 } else {
401 return &sections[PHYS_SECTION_UNASSIGNED];
402 }
f3705d53
AK
403}
404
e5548617
BS
405bool memory_region_is_unassigned(MemoryRegion *mr)
406{
2a8e7499 407 return mr != &io_mem_rom && mr != &io_mem_notdirty && !mr->rom_device
5b6dd868 408 && mr != &io_mem_watch;
fd6ce8f6 409}
149f54b5 410
79e2b9ae 411/* Called from RCU critical section */
c7086b4a 412static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
90260c6c
JK
413 hwaddr addr,
414 bool resolve_subpage)
9f029603 415{
729633c2 416 MemoryRegionSection *section = atomic_read(&d->mru_section);
90260c6c
JK
417 subpage_t *subpage;
418
07c114bb
PB
419 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
420 !section_covers_addr(section, addr)) {
003a0cf2 421 section = phys_page_find(d, addr);
07c114bb 422 atomic_set(&d->mru_section, section);
729633c2 423 }
90260c6c
JK
424 if (resolve_subpage && section->mr->subpage) {
425 subpage = container_of(section->mr, subpage_t, iomem);
53cb28cb 426 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
90260c6c
JK
427 }
428 return section;
9f029603
JK
429}
430
79e2b9ae 431/* Called from RCU critical section */
90260c6c 432static MemoryRegionSection *
c7086b4a 433address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
90260c6c 434 hwaddr *plen, bool resolve_subpage)
149f54b5
PB
435{
436 MemoryRegionSection *section;
965eb2fc 437 MemoryRegion *mr;
a87f3954 438 Int128 diff;
149f54b5 439
c7086b4a 440 section = address_space_lookup_region(d, addr, resolve_subpage);
149f54b5
PB
441 /* Compute offset within MemoryRegionSection */
442 addr -= section->offset_within_address_space;
443
444 /* Compute offset within MemoryRegion */
445 *xlat = addr + section->offset_within_region;
446
965eb2fc 447 mr = section->mr;
b242e0e0
PB
448
449 /* MMIO registers can be expected to perform full-width accesses based only
450 * on their address, without considering adjacent registers that could
451 * decode to completely different MemoryRegions. When such registers
452 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
453 * regions overlap wildly. For this reason we cannot clamp the accesses
454 * here.
455 *
456 * If the length is small (as is the case for address_space_ldl/stl),
457 * everything works fine. If the incoming length is large, however,
458 * the caller really has to do the clamping through memory_access_size.
459 */
965eb2fc 460 if (memory_region_is_ram(mr)) {
e4a511f8 461 diff = int128_sub(section->size, int128_make64(addr));
965eb2fc
PB
462 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
463 }
149f54b5
PB
464 return section;
465}
90260c6c 466
a411c84b
PB
467/**
468 * address_space_translate_iommu - translate an address through an IOMMU
469 * memory region and then through the target address space.
470 *
471 * @iommu_mr: the IOMMU memory region that we start the translation from
472 * @addr: the address to be translated through the MMU
473 * @xlat: the translated address offset within the destination memory region.
474 * It cannot be %NULL.
475 * @plen_out: valid read/write length of the translated address. It
476 * cannot be %NULL.
477 * @page_mask_out: page mask for the translated address. This
478 * should only be meaningful for IOMMU translated
479 * addresses, since there may be huge pages that this bit
480 * would tell. It can be %NULL if we don't care about it.
481 * @is_write: whether the translation operation is for write
482 * @is_mmio: whether this can be MMIO, set true if it can
483 * @target_as: the address space targeted by the IOMMU
2f7b009c 484 * @attrs: transaction attributes
a411c84b
PB
485 *
486 * This function is called from RCU critical section. It is the common
487 * part of flatview_do_translate and address_space_translate_cached.
488 */
489static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
490 hwaddr *xlat,
491 hwaddr *plen_out,
492 hwaddr *page_mask_out,
493 bool is_write,
494 bool is_mmio,
2f7b009c
PM
495 AddressSpace **target_as,
496 MemTxAttrs attrs)
a411c84b
PB
497{
498 MemoryRegionSection *section;
499 hwaddr page_mask = (hwaddr)-1;
500
501 do {
502 hwaddr addr = *xlat;
503 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
504 IOMMUTLBEntry iotlb = imrc->translate(iommu_mr, addr, is_write ?
505 IOMMU_WO : IOMMU_RO);
506
507 if (!(iotlb.perm & (1 << is_write))) {
508 goto unassigned;
509 }
510
511 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
512 | (addr & iotlb.addr_mask));
513 page_mask &= iotlb.addr_mask;
514 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
515 *target_as = iotlb.target_as;
516
517 section = address_space_translate_internal(
518 address_space_to_dispatch(iotlb.target_as), addr, xlat,
519 plen_out, is_mmio);
520
521 iommu_mr = memory_region_get_iommu(section->mr);
522 } while (unlikely(iommu_mr));
523
524 if (page_mask_out) {
525 *page_mask_out = page_mask;
526 }
527 return *section;
528
529unassigned:
530 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
531}
532
d5e5fafd
PX
533/**
534 * flatview_do_translate - translate an address in FlatView
535 *
536 * @fv: the flat view that we want to translate on
537 * @addr: the address to be translated in above address space
538 * @xlat: the translated address offset within memory region. It
539 * cannot be @NULL.
540 * @plen_out: valid read/write length of the translated address. It
541 * can be @NULL when we don't care about it.
542 * @page_mask_out: page mask for the translated address. This
543 * should only be meaningful for IOMMU translated
544 * addresses, since there may be huge pages that this bit
545 * would tell. It can be @NULL if we don't care about it.
546 * @is_write: whether the translation operation is for write
547 * @is_mmio: whether this can be MMIO, set true if it can
ad2804d9 548 * @target_as: the address space targeted by the IOMMU
49e14aa8 549 * @attrs: memory transaction attributes
d5e5fafd
PX
550 *
551 * This function is called from RCU critical section
552 */
16620684
AK
553static MemoryRegionSection flatview_do_translate(FlatView *fv,
554 hwaddr addr,
555 hwaddr *xlat,
d5e5fafd
PX
556 hwaddr *plen_out,
557 hwaddr *page_mask_out,
16620684
AK
558 bool is_write,
559 bool is_mmio,
49e14aa8
PM
560 AddressSpace **target_as,
561 MemTxAttrs attrs)
052c8fa9 562{
052c8fa9 563 MemoryRegionSection *section;
3df9d748 564 IOMMUMemoryRegion *iommu_mr;
d5e5fafd
PX
565 hwaddr plen = (hwaddr)(-1);
566
ad2804d9
PB
567 if (!plen_out) {
568 plen_out = &plen;
d5e5fafd 569 }
052c8fa9 570
a411c84b
PB
571 section = address_space_translate_internal(
572 flatview_to_dispatch(fv), addr, xlat,
573 plen_out, is_mmio);
052c8fa9 574
a411c84b
PB
575 iommu_mr = memory_region_get_iommu(section->mr);
576 if (unlikely(iommu_mr)) {
577 return address_space_translate_iommu(iommu_mr, xlat,
578 plen_out, page_mask_out,
579 is_write, is_mmio,
2f7b009c 580 target_as, attrs);
052c8fa9 581 }
d5e5fafd 582 if (page_mask_out) {
a411c84b
PB
583 /* Not behind an IOMMU, use default page size. */
584 *page_mask_out = ~TARGET_PAGE_MASK;
d5e5fafd
PX
585 }
586
a764040c 587 return *section;
052c8fa9
JW
588}
589
590/* Called from RCU critical section */
a764040c 591IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
7446eb07 592 bool is_write, MemTxAttrs attrs)
90260c6c 593{
a764040c 594 MemoryRegionSection section;
076a93d7 595 hwaddr xlat, page_mask;
30951157 596
076a93d7
PX
597 /*
598 * This can never be MMIO, and we don't really care about plen,
599 * but page mask.
600 */
601 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
49e14aa8
PM
602 NULL, &page_mask, is_write, false, &as,
603 attrs);
30951157 604
a764040c
PX
605 /* Illegal translation */
606 if (section.mr == &io_mem_unassigned) {
607 goto iotlb_fail;
608 }
30951157 609
a764040c
PX
610 /* Convert memory region offset into address space offset */
611 xlat += section.offset_within_address_space -
612 section.offset_within_region;
613
a764040c 614 return (IOMMUTLBEntry) {
e76bb18f 615 .target_as = as,
076a93d7
PX
616 .iova = addr & ~page_mask,
617 .translated_addr = xlat & ~page_mask,
618 .addr_mask = page_mask,
a764040c
PX
619 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
620 .perm = IOMMU_RW,
621 };
622
623iotlb_fail:
624 return (IOMMUTLBEntry) {0};
625}
626
627/* Called from RCU critical section */
16620684 628MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
efa99a2f
PM
629 hwaddr *plen, bool is_write,
630 MemTxAttrs attrs)
a764040c
PX
631{
632 MemoryRegion *mr;
633 MemoryRegionSection section;
16620684 634 AddressSpace *as = NULL;
a764040c
PX
635
636 /* This can be MMIO, so setup MMIO bit. */
d5e5fafd 637 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
49e14aa8 638 is_write, true, &as, attrs);
a764040c
PX
639 mr = section.mr;
640
fe680d0d 641 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
a87f3954 642 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
23820dbf 643 *plen = MIN(page, *plen);
a87f3954
PB
644 }
645
30951157 646 return mr;
90260c6c
JK
647}
648
79e2b9ae 649/* Called from RCU critical section */
90260c6c 650MemoryRegionSection *
d7898cda 651address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
9d82b5a7 652 hwaddr *xlat, hwaddr *plen)
90260c6c 653{
30951157 654 MemoryRegionSection *section;
f35e44e7 655 AddressSpaceDispatch *d = atomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
d7898cda
PM
656
657 section = address_space_translate_internal(d, addr, xlat, plen, false);
30951157 658
3df9d748 659 assert(!memory_region_is_iommu(section->mr));
30951157 660 return section;
90260c6c 661}
5b6dd868 662#endif
fd6ce8f6 663
b170fce3 664#if !defined(CONFIG_USER_ONLY)
5b6dd868
BS
665
666static int cpu_common_post_load(void *opaque, int version_id)
fd6ce8f6 667{
259186a7 668 CPUState *cpu = opaque;
a513fe19 669
5b6dd868
BS
670 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
671 version_id is increased. */
259186a7 672 cpu->interrupt_request &= ~0x01;
d10eb08f 673 tlb_flush(cpu);
5b6dd868 674
15a356c4
PD
675 /* loadvm has just updated the content of RAM, bypassing the
676 * usual mechanisms that ensure we flush TBs for writes to
677 * memory we've translated code from. So we must flush all TBs,
678 * which will now be stale.
679 */
680 tb_flush(cpu);
681
5b6dd868 682 return 0;
a513fe19 683}
7501267e 684
6c3bff0e
PD
685static int cpu_common_pre_load(void *opaque)
686{
687 CPUState *cpu = opaque;
688
adee6424 689 cpu->exception_index = -1;
6c3bff0e
PD
690
691 return 0;
692}
693
694static bool cpu_common_exception_index_needed(void *opaque)
695{
696 CPUState *cpu = opaque;
697
adee6424 698 return tcg_enabled() && cpu->exception_index != -1;
6c3bff0e
PD
699}
700
701static const VMStateDescription vmstate_cpu_common_exception_index = {
702 .name = "cpu_common/exception_index",
703 .version_id = 1,
704 .minimum_version_id = 1,
5cd8cada 705 .needed = cpu_common_exception_index_needed,
6c3bff0e
PD
706 .fields = (VMStateField[]) {
707 VMSTATE_INT32(exception_index, CPUState),
708 VMSTATE_END_OF_LIST()
709 }
710};
711
bac05aa9
AS
712static bool cpu_common_crash_occurred_needed(void *opaque)
713{
714 CPUState *cpu = opaque;
715
716 return cpu->crash_occurred;
717}
718
719static const VMStateDescription vmstate_cpu_common_crash_occurred = {
720 .name = "cpu_common/crash_occurred",
721 .version_id = 1,
722 .minimum_version_id = 1,
723 .needed = cpu_common_crash_occurred_needed,
724 .fields = (VMStateField[]) {
725 VMSTATE_BOOL(crash_occurred, CPUState),
726 VMSTATE_END_OF_LIST()
727 }
728};
729
1a1562f5 730const VMStateDescription vmstate_cpu_common = {
5b6dd868
BS
731 .name = "cpu_common",
732 .version_id = 1,
733 .minimum_version_id = 1,
6c3bff0e 734 .pre_load = cpu_common_pre_load,
5b6dd868 735 .post_load = cpu_common_post_load,
35d08458 736 .fields = (VMStateField[]) {
259186a7
AF
737 VMSTATE_UINT32(halted, CPUState),
738 VMSTATE_UINT32(interrupt_request, CPUState),
5b6dd868 739 VMSTATE_END_OF_LIST()
6c3bff0e 740 },
5cd8cada
JQ
741 .subsections = (const VMStateDescription*[]) {
742 &vmstate_cpu_common_exception_index,
bac05aa9 743 &vmstate_cpu_common_crash_occurred,
5cd8cada 744 NULL
5b6dd868
BS
745 }
746};
1a1562f5 747
5b6dd868 748#endif
ea041c0e 749
38d8f5c8 750CPUState *qemu_get_cpu(int index)
ea041c0e 751{
bdc44640 752 CPUState *cpu;
ea041c0e 753
bdc44640 754 CPU_FOREACH(cpu) {
55e5c285 755 if (cpu->cpu_index == index) {
bdc44640 756 return cpu;
55e5c285 757 }
ea041c0e 758 }
5b6dd868 759
bdc44640 760 return NULL;
ea041c0e
FB
761}
762
09daed84 763#if !defined(CONFIG_USER_ONLY)
80ceb07a
PX
764void cpu_address_space_init(CPUState *cpu, int asidx,
765 const char *prefix, MemoryRegion *mr)
09daed84 766{
12ebc9a7 767 CPUAddressSpace *newas;
80ceb07a 768 AddressSpace *as = g_new0(AddressSpace, 1);
87a621d8 769 char *as_name;
80ceb07a
PX
770
771 assert(mr);
87a621d8
PX
772 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
773 address_space_init(as, mr, as_name);
774 g_free(as_name);
12ebc9a7
PM
775
776 /* Target code should have set num_ases before calling us */
777 assert(asidx < cpu->num_ases);
778
56943e8c
PM
779 if (asidx == 0) {
780 /* address space 0 gets the convenience alias */
781 cpu->as = as;
782 }
783
12ebc9a7
PM
784 /* KVM cannot currently support multiple address spaces. */
785 assert(asidx == 0 || !kvm_enabled());
09daed84 786
12ebc9a7
PM
787 if (!cpu->cpu_ases) {
788 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
09daed84 789 }
32857f4d 790
12ebc9a7
PM
791 newas = &cpu->cpu_ases[asidx];
792 newas->cpu = cpu;
793 newas->as = as;
56943e8c 794 if (tcg_enabled()) {
12ebc9a7
PM
795 newas->tcg_as_listener.commit = tcg_commit;
796 memory_listener_register(&newas->tcg_as_listener, as);
56943e8c 797 }
09daed84 798}
651a5bc0
PM
799
800AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
801{
802 /* Return the AddressSpace corresponding to the specified index */
803 return cpu->cpu_ases[asidx].as;
804}
09daed84
EI
805#endif
806
7bbc124e 807void cpu_exec_unrealizefn(CPUState *cpu)
1c59eb39 808{
9dfeca7c
BR
809 CPUClass *cc = CPU_GET_CLASS(cpu);
810
267f685b 811 cpu_list_remove(cpu);
9dfeca7c
BR
812
813 if (cc->vmsd != NULL) {
814 vmstate_unregister(NULL, cc->vmsd, cpu);
815 }
816 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
817 vmstate_unregister(NULL, &vmstate_cpu_common, cpu);
818 }
1c59eb39
BR
819}
820
c7e002c5
FZ
821Property cpu_common_props[] = {
822#ifndef CONFIG_USER_ONLY
823 /* Create a memory property for softmmu CPU object,
824 * so users can wire up its memory. (This can't go in qom/cpu.c
825 * because that file is compiled only once for both user-mode
826 * and system builds.) The default if no link is set up is to use
827 * the system address space.
828 */
829 DEFINE_PROP_LINK("memory", CPUState, memory, TYPE_MEMORY_REGION,
830 MemoryRegion *),
831#endif
832 DEFINE_PROP_END_OF_LIST(),
833};
834
39e329e3 835void cpu_exec_initfn(CPUState *cpu)
ea041c0e 836{
56943e8c 837 cpu->as = NULL;
12ebc9a7 838 cpu->num_ases = 0;
56943e8c 839
291135b5 840#ifndef CONFIG_USER_ONLY
291135b5 841 cpu->thread_id = qemu_get_thread_id();
6731d864
PC
842 cpu->memory = system_memory;
843 object_ref(OBJECT(cpu->memory));
291135b5 844#endif
39e329e3
LV
845}
846
ce5b1bbf 847void cpu_exec_realizefn(CPUState *cpu, Error **errp)
39e329e3 848{
55c3ceef 849 CPUClass *cc = CPU_GET_CLASS(cpu);
2dda6354 850 static bool tcg_target_initialized;
291135b5 851
267f685b 852 cpu_list_add(cpu);
1bc7e522 853
2dda6354
EC
854 if (tcg_enabled() && !tcg_target_initialized) {
855 tcg_target_initialized = true;
55c3ceef
RH
856 cc->tcg_initialize();
857 }
858
1bc7e522 859#ifndef CONFIG_USER_ONLY
e0d47944 860 if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
741da0d3 861 vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);
e0d47944 862 }
b170fce3 863 if (cc->vmsd != NULL) {
741da0d3 864 vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);
b170fce3 865 }
741da0d3 866#endif
ea041c0e
FB
867}
868
2278b939
IM
869const char *parse_cpu_model(const char *cpu_model)
870{
871 ObjectClass *oc;
872 CPUClass *cc;
873 gchar **model_pieces;
874 const char *cpu_type;
875
876 model_pieces = g_strsplit(cpu_model, ",", 2);
877
878 oc = cpu_class_by_name(CPU_RESOLVING_TYPE, model_pieces[0]);
879 if (oc == NULL) {
880 error_report("unable to find CPU model '%s'", model_pieces[0]);
881 g_strfreev(model_pieces);
882 exit(EXIT_FAILURE);
883 }
884
885 cpu_type = object_class_get_name(oc);
886 cc = CPU_CLASS(oc);
887 cc->parse_features(cpu_type, model_pieces[1], &error_fatal);
888 g_strfreev(model_pieces);
889 return cpu_type;
890}
891
406bc339 892#if defined(CONFIG_USER_ONLY)
00b941e5 893static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
1e7855a5 894{
406bc339
PK
895 mmap_lock();
896 tb_lock();
897 tb_invalidate_phys_page_range(pc, pc + 1, 0);
898 tb_unlock();
899 mmap_unlock();
900}
901#else
902static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
903{
904 MemTxAttrs attrs;
905 hwaddr phys = cpu_get_phys_page_attrs_debug(cpu, pc, &attrs);
906 int asidx = cpu_asidx_from_attrs(cpu, attrs);
907 if (phys != -1) {
908 /* Locks grabbed by tb_invalidate_phys_addr */
909 tb_invalidate_phys_addr(cpu->cpu_ases[asidx].as,
c874dc4f 910 phys | (pc & ~TARGET_PAGE_MASK), attrs);
406bc339 911 }
1e7855a5 912}
406bc339 913#endif
d720b93d 914
c527ee8f 915#if defined(CONFIG_USER_ONLY)
75a34036 916void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
c527ee8f
PB
917
918{
919}
920
3ee887e8
PM
921int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
922 int flags)
923{
924 return -ENOSYS;
925}
926
927void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
928{
929}
930
75a34036 931int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
c527ee8f
PB
932 int flags, CPUWatchpoint **watchpoint)
933{
934 return -ENOSYS;
935}
936#else
6658ffb8 937/* Add a watchpoint. */
75a34036 938int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
a1d1bb31 939 int flags, CPUWatchpoint **watchpoint)
6658ffb8 940{
c0ce998e 941 CPUWatchpoint *wp;
6658ffb8 942
05068c0d 943 /* forbid ranges which are empty or run off the end of the address space */
07e2863d 944 if (len == 0 || (addr + len - 1) < addr) {
75a34036
AF
945 error_report("tried to set invalid watchpoint at %"
946 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
b4051334
AL
947 return -EINVAL;
948 }
7267c094 949 wp = g_malloc(sizeof(*wp));
a1d1bb31
AL
950
951 wp->vaddr = addr;
05068c0d 952 wp->len = len;
a1d1bb31
AL
953 wp->flags = flags;
954
2dc9f411 955 /* keep all GDB-injected watchpoints in front */
ff4700b0
AF
956 if (flags & BP_GDB) {
957 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
958 } else {
959 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
960 }
6658ffb8 961
31b030d4 962 tlb_flush_page(cpu, addr);
a1d1bb31
AL
963
964 if (watchpoint)
965 *watchpoint = wp;
966 return 0;
6658ffb8
PB
967}
968
a1d1bb31 969/* Remove a specific watchpoint. */
75a34036 970int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
a1d1bb31 971 int flags)
6658ffb8 972{
a1d1bb31 973 CPUWatchpoint *wp;
6658ffb8 974
ff4700b0 975 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
05068c0d 976 if (addr == wp->vaddr && len == wp->len
6e140f28 977 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
75a34036 978 cpu_watchpoint_remove_by_ref(cpu, wp);
6658ffb8
PB
979 return 0;
980 }
981 }
a1d1bb31 982 return -ENOENT;
6658ffb8
PB
983}
984
a1d1bb31 985/* Remove a specific watchpoint by reference. */
75a34036 986void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
a1d1bb31 987{
ff4700b0 988 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
7d03f82f 989
31b030d4 990 tlb_flush_page(cpu, watchpoint->vaddr);
a1d1bb31 991
7267c094 992 g_free(watchpoint);
a1d1bb31
AL
993}
994
995/* Remove all matching watchpoints. */
75a34036 996void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
a1d1bb31 997{
c0ce998e 998 CPUWatchpoint *wp, *next;
a1d1bb31 999
ff4700b0 1000 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
75a34036
AF
1001 if (wp->flags & mask) {
1002 cpu_watchpoint_remove_by_ref(cpu, wp);
1003 }
c0ce998e 1004 }
7d03f82f 1005}
05068c0d
PM
1006
1007/* Return true if this watchpoint address matches the specified
1008 * access (ie the address range covered by the watchpoint overlaps
1009 * partially or completely with the address range covered by the
1010 * access).
1011 */
1012static inline bool cpu_watchpoint_address_matches(CPUWatchpoint *wp,
1013 vaddr addr,
1014 vaddr len)
1015{
1016 /* We know the lengths are non-zero, but a little caution is
1017 * required to avoid errors in the case where the range ends
1018 * exactly at the top of the address space and so addr + len
1019 * wraps round to zero.
1020 */
1021 vaddr wpend = wp->vaddr + wp->len - 1;
1022 vaddr addrend = addr + len - 1;
1023
1024 return !(addr > wpend || wp->vaddr > addrend);
1025}
1026
c527ee8f 1027#endif
7d03f82f 1028
a1d1bb31 1029/* Add a breakpoint. */
b3310ab3 1030int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags,
a1d1bb31 1031 CPUBreakpoint **breakpoint)
4c3a88a2 1032{
c0ce998e 1033 CPUBreakpoint *bp;
3b46e624 1034
7267c094 1035 bp = g_malloc(sizeof(*bp));
4c3a88a2 1036
a1d1bb31
AL
1037 bp->pc = pc;
1038 bp->flags = flags;
1039
2dc9f411 1040 /* keep all GDB-injected breakpoints in front */
00b941e5 1041 if (flags & BP_GDB) {
f0c3c505 1042 QTAILQ_INSERT_HEAD(&cpu->breakpoints, bp, entry);
00b941e5 1043 } else {
f0c3c505 1044 QTAILQ_INSERT_TAIL(&cpu->breakpoints, bp, entry);
00b941e5 1045 }
3b46e624 1046
f0c3c505 1047 breakpoint_invalidate(cpu, pc);
a1d1bb31 1048
00b941e5 1049 if (breakpoint) {
a1d1bb31 1050 *breakpoint = bp;
00b941e5 1051 }
4c3a88a2 1052 return 0;
4c3a88a2
FB
1053}
1054
a1d1bb31 1055/* Remove a specific breakpoint. */
b3310ab3 1056int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)
a1d1bb31 1057{
a1d1bb31
AL
1058 CPUBreakpoint *bp;
1059
f0c3c505 1060 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
a1d1bb31 1061 if (bp->pc == pc && bp->flags == flags) {
b3310ab3 1062 cpu_breakpoint_remove_by_ref(cpu, bp);
a1d1bb31
AL
1063 return 0;
1064 }
7d03f82f 1065 }
a1d1bb31 1066 return -ENOENT;
7d03f82f
EI
1067}
1068
a1d1bb31 1069/* Remove a specific breakpoint by reference. */
b3310ab3 1070void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)
4c3a88a2 1071{
f0c3c505
AF
1072 QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);
1073
1074 breakpoint_invalidate(cpu, breakpoint->pc);
a1d1bb31 1075
7267c094 1076 g_free(breakpoint);
a1d1bb31
AL
1077}
1078
1079/* Remove all matching breakpoints. */
b3310ab3 1080void cpu_breakpoint_remove_all(CPUState *cpu, int mask)
a1d1bb31 1081{
c0ce998e 1082 CPUBreakpoint *bp, *next;
a1d1bb31 1083
f0c3c505 1084 QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {
b3310ab3
AF
1085 if (bp->flags & mask) {
1086 cpu_breakpoint_remove_by_ref(cpu, bp);
1087 }
c0ce998e 1088 }
4c3a88a2
FB
1089}
1090
c33a346e
FB
1091/* enable or disable single step mode. EXCP_DEBUG is returned by the
1092 CPU loop after each instruction */
3825b28f 1093void cpu_single_step(CPUState *cpu, int enabled)
c33a346e 1094{
ed2803da
AF
1095 if (cpu->singlestep_enabled != enabled) {
1096 cpu->singlestep_enabled = enabled;
1097 if (kvm_enabled()) {
38e478ec 1098 kvm_update_guest_debug(cpu, 0);
ed2803da 1099 } else {
ccbb4d44 1100 /* must flush all the translated code to avoid inconsistencies */
e22a25c9 1101 /* XXX: only flush what is necessary */
bbd77c18 1102 tb_flush(cpu);
e22a25c9 1103 }
c33a346e 1104 }
c33a346e
FB
1105}
1106
a47dddd7 1107void cpu_abort(CPUState *cpu, const char *fmt, ...)
7501267e
FB
1108{
1109 va_list ap;
493ae1f0 1110 va_list ap2;
7501267e
FB
1111
1112 va_start(ap, fmt);
493ae1f0 1113 va_copy(ap2, ap);
7501267e
FB
1114 fprintf(stderr, "qemu: fatal: ");
1115 vfprintf(stderr, fmt, ap);
1116 fprintf(stderr, "\n");
878096ee 1117 cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU | CPU_DUMP_CCOP);
013a2942 1118 if (qemu_log_separate()) {
1ee73216 1119 qemu_log_lock();
93fcfe39
AL
1120 qemu_log("qemu: fatal: ");
1121 qemu_log_vprintf(fmt, ap2);
1122 qemu_log("\n");
a0762859 1123 log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
31b1a7b4 1124 qemu_log_flush();
1ee73216 1125 qemu_log_unlock();
93fcfe39 1126 qemu_log_close();
924edcae 1127 }
493ae1f0 1128 va_end(ap2);
f9373291 1129 va_end(ap);
7615936e 1130 replay_finish();
fd052bf6
RV
1131#if defined(CONFIG_USER_ONLY)
1132 {
1133 struct sigaction act;
1134 sigfillset(&act.sa_mask);
1135 act.sa_handler = SIG_DFL;
8347c185 1136 act.sa_flags = 0;
fd052bf6
RV
1137 sigaction(SIGABRT, &act, NULL);
1138 }
1139#endif
7501267e
FB
1140 abort();
1141}
1142
0124311e 1143#if !defined(CONFIG_USER_ONLY)
0dc3f44a 1144/* Called from RCU critical section */
041603fe
PB
1145static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
1146{
1147 RAMBlock *block;
1148
43771539 1149 block = atomic_rcu_read(&ram_list.mru_block);
9b8424d5 1150 if (block && addr - block->offset < block->max_length) {
68851b98 1151 return block;
041603fe 1152 }
99e15582 1153 RAMBLOCK_FOREACH(block) {
9b8424d5 1154 if (addr - block->offset < block->max_length) {
041603fe
PB
1155 goto found;
1156 }
1157 }
1158
1159 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1160 abort();
1161
1162found:
43771539
PB
1163 /* It is safe to write mru_block outside the iothread lock. This
1164 * is what happens:
1165 *
1166 * mru_block = xxx
1167 * rcu_read_unlock()
1168 * xxx removed from list
1169 * rcu_read_lock()
1170 * read mru_block
1171 * mru_block = NULL;
1172 * call_rcu(reclaim_ramblock, xxx);
1173 * rcu_read_unlock()
1174 *
1175 * atomic_rcu_set is not needed here. The block was already published
1176 * when it was placed into the list. Here we're just making an extra
1177 * copy of the pointer.
1178 */
041603fe
PB
1179 ram_list.mru_block = block;
1180 return block;
1181}
1182
a2f4d5be 1183static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
d24981d3 1184{
9a13565d 1185 CPUState *cpu;
041603fe 1186 ram_addr_t start1;
a2f4d5be
JQ
1187 RAMBlock *block;
1188 ram_addr_t end;
1189
1190 end = TARGET_PAGE_ALIGN(start + length);
1191 start &= TARGET_PAGE_MASK;
d24981d3 1192
0dc3f44a 1193 rcu_read_lock();
041603fe
PB
1194 block = qemu_get_ram_block(start);
1195 assert(block == qemu_get_ram_block(end - 1));
1240be24 1196 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
9a13565d
PC
1197 CPU_FOREACH(cpu) {
1198 tlb_reset_dirty(cpu, start1, length);
1199 }
0dc3f44a 1200 rcu_read_unlock();
d24981d3
JQ
1201}
1202
5579c7f3 1203/* Note: start and end must be within the same ram block. */
03eebc9e
SH
1204bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1205 ram_addr_t length,
1206 unsigned client)
1ccde1cb 1207{
5b82b703 1208 DirtyMemoryBlocks *blocks;
03eebc9e 1209 unsigned long end, page;
5b82b703 1210 bool dirty = false;
03eebc9e
SH
1211
1212 if (length == 0) {
1213 return false;
1214 }
f23db169 1215
03eebc9e
SH
1216 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1217 page = start >> TARGET_PAGE_BITS;
5b82b703
SH
1218
1219 rcu_read_lock();
1220
1221 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1222
1223 while (page < end) {
1224 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1225 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1226 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1227
1228 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1229 offset, num);
1230 page += num;
1231 }
1232
1233 rcu_read_unlock();
03eebc9e
SH
1234
1235 if (dirty && tcg_enabled()) {
a2f4d5be 1236 tlb_reset_dirty_range_all(start, length);
5579c7f3 1237 }
03eebc9e
SH
1238
1239 return dirty;
1ccde1cb
FB
1240}
1241
8deaf12c
GH
1242DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1243 (ram_addr_t start, ram_addr_t length, unsigned client)
1244{
1245 DirtyMemoryBlocks *blocks;
1246 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1247 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1248 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1249 DirtyBitmapSnapshot *snap;
1250 unsigned long page, end, dest;
1251
1252 snap = g_malloc0(sizeof(*snap) +
1253 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1254 snap->start = first;
1255 snap->end = last;
1256
1257 page = first >> TARGET_PAGE_BITS;
1258 end = last >> TARGET_PAGE_BITS;
1259 dest = 0;
1260
1261 rcu_read_lock();
1262
1263 blocks = atomic_rcu_read(&ram_list.dirty_memory[client]);
1264
1265 while (page < end) {
1266 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1267 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1268 unsigned long num = MIN(end - page, DIRTY_MEMORY_BLOCK_SIZE - offset);
1269
1270 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1271 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1272 offset >>= BITS_PER_LEVEL;
1273
1274 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1275 blocks->blocks[idx] + offset,
1276 num);
1277 page += num;
1278 dest += num >> BITS_PER_LEVEL;
1279 }
1280
1281 rcu_read_unlock();
1282
1283 if (tcg_enabled()) {
1284 tlb_reset_dirty_range_all(start, length);
1285 }
1286
1287 return snap;
1288}
1289
1290bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1291 ram_addr_t start,
1292 ram_addr_t length)
1293{
1294 unsigned long page, end;
1295
1296 assert(start >= snap->start);
1297 assert(start + length <= snap->end);
1298
1299 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1300 page = (start - snap->start) >> TARGET_PAGE_BITS;
1301
1302 while (page < end) {
1303 if (test_bit(page, snap->dirty)) {
1304 return true;
1305 }
1306 page++;
1307 }
1308 return false;
1309}
1310
79e2b9ae 1311/* Called from RCU critical section */
bb0e627a 1312hwaddr memory_region_section_get_iotlb(CPUState *cpu,
149f54b5
PB
1313 MemoryRegionSection *section,
1314 target_ulong vaddr,
1315 hwaddr paddr, hwaddr xlat,
1316 int prot,
1317 target_ulong *address)
e5548617 1318{
a8170e5e 1319 hwaddr iotlb;
e5548617
BS
1320 CPUWatchpoint *wp;
1321
cc5bea60 1322 if (memory_region_is_ram(section->mr)) {
e5548617 1323 /* Normal RAM. */
e4e69794 1324 iotlb = memory_region_get_ram_addr(section->mr) + xlat;
e5548617 1325 if (!section->readonly) {
b41aac4f 1326 iotlb |= PHYS_SECTION_NOTDIRTY;
e5548617 1327 } else {
b41aac4f 1328 iotlb |= PHYS_SECTION_ROM;
e5548617
BS
1329 }
1330 } else {
0b8e2c10
PM
1331 AddressSpaceDispatch *d;
1332
16620684 1333 d = flatview_to_dispatch(section->fv);
0b8e2c10 1334 iotlb = section - d->map.sections;
149f54b5 1335 iotlb += xlat;
e5548617
BS
1336 }
1337
1338 /* Make accesses to pages with watchpoints go via the
1339 watchpoint trap routines. */
ff4700b0 1340 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
05068c0d 1341 if (cpu_watchpoint_address_matches(wp, vaddr, TARGET_PAGE_SIZE)) {
e5548617
BS
1342 /* Avoid trapping reads of pages with a write breakpoint. */
1343 if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
b41aac4f 1344 iotlb = PHYS_SECTION_WATCH + paddr;
e5548617
BS
1345 *address |= TLB_MMIO;
1346 break;
1347 }
1348 }
1349 }
1350
1351 return iotlb;
1352}
9fa3e853
FB
1353#endif /* defined(CONFIG_USER_ONLY) */
1354
e2eef170 1355#if !defined(CONFIG_USER_ONLY)
8da3ff18 1356
c227f099 1357static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
5312bd8b 1358 uint16_t section);
16620684 1359static subpage_t *subpage_init(FlatView *fv, hwaddr base);
54688b1e 1360
06329cce 1361static void *(*phys_mem_alloc)(size_t size, uint64_t *align, bool shared) =
a2b257d6 1362 qemu_anon_ram_alloc;
91138037
MA
1363
1364/*
1365 * Set a custom physical guest memory alloator.
1366 * Accelerators with unusual needs may need this. Hopefully, we can
1367 * get rid of it eventually.
1368 */
06329cce 1369void phys_mem_set_alloc(void *(*alloc)(size_t, uint64_t *align, bool shared))
91138037
MA
1370{
1371 phys_mem_alloc = alloc;
1372}
1373
53cb28cb
MA
1374static uint16_t phys_section_add(PhysPageMap *map,
1375 MemoryRegionSection *section)
5312bd8b 1376{
68f3f65b
PB
1377 /* The physical section number is ORed with a page-aligned
1378 * pointer to produce the iotlb entries. Thus it should
1379 * never overflow into the page-aligned value.
1380 */
53cb28cb 1381 assert(map->sections_nb < TARGET_PAGE_SIZE);
68f3f65b 1382
53cb28cb
MA
1383 if (map->sections_nb == map->sections_nb_alloc) {
1384 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1385 map->sections = g_renew(MemoryRegionSection, map->sections,
1386 map->sections_nb_alloc);
5312bd8b 1387 }
53cb28cb 1388 map->sections[map->sections_nb] = *section;
dfde4e6e 1389 memory_region_ref(section->mr);
53cb28cb 1390 return map->sections_nb++;
5312bd8b
AK
1391}
1392
058bc4b5
PB
1393static void phys_section_destroy(MemoryRegion *mr)
1394{
55b4e80b
DS
1395 bool have_sub_page = mr->subpage;
1396
dfde4e6e
PB
1397 memory_region_unref(mr);
1398
55b4e80b 1399 if (have_sub_page) {
058bc4b5 1400 subpage_t *subpage = container_of(mr, subpage_t, iomem);
b4fefef9 1401 object_unref(OBJECT(&subpage->iomem));
058bc4b5
PB
1402 g_free(subpage);
1403 }
1404}
1405
6092666e 1406static void phys_sections_free(PhysPageMap *map)
5312bd8b 1407{
9affd6fc
PB
1408 while (map->sections_nb > 0) {
1409 MemoryRegionSection *section = &map->sections[--map->sections_nb];
058bc4b5
PB
1410 phys_section_destroy(section->mr);
1411 }
9affd6fc
PB
1412 g_free(map->sections);
1413 g_free(map->nodes);
5312bd8b
AK
1414}
1415
9950322a 1416static void register_subpage(FlatView *fv, MemoryRegionSection *section)
0f0cb164 1417{
9950322a 1418 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
0f0cb164 1419 subpage_t *subpage;
a8170e5e 1420 hwaddr base = section->offset_within_address_space
0f0cb164 1421 & TARGET_PAGE_MASK;
003a0cf2 1422 MemoryRegionSection *existing = phys_page_find(d, base);
0f0cb164
AK
1423 MemoryRegionSection subsection = {
1424 .offset_within_address_space = base,
052e87b0 1425 .size = int128_make64(TARGET_PAGE_SIZE),
0f0cb164 1426 };
a8170e5e 1427 hwaddr start, end;
0f0cb164 1428
f3705d53 1429 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
0f0cb164 1430
f3705d53 1431 if (!(existing->mr->subpage)) {
16620684
AK
1432 subpage = subpage_init(fv, base);
1433 subsection.fv = fv;
0f0cb164 1434 subsection.mr = &subpage->iomem;
ac1970fb 1435 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
53cb28cb 1436 phys_section_add(&d->map, &subsection));
0f0cb164 1437 } else {
f3705d53 1438 subpage = container_of(existing->mr, subpage_t, iomem);
0f0cb164
AK
1439 }
1440 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
052e87b0 1441 end = start + int128_get64(section->size) - 1;
53cb28cb
MA
1442 subpage_register(subpage, start, end,
1443 phys_section_add(&d->map, section));
0f0cb164
AK
1444}
1445
1446
9950322a 1447static void register_multipage(FlatView *fv,
052e87b0 1448 MemoryRegionSection *section)
33417e70 1449{
9950322a 1450 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
a8170e5e 1451 hwaddr start_addr = section->offset_within_address_space;
53cb28cb 1452 uint16_t section_index = phys_section_add(&d->map, section);
052e87b0
PB
1453 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1454 TARGET_PAGE_BITS));
dd81124b 1455
733d5ef5
PB
1456 assert(num_pages);
1457 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
33417e70
FB
1458}
1459
8629d3fc 1460void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
0f0cb164 1461{
99b9cc06 1462 MemoryRegionSection now = *section, remain = *section;
052e87b0 1463 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
0f0cb164 1464
733d5ef5
PB
1465 if (now.offset_within_address_space & ~TARGET_PAGE_MASK) {
1466 uint64_t left = TARGET_PAGE_ALIGN(now.offset_within_address_space)
1467 - now.offset_within_address_space;
1468
052e87b0 1469 now.size = int128_min(int128_make64(left), now.size);
9950322a 1470 register_subpage(fv, &now);
733d5ef5 1471 } else {
052e87b0 1472 now.size = int128_zero();
733d5ef5 1473 }
052e87b0
PB
1474 while (int128_ne(remain.size, now.size)) {
1475 remain.size = int128_sub(remain.size, now.size);
1476 remain.offset_within_address_space += int128_get64(now.size);
1477 remain.offset_within_region += int128_get64(now.size);
69b67646 1478 now = remain;
052e87b0 1479 if (int128_lt(remain.size, page_size)) {
9950322a 1480 register_subpage(fv, &now);
88266249 1481 } else if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
052e87b0 1482 now.size = page_size;
9950322a 1483 register_subpage(fv, &now);
69b67646 1484 } else {
052e87b0 1485 now.size = int128_and(now.size, int128_neg(page_size));
9950322a 1486 register_multipage(fv, &now);
69b67646 1487 }
0f0cb164
AK
1488 }
1489}
1490
62a2744c
SY
1491void qemu_flush_coalesced_mmio_buffer(void)
1492{
1493 if (kvm_enabled())
1494 kvm_flush_coalesced_mmio_buffer();
1495}
1496
b2a8658e
UD
1497void qemu_mutex_lock_ramlist(void)
1498{
1499 qemu_mutex_lock(&ram_list.mutex);
1500}
1501
1502void qemu_mutex_unlock_ramlist(void)
1503{
1504 qemu_mutex_unlock(&ram_list.mutex);
1505}
1506
be9b23c4
PX
1507void ram_block_dump(Monitor *mon)
1508{
1509 RAMBlock *block;
1510 char *psize;
1511
1512 rcu_read_lock();
1513 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1514 "Block Name", "PSize", "Offset", "Used", "Total");
1515 RAMBLOCK_FOREACH(block) {
1516 psize = size_to_str(block->page_size);
1517 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1518 " 0x%016" PRIx64 "\n", block->idstr, psize,
1519 (uint64_t)block->offset,
1520 (uint64_t)block->used_length,
1521 (uint64_t)block->max_length);
1522 g_free(psize);
1523 }
1524 rcu_read_unlock();
1525}
1526
9c607668
AK
1527#ifdef __linux__
1528/*
1529 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1530 * may or may not name the same files / on the same filesystem now as
1531 * when we actually open and map them. Iterate over the file
1532 * descriptors instead, and use qemu_fd_getpagesize().
1533 */
1534static int find_max_supported_pagesize(Object *obj, void *opaque)
1535{
9c607668
AK
1536 long *hpsize_min = opaque;
1537
1538 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
2b108085
DG
1539 long hpsize = host_memory_backend_pagesize(MEMORY_BACKEND(obj));
1540
0de6e2a3
DG
1541 if (hpsize < *hpsize_min) {
1542 *hpsize_min = hpsize;
9c607668
AK
1543 }
1544 }
1545
1546 return 0;
1547}
1548
1549long qemu_getrampagesize(void)
1550{
1551 long hpsize = LONG_MAX;
1552 long mainrampagesize;
1553 Object *memdev_root;
1554
0de6e2a3 1555 mainrampagesize = qemu_mempath_getpagesize(mem_path);
9c607668
AK
1556
1557 /* it's possible we have memory-backend objects with
1558 * hugepage-backed RAM. these may get mapped into system
1559 * address space via -numa parameters or memory hotplug
1560 * hooks. we want to take these into account, but we
1561 * also want to make sure these supported hugepage
1562 * sizes are applicable across the entire range of memory
1563 * we may boot from, so we take the min across all
1564 * backends, and assume normal pages in cases where a
1565 * backend isn't backed by hugepages.
1566 */
1567 memdev_root = object_resolve_path("/objects", NULL);
1568 if (memdev_root) {
1569 object_child_foreach(memdev_root, find_max_supported_pagesize, &hpsize);
1570 }
1571 if (hpsize == LONG_MAX) {
1572 /* No additional memory regions found ==> Report main RAM page size */
1573 return mainrampagesize;
1574 }
1575
1576 /* If NUMA is disabled or the NUMA nodes are not backed with a
1577 * memory-backend, then there is at least one node using "normal" RAM,
1578 * so if its page size is smaller we have got to report that size instead.
1579 */
1580 if (hpsize > mainrampagesize &&
1581 (nb_numa_nodes == 0 || numa_info[0].node_memdev == NULL)) {
1582 static bool warned;
1583 if (!warned) {
1584 error_report("Huge page support disabled (n/a for main memory).");
1585 warned = true;
1586 }
1587 return mainrampagesize;
1588 }
1589
1590 return hpsize;
1591}
1592#else
1593long qemu_getrampagesize(void)
1594{
1595 return getpagesize();
1596}
1597#endif
1598
e1e84ba0 1599#ifdef __linux__
d6af99c9
HZ
1600static int64_t get_file_size(int fd)
1601{
1602 int64_t size = lseek(fd, 0, SEEK_END);
1603 if (size < 0) {
1604 return -errno;
1605 }
1606 return size;
1607}
1608
8d37b030
MAL
1609static int file_ram_open(const char *path,
1610 const char *region_name,
1611 bool *created,
1612 Error **errp)
c902760f
MT
1613{
1614 char *filename;
8ca761f6
PF
1615 char *sanitized_name;
1616 char *c;
5c3ece79 1617 int fd = -1;
c902760f 1618
8d37b030 1619 *created = false;
fd97fd44
MA
1620 for (;;) {
1621 fd = open(path, O_RDWR);
1622 if (fd >= 0) {
1623 /* @path names an existing file, use it */
1624 break;
8d31d6b6 1625 }
fd97fd44
MA
1626 if (errno == ENOENT) {
1627 /* @path names a file that doesn't exist, create it */
1628 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1629 if (fd >= 0) {
8d37b030 1630 *created = true;
fd97fd44
MA
1631 break;
1632 }
1633 } else if (errno == EISDIR) {
1634 /* @path names a directory, create a file there */
1635 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
8d37b030 1636 sanitized_name = g_strdup(region_name);
fd97fd44
MA
1637 for (c = sanitized_name; *c != '\0'; c++) {
1638 if (*c == '/') {
1639 *c = '_';
1640 }
1641 }
8ca761f6 1642
fd97fd44
MA
1643 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1644 sanitized_name);
1645 g_free(sanitized_name);
8d31d6b6 1646
fd97fd44
MA
1647 fd = mkstemp(filename);
1648 if (fd >= 0) {
1649 unlink(filename);
1650 g_free(filename);
1651 break;
1652 }
1653 g_free(filename);
8d31d6b6 1654 }
fd97fd44
MA
1655 if (errno != EEXIST && errno != EINTR) {
1656 error_setg_errno(errp, errno,
1657 "can't open backing store %s for guest RAM",
1658 path);
8d37b030 1659 return -1;
fd97fd44
MA
1660 }
1661 /*
1662 * Try again on EINTR and EEXIST. The latter happens when
1663 * something else creates the file between our two open().
1664 */
8d31d6b6 1665 }
c902760f 1666
8d37b030
MAL
1667 return fd;
1668}
1669
1670static void *file_ram_alloc(RAMBlock *block,
1671 ram_addr_t memory,
1672 int fd,
1673 bool truncate,
1674 Error **errp)
1675{
1676 void *area;
1677
863e9621 1678 block->page_size = qemu_fd_getpagesize(fd);
98376843
HZ
1679 if (block->mr->align % block->page_size) {
1680 error_setg(errp, "alignment 0x%" PRIx64
1681 " must be multiples of page size 0x%zx",
1682 block->mr->align, block->page_size);
1683 return NULL;
1684 }
1685 block->mr->align = MAX(block->page_size, block->mr->align);
8360668e
HZ
1686#if defined(__s390x__)
1687 if (kvm_enabled()) {
1688 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1689 }
1690#endif
fd97fd44 1691
863e9621 1692 if (memory < block->page_size) {
fd97fd44 1693 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
863e9621
DDAG
1694 "or larger than page size 0x%zx",
1695 memory, block->page_size);
8d37b030 1696 return NULL;
1775f111
HZ
1697 }
1698
863e9621 1699 memory = ROUND_UP(memory, block->page_size);
c902760f
MT
1700
1701 /*
1702 * ftruncate is not supported by hugetlbfs in older
1703 * hosts, so don't bother bailing out on errors.
1704 * If anything goes wrong with it under other filesystems,
1705 * mmap will fail.
d6af99c9
HZ
1706 *
1707 * Do not truncate the non-empty backend file to avoid corrupting
1708 * the existing data in the file. Disabling shrinking is not
1709 * enough. For example, the current vNVDIMM implementation stores
1710 * the guest NVDIMM labels at the end of the backend file. If the
1711 * backend file is later extended, QEMU will not be able to find
1712 * those labels. Therefore, extending the non-empty backend file
1713 * is disabled as well.
c902760f 1714 */
8d37b030 1715 if (truncate && ftruncate(fd, memory)) {
9742bf26 1716 perror("ftruncate");
7f56e740 1717 }
c902760f 1718
d2f39add
DD
1719 area = qemu_ram_mmap(fd, memory, block->mr->align,
1720 block->flags & RAM_SHARED);
c902760f 1721 if (area == MAP_FAILED) {
7f56e740 1722 error_setg_errno(errp, errno,
fd97fd44 1723 "unable to map backing store for guest RAM");
8d37b030 1724 return NULL;
c902760f 1725 }
ef36fa14
MT
1726
1727 if (mem_prealloc) {
1e356fc1 1728 os_mem_prealloc(fd, area, memory, smp_cpus, errp);
056b68af 1729 if (errp && *errp) {
8d37b030
MAL
1730 qemu_ram_munmap(area, memory);
1731 return NULL;
056b68af 1732 }
ef36fa14
MT
1733 }
1734
04b16653 1735 block->fd = fd;
c902760f
MT
1736 return area;
1737}
1738#endif
1739
154cc9ea
DDAG
1740/* Allocate space within the ram_addr_t space that governs the
1741 * dirty bitmaps.
1742 * Called with the ramlist lock held.
1743 */
d17b5288 1744static ram_addr_t find_ram_offset(ram_addr_t size)
04b16653
AW
1745{
1746 RAMBlock *block, *next_block;
3e837b2c 1747 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
04b16653 1748
49cd9ac6
SH
1749 assert(size != 0); /* it would hand out same offset multiple times */
1750
0dc3f44a 1751 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
04b16653 1752 return 0;
0d53d9fe 1753 }
04b16653 1754
99e15582 1755 RAMBLOCK_FOREACH(block) {
154cc9ea 1756 ram_addr_t candidate, next = RAM_ADDR_MAX;
04b16653 1757
801110ab
DDAG
1758 /* Align blocks to start on a 'long' in the bitmap
1759 * which makes the bitmap sync'ing take the fast path.
1760 */
154cc9ea 1761 candidate = block->offset + block->max_length;
801110ab 1762 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
04b16653 1763
154cc9ea
DDAG
1764 /* Search for the closest following block
1765 * and find the gap.
1766 */
99e15582 1767 RAMBLOCK_FOREACH(next_block) {
154cc9ea 1768 if (next_block->offset >= candidate) {
04b16653
AW
1769 next = MIN(next, next_block->offset);
1770 }
1771 }
154cc9ea
DDAG
1772
1773 /* If it fits remember our place and remember the size
1774 * of gap, but keep going so that we might find a smaller
1775 * gap to fill so avoiding fragmentation.
1776 */
1777 if (next - candidate >= size && next - candidate < mingap) {
1778 offset = candidate;
1779 mingap = next - candidate;
04b16653 1780 }
154cc9ea
DDAG
1781
1782 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
04b16653 1783 }
3e837b2c
AW
1784
1785 if (offset == RAM_ADDR_MAX) {
1786 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1787 (uint64_t)size);
1788 abort();
1789 }
1790
154cc9ea
DDAG
1791 trace_find_ram_offset(size, offset);
1792
04b16653
AW
1793 return offset;
1794}
1795
b8c48993 1796unsigned long last_ram_page(void)
d17b5288
AW
1797{
1798 RAMBlock *block;
1799 ram_addr_t last = 0;
1800
0dc3f44a 1801 rcu_read_lock();
99e15582 1802 RAMBLOCK_FOREACH(block) {
62be4e3a 1803 last = MAX(last, block->offset + block->max_length);
0d53d9fe 1804 }
0dc3f44a 1805 rcu_read_unlock();
b8c48993 1806 return last >> TARGET_PAGE_BITS;
d17b5288
AW
1807}
1808
ddb97f1d
JB
1809static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1810{
1811 int ret;
ddb97f1d
JB
1812
1813 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
47c8ca53 1814 if (!machine_dump_guest_core(current_machine)) {
ddb97f1d
JB
1815 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1816 if (ret) {
1817 perror("qemu_madvise");
1818 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1819 "but dump_guest_core=off specified\n");
1820 }
1821 }
1822}
1823
422148d3
DDAG
1824const char *qemu_ram_get_idstr(RAMBlock *rb)
1825{
1826 return rb->idstr;
1827}
1828
463a4ac2
DDAG
1829bool qemu_ram_is_shared(RAMBlock *rb)
1830{
1831 return rb->flags & RAM_SHARED;
1832}
1833
2ce16640
DDAG
1834/* Note: Only set at the start of postcopy */
1835bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1836{
1837 return rb->flags & RAM_UF_ZEROPAGE;
1838}
1839
1840void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1841{
1842 rb->flags |= RAM_UF_ZEROPAGE;
1843}
1844
b895de50
CLG
1845bool qemu_ram_is_migratable(RAMBlock *rb)
1846{
1847 return rb->flags & RAM_MIGRATABLE;
1848}
1849
1850void qemu_ram_set_migratable(RAMBlock *rb)
1851{
1852 rb->flags |= RAM_MIGRATABLE;
1853}
1854
1855void qemu_ram_unset_migratable(RAMBlock *rb)
1856{
1857 rb->flags &= ~RAM_MIGRATABLE;
1858}
1859
ae3a7047 1860/* Called with iothread lock held. */
fa53a0e5 1861void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
20cfe881 1862{
fa53a0e5 1863 RAMBlock *block;
20cfe881 1864
c5705a77
AK
1865 assert(new_block);
1866 assert(!new_block->idstr[0]);
84b89d78 1867
09e5ab63
AL
1868 if (dev) {
1869 char *id = qdev_get_dev_path(dev);
84b89d78
CM
1870 if (id) {
1871 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
7267c094 1872 g_free(id);
84b89d78
CM
1873 }
1874 }
1875 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1876
ab0a9956 1877 rcu_read_lock();
99e15582 1878 RAMBLOCK_FOREACH(block) {
fa53a0e5
GA
1879 if (block != new_block &&
1880 !strcmp(block->idstr, new_block->idstr)) {
84b89d78
CM
1881 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1882 new_block->idstr);
1883 abort();
1884 }
1885 }
0dc3f44a 1886 rcu_read_unlock();
c5705a77
AK
1887}
1888
ae3a7047 1889/* Called with iothread lock held. */
fa53a0e5 1890void qemu_ram_unset_idstr(RAMBlock *block)
20cfe881 1891{
ae3a7047
MD
1892 /* FIXME: arch_init.c assumes that this is not called throughout
1893 * migration. Ignore the problem since hot-unplug during migration
1894 * does not work anyway.
1895 */
20cfe881
HT
1896 if (block) {
1897 memset(block->idstr, 0, sizeof(block->idstr));
1898 }
1899}
1900
863e9621
DDAG
1901size_t qemu_ram_pagesize(RAMBlock *rb)
1902{
1903 return rb->page_size;
1904}
1905
67f11b5c
DDAG
1906/* Returns the largest size of page in use */
1907size_t qemu_ram_pagesize_largest(void)
1908{
1909 RAMBlock *block;
1910 size_t largest = 0;
1911
99e15582 1912 RAMBLOCK_FOREACH(block) {
67f11b5c
DDAG
1913 largest = MAX(largest, qemu_ram_pagesize(block));
1914 }
1915
1916 return largest;
1917}
1918
8490fc78
LC
1919static int memory_try_enable_merging(void *addr, size_t len)
1920{
75cc7f01 1921 if (!machine_mem_merge(current_machine)) {
8490fc78
LC
1922 /* disabled by the user */
1923 return 0;
1924 }
1925
1926 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1927}
1928
62be4e3a
MT
1929/* Only legal before guest might have detected the memory size: e.g. on
1930 * incoming migration, or right after reset.
1931 *
1932 * As memory core doesn't know how is memory accessed, it is up to
1933 * resize callback to update device state and/or add assertions to detect
1934 * misuse, if necessary.
1935 */
fa53a0e5 1936int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
62be4e3a 1937{
62be4e3a
MT
1938 assert(block);
1939
4ed023ce 1940 newsize = HOST_PAGE_ALIGN(newsize);
129ddaf3 1941
62be4e3a
MT
1942 if (block->used_length == newsize) {
1943 return 0;
1944 }
1945
1946 if (!(block->flags & RAM_RESIZEABLE)) {
1947 error_setg_errno(errp, EINVAL,
1948 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1949 " in != 0x" RAM_ADDR_FMT, block->idstr,
1950 newsize, block->used_length);
1951 return -EINVAL;
1952 }
1953
1954 if (block->max_length < newsize) {
1955 error_setg_errno(errp, EINVAL,
1956 "Length too large: %s: 0x" RAM_ADDR_FMT
1957 " > 0x" RAM_ADDR_FMT, block->idstr,
1958 newsize, block->max_length);
1959 return -EINVAL;
1960 }
1961
1962 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1963 block->used_length = newsize;
58d2707e
PB
1964 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1965 DIRTY_CLIENTS_ALL);
62be4e3a
MT
1966 memory_region_set_size(block->mr, newsize);
1967 if (block->resized) {
1968 block->resized(block->idstr, newsize, block->host);
1969 }
1970 return 0;
1971}
1972
5b82b703
SH
1973/* Called with ram_list.mutex held */
1974static void dirty_memory_extend(ram_addr_t old_ram_size,
1975 ram_addr_t new_ram_size)
1976{
1977 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1978 DIRTY_MEMORY_BLOCK_SIZE);
1979 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1980 DIRTY_MEMORY_BLOCK_SIZE);
1981 int i;
1982
1983 /* Only need to extend if block count increased */
1984 if (new_num_blocks <= old_num_blocks) {
1985 return;
1986 }
1987
1988 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1989 DirtyMemoryBlocks *old_blocks;
1990 DirtyMemoryBlocks *new_blocks;
1991 int j;
1992
1993 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
1994 new_blocks = g_malloc(sizeof(*new_blocks) +
1995 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1996
1997 if (old_num_blocks) {
1998 memcpy(new_blocks->blocks, old_blocks->blocks,
1999 old_num_blocks * sizeof(old_blocks->blocks[0]));
2000 }
2001
2002 for (j = old_num_blocks; j < new_num_blocks; j++) {
2003 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
2004 }
2005
2006 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
2007
2008 if (old_blocks) {
2009 g_free_rcu(old_blocks, rcu);
2010 }
2011 }
2012}
2013
06329cce 2014static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
c5705a77 2015{
e1c57ab8 2016 RAMBlock *block;
0d53d9fe 2017 RAMBlock *last_block = NULL;
2152f5ca 2018 ram_addr_t old_ram_size, new_ram_size;
37aa7a0e 2019 Error *err = NULL;
2152f5ca 2020
b8c48993 2021 old_ram_size = last_ram_page();
c5705a77 2022
b2a8658e 2023 qemu_mutex_lock_ramlist();
9b8424d5 2024 new_block->offset = find_ram_offset(new_block->max_length);
e1c57ab8
PB
2025
2026 if (!new_block->host) {
2027 if (xen_enabled()) {
9b8424d5 2028 xen_ram_alloc(new_block->offset, new_block->max_length,
37aa7a0e
MA
2029 new_block->mr, &err);
2030 if (err) {
2031 error_propagate(errp, err);
2032 qemu_mutex_unlock_ramlist();
39c350ee 2033 return;
37aa7a0e 2034 }
e1c57ab8 2035 } else {
9b8424d5 2036 new_block->host = phys_mem_alloc(new_block->max_length,
06329cce 2037 &new_block->mr->align, shared);
39228250 2038 if (!new_block->host) {
ef701d7b
HT
2039 error_setg_errno(errp, errno,
2040 "cannot set up guest memory '%s'",
2041 memory_region_name(new_block->mr));
2042 qemu_mutex_unlock_ramlist();
39c350ee 2043 return;
39228250 2044 }
9b8424d5 2045 memory_try_enable_merging(new_block->host, new_block->max_length);
6977dfe6 2046 }
c902760f 2047 }
94a6b54f 2048
dd631697
LZ
2049 new_ram_size = MAX(old_ram_size,
2050 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
2051 if (new_ram_size > old_ram_size) {
5b82b703 2052 dirty_memory_extend(old_ram_size, new_ram_size);
dd631697 2053 }
0d53d9fe
MD
2054 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
2055 * QLIST (which has an RCU-friendly variant) does not have insertion at
2056 * tail, so save the last element in last_block.
2057 */
99e15582 2058 RAMBLOCK_FOREACH(block) {
0d53d9fe 2059 last_block = block;
9b8424d5 2060 if (block->max_length < new_block->max_length) {
abb26d63
PB
2061 break;
2062 }
2063 }
2064 if (block) {
0dc3f44a 2065 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
0d53d9fe 2066 } else if (last_block) {
0dc3f44a 2067 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
0d53d9fe 2068 } else { /* list is empty */
0dc3f44a 2069 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
abb26d63 2070 }
0d6d3c87 2071 ram_list.mru_block = NULL;
94a6b54f 2072
0dc3f44a
MD
2073 /* Write list before version */
2074 smp_wmb();
f798b07f 2075 ram_list.version++;
b2a8658e 2076 qemu_mutex_unlock_ramlist();
f798b07f 2077
9b8424d5 2078 cpu_physical_memory_set_dirty_range(new_block->offset,
58d2707e
PB
2079 new_block->used_length,
2080 DIRTY_CLIENTS_ALL);
94a6b54f 2081
a904c911
PB
2082 if (new_block->host) {
2083 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2084 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
c2cd627d 2085 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
a904c911 2086 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
0987d735 2087 ram_block_notify_add(new_block->host, new_block->max_length);
e1c57ab8 2088 }
94a6b54f 2089}
e9a1ab19 2090
0b183fc8 2091#ifdef __linux__
38b3362d
MAL
2092RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2093 bool share, int fd,
2094 Error **errp)
e1c57ab8
PB
2095{
2096 RAMBlock *new_block;
ef701d7b 2097 Error *local_err = NULL;
8d37b030 2098 int64_t file_size;
e1c57ab8
PB
2099
2100 if (xen_enabled()) {
7f56e740 2101 error_setg(errp, "-mem-path not supported with Xen");
528f46af 2102 return NULL;
e1c57ab8
PB
2103 }
2104
e45e7ae2
MAL
2105 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2106 error_setg(errp,
2107 "host lacks kvm mmu notifiers, -mem-path unsupported");
2108 return NULL;
2109 }
2110
e1c57ab8
PB
2111 if (phys_mem_alloc != qemu_anon_ram_alloc) {
2112 /*
2113 * file_ram_alloc() needs to allocate just like
2114 * phys_mem_alloc, but we haven't bothered to provide
2115 * a hook there.
2116 */
7f56e740
PB
2117 error_setg(errp,
2118 "-mem-path not supported with this accelerator");
528f46af 2119 return NULL;
e1c57ab8
PB
2120 }
2121
4ed023ce 2122 size = HOST_PAGE_ALIGN(size);
8d37b030
MAL
2123 file_size = get_file_size(fd);
2124 if (file_size > 0 && file_size < size) {
2125 error_setg(errp, "backing store %s size 0x%" PRIx64
2126 " does not match 'size' option 0x" RAM_ADDR_FMT,
2127 mem_path, file_size, size);
8d37b030
MAL
2128 return NULL;
2129 }
2130
e1c57ab8
PB
2131 new_block = g_malloc0(sizeof(*new_block));
2132 new_block->mr = mr;
9b8424d5
MT
2133 new_block->used_length = size;
2134 new_block->max_length = size;
dbcb8981 2135 new_block->flags = share ? RAM_SHARED : 0;
8d37b030 2136 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
7f56e740
PB
2137 if (!new_block->host) {
2138 g_free(new_block);
528f46af 2139 return NULL;
7f56e740
PB
2140 }
2141
06329cce 2142 ram_block_add(new_block, &local_err, share);
ef701d7b
HT
2143 if (local_err) {
2144 g_free(new_block);
2145 error_propagate(errp, local_err);
528f46af 2146 return NULL;
ef701d7b 2147 }
528f46af 2148 return new_block;
38b3362d
MAL
2149
2150}
2151
2152
2153RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2154 bool share, const char *mem_path,
2155 Error **errp)
2156{
2157 int fd;
2158 bool created;
2159 RAMBlock *block;
2160
2161 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2162 if (fd < 0) {
2163 return NULL;
2164 }
2165
2166 block = qemu_ram_alloc_from_fd(size, mr, share, fd, errp);
2167 if (!block) {
2168 if (created) {
2169 unlink(mem_path);
2170 }
2171 close(fd);
2172 return NULL;
2173 }
2174
2175 return block;
e1c57ab8 2176}
0b183fc8 2177#endif
e1c57ab8 2178
62be4e3a 2179static
528f46af
FZ
2180RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2181 void (*resized)(const char*,
2182 uint64_t length,
2183 void *host),
06329cce 2184 void *host, bool resizeable, bool share,
528f46af 2185 MemoryRegion *mr, Error **errp)
e1c57ab8
PB
2186{
2187 RAMBlock *new_block;
ef701d7b 2188 Error *local_err = NULL;
e1c57ab8 2189
4ed023ce
DDAG
2190 size = HOST_PAGE_ALIGN(size);
2191 max_size = HOST_PAGE_ALIGN(max_size);
e1c57ab8
PB
2192 new_block = g_malloc0(sizeof(*new_block));
2193 new_block->mr = mr;
62be4e3a 2194 new_block->resized = resized;
9b8424d5
MT
2195 new_block->used_length = size;
2196 new_block->max_length = max_size;
62be4e3a 2197 assert(max_size >= size);
e1c57ab8 2198 new_block->fd = -1;
863e9621 2199 new_block->page_size = getpagesize();
e1c57ab8
PB
2200 new_block->host = host;
2201 if (host) {
7bd4f430 2202 new_block->flags |= RAM_PREALLOC;
e1c57ab8 2203 }
62be4e3a
MT
2204 if (resizeable) {
2205 new_block->flags |= RAM_RESIZEABLE;
2206 }
06329cce 2207 ram_block_add(new_block, &local_err, share);
ef701d7b
HT
2208 if (local_err) {
2209 g_free(new_block);
2210 error_propagate(errp, local_err);
528f46af 2211 return NULL;
ef701d7b 2212 }
528f46af 2213 return new_block;
e1c57ab8
PB
2214}
2215
528f46af 2216RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
62be4e3a
MT
2217 MemoryRegion *mr, Error **errp)
2218{
06329cce
MA
2219 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2220 false, mr, errp);
62be4e3a
MT
2221}
2222
06329cce
MA
2223RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2224 MemoryRegion *mr, Error **errp)
6977dfe6 2225{
06329cce
MA
2226 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2227 share, mr, errp);
62be4e3a
MT
2228}
2229
528f46af 2230RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
62be4e3a
MT
2231 void (*resized)(const char*,
2232 uint64_t length,
2233 void *host),
2234 MemoryRegion *mr, Error **errp)
2235{
06329cce
MA
2236 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2237 false, mr, errp);
6977dfe6
YT
2238}
2239
43771539
PB
2240static void reclaim_ramblock(RAMBlock *block)
2241{
2242 if (block->flags & RAM_PREALLOC) {
2243 ;
2244 } else if (xen_enabled()) {
2245 xen_invalidate_map_cache_entry(block->host);
2246#ifndef _WIN32
2247 } else if (block->fd >= 0) {
2f3a2bb1 2248 qemu_ram_munmap(block->host, block->max_length);
43771539
PB
2249 close(block->fd);
2250#endif
2251 } else {
2252 qemu_anon_ram_free(block->host, block->max_length);
2253 }
2254 g_free(block);
2255}
2256
f1060c55 2257void qemu_ram_free(RAMBlock *block)
e9a1ab19 2258{
85bc2a15
MAL
2259 if (!block) {
2260 return;
2261 }
2262
0987d735
PB
2263 if (block->host) {
2264 ram_block_notify_remove(block->host, block->max_length);
2265 }
2266
b2a8658e 2267 qemu_mutex_lock_ramlist();
f1060c55
FZ
2268 QLIST_REMOVE_RCU(block, next);
2269 ram_list.mru_block = NULL;
2270 /* Write list before version */
2271 smp_wmb();
2272 ram_list.version++;
2273 call_rcu(block, reclaim_ramblock, rcu);
b2a8658e 2274 qemu_mutex_unlock_ramlist();
e9a1ab19
FB
2275}
2276
cd19cfa2
HY
2277#ifndef _WIN32
2278void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2279{
2280 RAMBlock *block;
2281 ram_addr_t offset;
2282 int flags;
2283 void *area, *vaddr;
2284
99e15582 2285 RAMBLOCK_FOREACH(block) {
cd19cfa2 2286 offset = addr - block->offset;
9b8424d5 2287 if (offset < block->max_length) {
1240be24 2288 vaddr = ramblock_ptr(block, offset);
7bd4f430 2289 if (block->flags & RAM_PREALLOC) {
cd19cfa2 2290 ;
dfeaf2ab
MA
2291 } else if (xen_enabled()) {
2292 abort();
cd19cfa2
HY
2293 } else {
2294 flags = MAP_FIXED;
3435f395 2295 if (block->fd >= 0) {
dbcb8981
PB
2296 flags |= (block->flags & RAM_SHARED ?
2297 MAP_SHARED : MAP_PRIVATE);
3435f395
MA
2298 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2299 flags, block->fd, offset);
cd19cfa2 2300 } else {
2eb9fbaa
MA
2301 /*
2302 * Remap needs to match alloc. Accelerators that
2303 * set phys_mem_alloc never remap. If they did,
2304 * we'd need a remap hook here.
2305 */
2306 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2307
cd19cfa2
HY
2308 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2309 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2310 flags, -1, 0);
cd19cfa2
HY
2311 }
2312 if (area != vaddr) {
493d89bf
AF
2313 error_report("Could not remap addr: "
2314 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2315 length, addr);
cd19cfa2
HY
2316 exit(1);
2317 }
8490fc78 2318 memory_try_enable_merging(vaddr, length);
ddb97f1d 2319 qemu_ram_setup_dump(vaddr, length);
cd19cfa2 2320 }
cd19cfa2
HY
2321 }
2322 }
2323}
2324#endif /* !_WIN32 */
2325
1b5ec234 2326/* Return a host pointer to ram allocated with qemu_ram_alloc.
ae3a7047
MD
2327 * This should not be used for general purpose DMA. Use address_space_map
2328 * or address_space_rw instead. For local memory (e.g. video ram) that the
2329 * device owns, use memory_region_get_ram_ptr.
0dc3f44a 2330 *
49b24afc 2331 * Called within RCU critical section.
1b5ec234 2332 */
0878d0e1 2333void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
1b5ec234 2334{
3655cb9c
GA
2335 RAMBlock *block = ram_block;
2336
2337 if (block == NULL) {
2338 block = qemu_get_ram_block(addr);
0878d0e1 2339 addr -= block->offset;
3655cb9c 2340 }
ae3a7047
MD
2341
2342 if (xen_enabled() && block->host == NULL) {
0d6d3c87
PB
2343 /* We need to check if the requested address is in the RAM
2344 * because we don't want to map the entire memory in QEMU.
2345 * In that case just map until the end of the page.
2346 */
2347 if (block->offset == 0) {
1ff7c598 2348 return xen_map_cache(addr, 0, 0, false);
0d6d3c87 2349 }
ae3a7047 2350
1ff7c598 2351 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
0d6d3c87 2352 }
0878d0e1 2353 return ramblock_ptr(block, addr);
dc828ca1
PB
2354}
2355
0878d0e1 2356/* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
ae3a7047 2357 * but takes a size argument.
0dc3f44a 2358 *
e81bcda5 2359 * Called within RCU critical section.
ae3a7047 2360 */
3655cb9c 2361static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
f5aa69bd 2362 hwaddr *size, bool lock)
38bee5dc 2363{
3655cb9c 2364 RAMBlock *block = ram_block;
8ab934f9
SS
2365 if (*size == 0) {
2366 return NULL;
2367 }
e81bcda5 2368
3655cb9c
GA
2369 if (block == NULL) {
2370 block = qemu_get_ram_block(addr);
0878d0e1 2371 addr -= block->offset;
3655cb9c 2372 }
0878d0e1 2373 *size = MIN(*size, block->max_length - addr);
e81bcda5
PB
2374
2375 if (xen_enabled() && block->host == NULL) {
2376 /* We need to check if the requested address is in the RAM
2377 * because we don't want to map the entire memory in QEMU.
2378 * In that case just map the requested area.
2379 */
2380 if (block->offset == 0) {
f5aa69bd 2381 return xen_map_cache(addr, *size, lock, lock);
38bee5dc
SS
2382 }
2383
f5aa69bd 2384 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
38bee5dc 2385 }
e81bcda5 2386
0878d0e1 2387 return ramblock_ptr(block, addr);
38bee5dc
SS
2388}
2389
f90bb71b
DDAG
2390/* Return the offset of a hostpointer within a ramblock */
2391ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2392{
2393 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2394 assert((uintptr_t)host >= (uintptr_t)rb->host);
2395 assert(res < rb->max_length);
2396
2397 return res;
2398}
2399
422148d3
DDAG
2400/*
2401 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2402 * in that RAMBlock.
2403 *
2404 * ptr: Host pointer to look up
2405 * round_offset: If true round the result offset down to a page boundary
2406 * *ram_addr: set to result ram_addr
2407 * *offset: set to result offset within the RAMBlock
2408 *
2409 * Returns: RAMBlock (or NULL if not found)
ae3a7047
MD
2410 *
2411 * By the time this function returns, the returned pointer is not protected
2412 * by RCU anymore. If the caller is not within an RCU critical section and
2413 * does not hold the iothread lock, it must have other means of protecting the
2414 * pointer, such as a reference to the region that includes the incoming
2415 * ram_addr_t.
2416 */
422148d3 2417RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
422148d3 2418 ram_addr_t *offset)
5579c7f3 2419{
94a6b54f
PB
2420 RAMBlock *block;
2421 uint8_t *host = ptr;
2422
868bb33f 2423 if (xen_enabled()) {
f615f396 2424 ram_addr_t ram_addr;
0dc3f44a 2425 rcu_read_lock();
f615f396
PB
2426 ram_addr = xen_ram_addr_from_mapcache(ptr);
2427 block = qemu_get_ram_block(ram_addr);
422148d3 2428 if (block) {
d6b6aec4 2429 *offset = ram_addr - block->offset;
422148d3 2430 }
0dc3f44a 2431 rcu_read_unlock();
422148d3 2432 return block;
712c2b41
SS
2433 }
2434
0dc3f44a
MD
2435 rcu_read_lock();
2436 block = atomic_rcu_read(&ram_list.mru_block);
9b8424d5 2437 if (block && block->host && host - block->host < block->max_length) {
23887b79
PB
2438 goto found;
2439 }
2440
99e15582 2441 RAMBLOCK_FOREACH(block) {
432d268c
JN
2442 /* This case append when the block is not mapped. */
2443 if (block->host == NULL) {
2444 continue;
2445 }
9b8424d5 2446 if (host - block->host < block->max_length) {
23887b79 2447 goto found;
f471a17e 2448 }
94a6b54f 2449 }
432d268c 2450
0dc3f44a 2451 rcu_read_unlock();
1b5ec234 2452 return NULL;
23887b79
PB
2453
2454found:
422148d3
DDAG
2455 *offset = (host - block->host);
2456 if (round_offset) {
2457 *offset &= TARGET_PAGE_MASK;
2458 }
0dc3f44a 2459 rcu_read_unlock();
422148d3
DDAG
2460 return block;
2461}
2462
e3dd7493
DDAG
2463/*
2464 * Finds the named RAMBlock
2465 *
2466 * name: The name of RAMBlock to find
2467 *
2468 * Returns: RAMBlock (or NULL if not found)
2469 */
2470RAMBlock *qemu_ram_block_by_name(const char *name)
2471{
2472 RAMBlock *block;
2473
99e15582 2474 RAMBLOCK_FOREACH(block) {
e3dd7493
DDAG
2475 if (!strcmp(name, block->idstr)) {
2476 return block;
2477 }
2478 }
2479
2480 return NULL;
2481}
2482
422148d3
DDAG
2483/* Some of the softmmu routines need to translate from a host pointer
2484 (typically a TLB entry) back to a ram offset. */
07bdaa41 2485ram_addr_t qemu_ram_addr_from_host(void *ptr)
422148d3
DDAG
2486{
2487 RAMBlock *block;
f615f396 2488 ram_addr_t offset;
422148d3 2489
f615f396 2490 block = qemu_ram_block_from_host(ptr, false, &offset);
422148d3 2491 if (!block) {
07bdaa41 2492 return RAM_ADDR_INVALID;
422148d3
DDAG
2493 }
2494
07bdaa41 2495 return block->offset + offset;
e890261f 2496}
f471a17e 2497
27266271
PM
2498/* Called within RCU critical section. */
2499void memory_notdirty_write_prepare(NotDirtyInfo *ndi,
2500 CPUState *cpu,
2501 vaddr mem_vaddr,
2502 ram_addr_t ram_addr,
2503 unsigned size)
2504{
2505 ndi->cpu = cpu;
2506 ndi->ram_addr = ram_addr;
2507 ndi->mem_vaddr = mem_vaddr;
2508 ndi->size = size;
2509 ndi->locked = false;
ba051fb5 2510
5aa1ef71 2511 assert(tcg_enabled());
52159192 2512 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
27266271 2513 ndi->locked = true;
ba051fb5 2514 tb_lock();
0e0df1e2 2515 tb_invalidate_phys_page_fast(ram_addr, size);
3a7d929e 2516 }
27266271
PM
2517}
2518
2519/* Called within RCU critical section. */
2520void memory_notdirty_write_complete(NotDirtyInfo *ndi)
2521{
2522 if (ndi->locked) {
2523 tb_unlock();
2524 }
2525
2526 /* Set both VGA and migration bits for simplicity and to remove
2527 * the notdirty callback faster.
2528 */
2529 cpu_physical_memory_set_dirty_range(ndi->ram_addr, ndi->size,
2530 DIRTY_CLIENTS_NOCODE);
2531 /* we remove the notdirty callback only if the code has been
2532 flushed */
2533 if (!cpu_physical_memory_is_clean(ndi->ram_addr)) {
2534 tlb_set_dirty(ndi->cpu, ndi->mem_vaddr);
2535 }
2536}
2537
2538/* Called within RCU critical section. */
2539static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2540 uint64_t val, unsigned size)
2541{
2542 NotDirtyInfo ndi;
2543
2544 memory_notdirty_write_prepare(&ndi, current_cpu, current_cpu->mem_io_vaddr,
2545 ram_addr, size);
2546
6d3ede54 2547 stn_p(qemu_map_ram_ptr(NULL, ram_addr), size, val);
27266271 2548 memory_notdirty_write_complete(&ndi);
9fa3e853
FB
2549}
2550
b018ddf6 2551static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
8372d383
PM
2552 unsigned size, bool is_write,
2553 MemTxAttrs attrs)
b018ddf6
PB
2554{
2555 return is_write;
2556}
2557
0e0df1e2 2558static const MemoryRegionOps notdirty_mem_ops = {
0e0df1e2 2559 .write = notdirty_mem_write,
b018ddf6 2560 .valid.accepts = notdirty_mem_accepts,
0e0df1e2 2561 .endianness = DEVICE_NATIVE_ENDIAN,
ad52878f
AB
2562 .valid = {
2563 .min_access_size = 1,
2564 .max_access_size = 8,
2565 .unaligned = false,
2566 },
2567 .impl = {
2568 .min_access_size = 1,
2569 .max_access_size = 8,
2570 .unaligned = false,
2571 },
1ccde1cb
FB
2572};
2573
0f459d16 2574/* Generate a debug exception if a watchpoint has been hit. */
66b9b43c 2575static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
0f459d16 2576{
93afeade 2577 CPUState *cpu = current_cpu;
568496c0 2578 CPUClass *cc = CPU_GET_CLASS(cpu);
0f459d16 2579 target_ulong vaddr;
a1d1bb31 2580 CPUWatchpoint *wp;
0f459d16 2581
5aa1ef71 2582 assert(tcg_enabled());
ff4700b0 2583 if (cpu->watchpoint_hit) {
06d55cc1
AL
2584 /* We re-entered the check after replacing the TB. Now raise
2585 * the debug interrupt so that is will trigger after the
2586 * current instruction. */
93afeade 2587 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
06d55cc1
AL
2588 return;
2589 }
93afeade 2590 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
40612000 2591 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
ff4700b0 2592 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
05068c0d
PM
2593 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2594 && (wp->flags & flags)) {
08225676
PM
2595 if (flags == BP_MEM_READ) {
2596 wp->flags |= BP_WATCHPOINT_HIT_READ;
2597 } else {
2598 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2599 }
2600 wp->hitaddr = vaddr;
66b9b43c 2601 wp->hitattrs = attrs;
ff4700b0 2602 if (!cpu->watchpoint_hit) {
568496c0
SF
2603 if (wp->flags & BP_CPU &&
2604 !cc->debug_check_watchpoint(cpu, wp)) {
2605 wp->flags &= ~BP_WATCHPOINT_HIT;
2606 continue;
2607 }
ff4700b0 2608 cpu->watchpoint_hit = wp;
a5e99826 2609
8d04fb55
JK
2610 /* Both tb_lock and iothread_mutex will be reset when
2611 * cpu_loop_exit or cpu_loop_exit_noexc longjmp
2612 * back into the cpu_exec main loop.
a5e99826
FK
2613 */
2614 tb_lock();
239c51a5 2615 tb_check_watchpoint(cpu);
6e140f28 2616 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
27103424 2617 cpu->exception_index = EXCP_DEBUG;
5638d180 2618 cpu_loop_exit(cpu);
6e140f28 2619 } else {
9b990ee5
RH
2620 /* Force execution of one insn next time. */
2621 cpu->cflags_next_tb = 1 | curr_cflags();
6886b980 2622 cpu_loop_exit_noexc(cpu);
6e140f28 2623 }
06d55cc1 2624 }
6e140f28
AL
2625 } else {
2626 wp->flags &= ~BP_WATCHPOINT_HIT;
0f459d16
PB
2627 }
2628 }
2629}
2630
6658ffb8
PB
2631/* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2632 so these check for a hit then pass through to the normal out-of-line
2633 phys routines. */
66b9b43c
PM
2634static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2635 unsigned size, MemTxAttrs attrs)
6658ffb8 2636{
66b9b43c
PM
2637 MemTxResult res;
2638 uint64_t data;
79ed0416
PM
2639 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2640 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
66b9b43c
PM
2641
2642 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
1ec9b909 2643 switch (size) {
66b9b43c 2644 case 1:
79ed0416 2645 data = address_space_ldub(as, addr, attrs, &res);
66b9b43c
PM
2646 break;
2647 case 2:
79ed0416 2648 data = address_space_lduw(as, addr, attrs, &res);
66b9b43c
PM
2649 break;
2650 case 4:
79ed0416 2651 data = address_space_ldl(as, addr, attrs, &res);
66b9b43c 2652 break;
306526b5
PB
2653 case 8:
2654 data = address_space_ldq(as, addr, attrs, &res);
2655 break;
1ec9b909
AK
2656 default: abort();
2657 }
66b9b43c
PM
2658 *pdata = data;
2659 return res;
6658ffb8
PB
2660}
2661
66b9b43c
PM
2662static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2663 uint64_t val, unsigned size,
2664 MemTxAttrs attrs)
6658ffb8 2665{
66b9b43c 2666 MemTxResult res;
79ed0416
PM
2667 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2668 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
66b9b43c
PM
2669
2670 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
1ec9b909 2671 switch (size) {
67364150 2672 case 1:
79ed0416 2673 address_space_stb(as, addr, val, attrs, &res);
67364150
MF
2674 break;
2675 case 2:
79ed0416 2676 address_space_stw(as, addr, val, attrs, &res);
67364150
MF
2677 break;
2678 case 4:
79ed0416 2679 address_space_stl(as, addr, val, attrs, &res);
67364150 2680 break;
306526b5
PB
2681 case 8:
2682 address_space_stq(as, addr, val, attrs, &res);
2683 break;
1ec9b909
AK
2684 default: abort();
2685 }
66b9b43c 2686 return res;
6658ffb8
PB
2687}
2688
1ec9b909 2689static const MemoryRegionOps watch_mem_ops = {
66b9b43c
PM
2690 .read_with_attrs = watch_mem_read,
2691 .write_with_attrs = watch_mem_write,
1ec9b909 2692 .endianness = DEVICE_NATIVE_ENDIAN,
306526b5
PB
2693 .valid = {
2694 .min_access_size = 1,
2695 .max_access_size = 8,
2696 .unaligned = false,
2697 },
2698 .impl = {
2699 .min_access_size = 1,
2700 .max_access_size = 8,
2701 .unaligned = false,
2702 },
6658ffb8 2703};
6658ffb8 2704
b2a44fca
PB
2705static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2706 MemTxAttrs attrs, uint8_t *buf, int len);
16620684
AK
2707static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2708 const uint8_t *buf, int len);
2709static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
eace72b7 2710 bool is_write, MemTxAttrs attrs);
16620684 2711
f25a49e0
PM
2712static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2713 unsigned len, MemTxAttrs attrs)
db7b5426 2714{
acc9d80b 2715 subpage_t *subpage = opaque;
ff6cff75 2716 uint8_t buf[8];
5c9eb028 2717 MemTxResult res;
791af8c8 2718
db7b5426 2719#if defined(DEBUG_SUBPAGE)
016e9d62 2720 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
acc9d80b 2721 subpage, len, addr);
db7b5426 2722#endif
16620684 2723 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
5c9eb028
PM
2724 if (res) {
2725 return res;
f25a49e0 2726 }
6d3ede54
PM
2727 *data = ldn_p(buf, len);
2728 return MEMTX_OK;
db7b5426
BS
2729}
2730
f25a49e0
PM
2731static MemTxResult subpage_write(void *opaque, hwaddr addr,
2732 uint64_t value, unsigned len, MemTxAttrs attrs)
db7b5426 2733{
acc9d80b 2734 subpage_t *subpage = opaque;
ff6cff75 2735 uint8_t buf[8];
acc9d80b 2736
db7b5426 2737#if defined(DEBUG_SUBPAGE)
016e9d62 2738 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
acc9d80b
JK
2739 " value %"PRIx64"\n",
2740 __func__, subpage, len, addr, value);
db7b5426 2741#endif
6d3ede54 2742 stn_p(buf, len, value);
16620684 2743 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
db7b5426
BS
2744}
2745
c353e4cc 2746static bool subpage_accepts(void *opaque, hwaddr addr,
8372d383
PM
2747 unsigned len, bool is_write,
2748 MemTxAttrs attrs)
c353e4cc 2749{
acc9d80b 2750 subpage_t *subpage = opaque;
c353e4cc 2751#if defined(DEBUG_SUBPAGE)
016e9d62 2752 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
acc9d80b 2753 __func__, subpage, is_write ? 'w' : 'r', len, addr);
c353e4cc
PB
2754#endif
2755
16620684 2756 return flatview_access_valid(subpage->fv, addr + subpage->base,
eace72b7 2757 len, is_write, attrs);
c353e4cc
PB
2758}
2759
70c68e44 2760static const MemoryRegionOps subpage_ops = {
f25a49e0
PM
2761 .read_with_attrs = subpage_read,
2762 .write_with_attrs = subpage_write,
ff6cff75
PB
2763 .impl.min_access_size = 1,
2764 .impl.max_access_size = 8,
2765 .valid.min_access_size = 1,
2766 .valid.max_access_size = 8,
c353e4cc 2767 .valid.accepts = subpage_accepts,
70c68e44 2768 .endianness = DEVICE_NATIVE_ENDIAN,
db7b5426
BS
2769};
2770
c227f099 2771static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
5312bd8b 2772 uint16_t section)
db7b5426
BS
2773{
2774 int idx, eidx;
2775
2776 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2777 return -1;
2778 idx = SUBPAGE_IDX(start);
2779 eidx = SUBPAGE_IDX(end);
2780#if defined(DEBUG_SUBPAGE)
016e9d62
AK
2781 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2782 __func__, mmio, start, end, idx, eidx, section);
db7b5426 2783#endif
db7b5426 2784 for (; idx <= eidx; idx++) {
5312bd8b 2785 mmio->sub_section[idx] = section;
db7b5426
BS
2786 }
2787
2788 return 0;
2789}
2790
16620684 2791static subpage_t *subpage_init(FlatView *fv, hwaddr base)
db7b5426 2792{
c227f099 2793 subpage_t *mmio;
db7b5426 2794
2615fabd 2795 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
16620684 2796 mmio->fv = fv;
1eec614b 2797 mmio->base = base;
2c9b15ca 2798 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
b4fefef9 2799 NULL, TARGET_PAGE_SIZE);
b3b00c78 2800 mmio->iomem.subpage = true;
db7b5426 2801#if defined(DEBUG_SUBPAGE)
016e9d62
AK
2802 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2803 mmio, base, TARGET_PAGE_SIZE);
db7b5426 2804#endif
b41aac4f 2805 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
db7b5426
BS
2806
2807 return mmio;
2808}
2809
16620684 2810static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
5312bd8b 2811{
16620684 2812 assert(fv);
5312bd8b 2813 MemoryRegionSection section = {
16620684 2814 .fv = fv,
5312bd8b
AK
2815 .mr = mr,
2816 .offset_within_address_space = 0,
2817 .offset_within_region = 0,
052e87b0 2818 .size = int128_2_64(),
5312bd8b
AK
2819 };
2820
53cb28cb 2821 return phys_section_add(map, &section);
5312bd8b
AK
2822}
2823
8af36743
PM
2824static void readonly_mem_write(void *opaque, hwaddr addr,
2825 uint64_t val, unsigned size)
2826{
2827 /* Ignore any write to ROM. */
2828}
2829
2830static bool readonly_mem_accepts(void *opaque, hwaddr addr,
8372d383
PM
2831 unsigned size, bool is_write,
2832 MemTxAttrs attrs)
8af36743
PM
2833{
2834 return is_write;
2835}
2836
2837/* This will only be used for writes, because reads are special cased
2838 * to directly access the underlying host ram.
2839 */
2840static const MemoryRegionOps readonly_mem_ops = {
2841 .write = readonly_mem_write,
2842 .valid.accepts = readonly_mem_accepts,
2843 .endianness = DEVICE_NATIVE_ENDIAN,
2844 .valid = {
2845 .min_access_size = 1,
2846 .max_access_size = 8,
2847 .unaligned = false,
2848 },
2849 .impl = {
2850 .min_access_size = 1,
2851 .max_access_size = 8,
2852 .unaligned = false,
2853 },
2854};
2855
2d54f194
PM
2856MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2857 hwaddr index, MemTxAttrs attrs)
aa102231 2858{
a54c87b6
PM
2859 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2860 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
32857f4d 2861 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
79e2b9ae 2862 MemoryRegionSection *sections = d->map.sections;
9d82b5a7 2863
2d54f194 2864 return &sections[index & ~TARGET_PAGE_MASK];
aa102231
AK
2865}
2866
e9179ce1
AK
2867static void io_mem_init(void)
2868{
8af36743
PM
2869 memory_region_init_io(&io_mem_rom, NULL, &readonly_mem_ops,
2870 NULL, NULL, UINT64_MAX);
2c9b15ca 2871 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
1f6245e5 2872 NULL, UINT64_MAX);
8d04fb55
JK
2873
2874 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
2875 * which can be called without the iothread mutex.
2876 */
2c9b15ca 2877 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
1f6245e5 2878 NULL, UINT64_MAX);
8d04fb55
JK
2879 memory_region_clear_global_locking(&io_mem_notdirty);
2880
2c9b15ca 2881 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
1f6245e5 2882 NULL, UINT64_MAX);
e9179ce1
AK
2883}
2884
8629d3fc 2885AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
00752703 2886{
53cb28cb
MA
2887 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2888 uint16_t n;
2889
16620684 2890 n = dummy_section(&d->map, fv, &io_mem_unassigned);
53cb28cb 2891 assert(n == PHYS_SECTION_UNASSIGNED);
16620684 2892 n = dummy_section(&d->map, fv, &io_mem_notdirty);
53cb28cb 2893 assert(n == PHYS_SECTION_NOTDIRTY);
16620684 2894 n = dummy_section(&d->map, fv, &io_mem_rom);
53cb28cb 2895 assert(n == PHYS_SECTION_ROM);
16620684 2896 n = dummy_section(&d->map, fv, &io_mem_watch);
53cb28cb 2897 assert(n == PHYS_SECTION_WATCH);
00752703 2898
9736e55b 2899 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
66a6df1d
AK
2900
2901 return d;
00752703
PB
2902}
2903
66a6df1d 2904void address_space_dispatch_free(AddressSpaceDispatch *d)
79e2b9ae
PB
2905{
2906 phys_sections_free(&d->map);
2907 g_free(d);
2908}
2909
1d71148e 2910static void tcg_commit(MemoryListener *listener)
50c1e149 2911{
32857f4d
PM
2912 CPUAddressSpace *cpuas;
2913 AddressSpaceDispatch *d;
117712c3
AK
2914
2915 /* since each CPU stores ram addresses in its TLB cache, we must
2916 reset the modified entries */
32857f4d
PM
2917 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2918 cpu_reloading_memory_map();
2919 /* The CPU and TLB are protected by the iothread lock.
2920 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2921 * may have split the RCU critical section.
2922 */
66a6df1d 2923 d = address_space_to_dispatch(cpuas->as);
f35e44e7 2924 atomic_rcu_set(&cpuas->memory_dispatch, d);
d10eb08f 2925 tlb_flush(cpuas->cpu);
50c1e149
AK
2926}
2927
62152b8a
AK
2928static void memory_map_init(void)
2929{
7267c094 2930 system_memory = g_malloc(sizeof(*system_memory));
03f49957 2931
57271d63 2932 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
7dca8043 2933 address_space_init(&address_space_memory, system_memory, "memory");
309cb471 2934
7267c094 2935 system_io = g_malloc(sizeof(*system_io));
3bb28b72
JK
2936 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2937 65536);
7dca8043 2938 address_space_init(&address_space_io, system_io, "I/O");
62152b8a
AK
2939}
2940
2941MemoryRegion *get_system_memory(void)
2942{
2943 return system_memory;
2944}
2945
309cb471
AK
2946MemoryRegion *get_system_io(void)
2947{
2948 return system_io;
2949}
2950
e2eef170
PB
2951#endif /* !defined(CONFIG_USER_ONLY) */
2952
13eb76e0
FB
2953/* physical memory access (slow version, mainly for debug) */
2954#if defined(CONFIG_USER_ONLY)
f17ec444 2955int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
a68fe89c 2956 uint8_t *buf, int len, int is_write)
13eb76e0
FB
2957{
2958 int l, flags;
2959 target_ulong page;
53a5960a 2960 void * p;
13eb76e0
FB
2961
2962 while (len > 0) {
2963 page = addr & TARGET_PAGE_MASK;
2964 l = (page + TARGET_PAGE_SIZE) - addr;
2965 if (l > len)
2966 l = len;
2967 flags = page_get_flags(page);
2968 if (!(flags & PAGE_VALID))
a68fe89c 2969 return -1;
13eb76e0
FB
2970 if (is_write) {
2971 if (!(flags & PAGE_WRITE))
a68fe89c 2972 return -1;
579a97f7 2973 /* XXX: this code should not depend on lock_user */
72fb7daa 2974 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
a68fe89c 2975 return -1;
72fb7daa
AJ
2976 memcpy(p, buf, l);
2977 unlock_user(p, addr, l);
13eb76e0
FB
2978 } else {
2979 if (!(flags & PAGE_READ))
a68fe89c 2980 return -1;
579a97f7 2981 /* XXX: this code should not depend on lock_user */
72fb7daa 2982 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
a68fe89c 2983 return -1;
72fb7daa 2984 memcpy(buf, p, l);
5b257578 2985 unlock_user(p, addr, 0);
13eb76e0
FB
2986 }
2987 len -= l;
2988 buf += l;
2989 addr += l;
2990 }
a68fe89c 2991 return 0;
13eb76e0 2992}
8df1cd07 2993
13eb76e0 2994#else
51d7a9eb 2995
845b6214 2996static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
a8170e5e 2997 hwaddr length)
51d7a9eb 2998{
e87f7778 2999 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
0878d0e1
PB
3000 addr += memory_region_get_ram_addr(mr);
3001
e87f7778
PB
3002 /* No early return if dirty_log_mask is or becomes 0, because
3003 * cpu_physical_memory_set_dirty_range will still call
3004 * xen_modified_memory.
3005 */
3006 if (dirty_log_mask) {
3007 dirty_log_mask =
3008 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
3009 }
3010 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
5aa1ef71 3011 assert(tcg_enabled());
ba051fb5 3012 tb_lock();
e87f7778 3013 tb_invalidate_phys_range(addr, addr + length);
ba051fb5 3014 tb_unlock();
e87f7778 3015 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
51d7a9eb 3016 }
e87f7778 3017 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
51d7a9eb
AP
3018}
3019
23326164 3020static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
82f2563f 3021{
e1622f4b 3022 unsigned access_size_max = mr->ops->valid.max_access_size;
23326164
RH
3023
3024 /* Regions are assumed to support 1-4 byte accesses unless
3025 otherwise specified. */
23326164
RH
3026 if (access_size_max == 0) {
3027 access_size_max = 4;
3028 }
3029
3030 /* Bound the maximum access by the alignment of the address. */
3031 if (!mr->ops->impl.unaligned) {
3032 unsigned align_size_max = addr & -addr;
3033 if (align_size_max != 0 && align_size_max < access_size_max) {
3034 access_size_max = align_size_max;
3035 }
82f2563f 3036 }
23326164
RH
3037
3038 /* Don't attempt accesses larger than the maximum. */
3039 if (l > access_size_max) {
3040 l = access_size_max;
82f2563f 3041 }
6554f5c0 3042 l = pow2floor(l);
23326164
RH
3043
3044 return l;
82f2563f
PB
3045}
3046
4840f10e 3047static bool prepare_mmio_access(MemoryRegion *mr)
125b3806 3048{
4840f10e
JK
3049 bool unlocked = !qemu_mutex_iothread_locked();
3050 bool release_lock = false;
3051
3052 if (unlocked && mr->global_locking) {
3053 qemu_mutex_lock_iothread();
3054 unlocked = false;
3055 release_lock = true;
3056 }
125b3806 3057 if (mr->flush_coalesced_mmio) {
4840f10e
JK
3058 if (unlocked) {
3059 qemu_mutex_lock_iothread();
3060 }
125b3806 3061 qemu_flush_coalesced_mmio_buffer();
4840f10e
JK
3062 if (unlocked) {
3063 qemu_mutex_unlock_iothread();
3064 }
125b3806 3065 }
4840f10e
JK
3066
3067 return release_lock;
125b3806
PB
3068}
3069
a203ac70 3070/* Called within RCU critical section. */
16620684
AK
3071static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
3072 MemTxAttrs attrs,
3073 const uint8_t *buf,
3074 int len, hwaddr addr1,
3075 hwaddr l, MemoryRegion *mr)
13eb76e0 3076{
13eb76e0 3077 uint8_t *ptr;
791af8c8 3078 uint64_t val;
3b643495 3079 MemTxResult result = MEMTX_OK;
4840f10e 3080 bool release_lock = false;
3b46e624 3081
a203ac70 3082 for (;;) {
eb7eeb88
PB
3083 if (!memory_access_is_direct(mr, true)) {
3084 release_lock |= prepare_mmio_access(mr);
3085 l = memory_access_size(mr, l, addr1);
3086 /* XXX: could force current_cpu to NULL to avoid
3087 potential bugs */
6d3ede54
PM
3088 val = ldn_p(buf, l);
3089 result |= memory_region_dispatch_write(mr, addr1, val, l, attrs);
13eb76e0 3090 } else {
eb7eeb88 3091 /* RAM case */
f5aa69bd 3092 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
eb7eeb88
PB
3093 memcpy(ptr, buf, l);
3094 invalidate_and_set_dirty(mr, addr1, l);
13eb76e0 3095 }
4840f10e
JK
3096
3097 if (release_lock) {
3098 qemu_mutex_unlock_iothread();
3099 release_lock = false;
3100 }
3101
13eb76e0
FB
3102 len -= l;
3103 buf += l;
3104 addr += l;
a203ac70
PB
3105
3106 if (!len) {
3107 break;
3108 }
3109
3110 l = len;
efa99a2f 3111 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
13eb76e0 3112 }
fd8aaa76 3113
3b643495 3114 return result;
13eb76e0 3115}
8df1cd07 3116
4c6ebbb3 3117/* Called from RCU critical section. */
16620684
AK
3118static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
3119 const uint8_t *buf, int len)
ac1970fb 3120{
eb7eeb88 3121 hwaddr l;
eb7eeb88
PB
3122 hwaddr addr1;
3123 MemoryRegion *mr;
3124 MemTxResult result = MEMTX_OK;
eb7eeb88 3125
4c6ebbb3 3126 l = len;
efa99a2f 3127 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
4c6ebbb3
PB
3128 result = flatview_write_continue(fv, addr, attrs, buf, len,
3129 addr1, l, mr);
a203ac70
PB
3130
3131 return result;
3132}
3133
3134/* Called within RCU critical section. */
16620684
AK
3135MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
3136 MemTxAttrs attrs, uint8_t *buf,
3137 int len, hwaddr addr1, hwaddr l,
3138 MemoryRegion *mr)
a203ac70
PB
3139{
3140 uint8_t *ptr;
3141 uint64_t val;
3142 MemTxResult result = MEMTX_OK;
3143 bool release_lock = false;
eb7eeb88 3144
a203ac70 3145 for (;;) {
eb7eeb88
PB
3146 if (!memory_access_is_direct(mr, false)) {
3147 /* I/O case */
3148 release_lock |= prepare_mmio_access(mr);
3149 l = memory_access_size(mr, l, addr1);
6d3ede54
PM
3150 result |= memory_region_dispatch_read(mr, addr1, &val, l, attrs);
3151 stn_p(buf, l, val);
eb7eeb88
PB
3152 } else {
3153 /* RAM case */
f5aa69bd 3154 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
eb7eeb88
PB
3155 memcpy(buf, ptr, l);
3156 }
3157
3158 if (release_lock) {
3159 qemu_mutex_unlock_iothread();
3160 release_lock = false;
3161 }
3162
3163 len -= l;
3164 buf += l;
3165 addr += l;
a203ac70
PB
3166
3167 if (!len) {
3168 break;
3169 }
3170
3171 l = len;
efa99a2f 3172 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
a203ac70
PB
3173 }
3174
3175 return result;
3176}
3177
b2a44fca
PB
3178/* Called from RCU critical section. */
3179static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
3180 MemTxAttrs attrs, uint8_t *buf, int len)
a203ac70
PB
3181{
3182 hwaddr l;
3183 hwaddr addr1;
3184 MemoryRegion *mr;
eb7eeb88 3185
b2a44fca 3186 l = len;
efa99a2f 3187 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
b2a44fca
PB
3188 return flatview_read_continue(fv, addr, attrs, buf, len,
3189 addr1, l, mr);
ac1970fb
AK
3190}
3191
b2a44fca
PB
3192MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3193 MemTxAttrs attrs, uint8_t *buf, int len)
3194{
3195 MemTxResult result = MEMTX_OK;
3196 FlatView *fv;
3197
3198 if (len > 0) {
3199 rcu_read_lock();
3200 fv = address_space_to_flatview(as);
3201 result = flatview_read(fv, addr, attrs, buf, len);
3202 rcu_read_unlock();
3203 }
3204
3205 return result;
3206}
3207
4c6ebbb3
PB
3208MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
3209 MemTxAttrs attrs,
3210 const uint8_t *buf, int len)
3211{
3212 MemTxResult result = MEMTX_OK;
3213 FlatView *fv;
3214
3215 if (len > 0) {
3216 rcu_read_lock();
3217 fv = address_space_to_flatview(as);
3218 result = flatview_write(fv, addr, attrs, buf, len);
3219 rcu_read_unlock();
3220 }
3221
3222 return result;
3223}
3224
db84fd97
PB
3225MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3226 uint8_t *buf, int len, bool is_write)
3227{
3228 if (is_write) {
3229 return address_space_write(as, addr, attrs, buf, len);
3230 } else {
3231 return address_space_read_full(as, addr, attrs, buf, len);
3232 }
3233}
3234
a8170e5e 3235void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
ac1970fb
AK
3236 int len, int is_write)
3237{
5c9eb028
PM
3238 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3239 buf, len, is_write);
ac1970fb
AK
3240}
3241
582b55a9
AG
3242enum write_rom_type {
3243 WRITE_DATA,
3244 FLUSH_CACHE,
3245};
3246
2a221651 3247static inline void cpu_physical_memory_write_rom_internal(AddressSpace *as,
582b55a9 3248 hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
d0ecd2aa 3249{
149f54b5 3250 hwaddr l;
d0ecd2aa 3251 uint8_t *ptr;
149f54b5 3252 hwaddr addr1;
5c8a00ce 3253 MemoryRegion *mr;
3b46e624 3254
41063e1e 3255 rcu_read_lock();
d0ecd2aa 3256 while (len > 0) {
149f54b5 3257 l = len;
bc6b1cec
PM
3258 mr = address_space_translate(as, addr, &addr1, &l, true,
3259 MEMTXATTRS_UNSPECIFIED);
3b46e624 3260
5c8a00ce
PB
3261 if (!(memory_region_is_ram(mr) ||
3262 memory_region_is_romd(mr))) {
b242e0e0 3263 l = memory_access_size(mr, l, addr1);
d0ecd2aa 3264 } else {
d0ecd2aa 3265 /* ROM/RAM case */
0878d0e1 3266 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
582b55a9
AG
3267 switch (type) {
3268 case WRITE_DATA:
3269 memcpy(ptr, buf, l);
845b6214 3270 invalidate_and_set_dirty(mr, addr1, l);
582b55a9
AG
3271 break;
3272 case FLUSH_CACHE:
3273 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
3274 break;
3275 }
d0ecd2aa
FB
3276 }
3277 len -= l;
3278 buf += l;
3279 addr += l;
3280 }
41063e1e 3281 rcu_read_unlock();
d0ecd2aa
FB
3282}
3283
582b55a9 3284/* used for ROM loading : can write in RAM and ROM */
2a221651 3285void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
582b55a9
AG
3286 const uint8_t *buf, int len)
3287{
2a221651 3288 cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
582b55a9
AG
3289}
3290
3291void cpu_flush_icache_range(hwaddr start, int len)
3292{
3293 /*
3294 * This function should do the same thing as an icache flush that was
3295 * triggered from within the guest. For TCG we are always cache coherent,
3296 * so there is no need to flush anything. For KVM / Xen we need to flush
3297 * the host's instruction cache at least.
3298 */
3299 if (tcg_enabled()) {
3300 return;
3301 }
3302
2a221651
EI
3303 cpu_physical_memory_write_rom_internal(&address_space_memory,
3304 start, NULL, len, FLUSH_CACHE);
582b55a9
AG
3305}
3306
6d16c2f8 3307typedef struct {
d3e71559 3308 MemoryRegion *mr;
6d16c2f8 3309 void *buffer;
a8170e5e
AK
3310 hwaddr addr;
3311 hwaddr len;
c2cba0ff 3312 bool in_use;
6d16c2f8
AL
3313} BounceBuffer;
3314
3315static BounceBuffer bounce;
3316
ba223c29 3317typedef struct MapClient {
e95205e1 3318 QEMUBH *bh;
72cf2d4f 3319 QLIST_ENTRY(MapClient) link;
ba223c29
AL
3320} MapClient;
3321
38e047b5 3322QemuMutex map_client_list_lock;
72cf2d4f
BS
3323static QLIST_HEAD(map_client_list, MapClient) map_client_list
3324 = QLIST_HEAD_INITIALIZER(map_client_list);
ba223c29 3325
e95205e1
FZ
3326static void cpu_unregister_map_client_do(MapClient *client)
3327{
3328 QLIST_REMOVE(client, link);
3329 g_free(client);
3330}
3331
33b6c2ed
FZ
3332static void cpu_notify_map_clients_locked(void)
3333{
3334 MapClient *client;
3335
3336 while (!QLIST_EMPTY(&map_client_list)) {
3337 client = QLIST_FIRST(&map_client_list);
e95205e1
FZ
3338 qemu_bh_schedule(client->bh);
3339 cpu_unregister_map_client_do(client);
33b6c2ed
FZ
3340 }
3341}
3342
e95205e1 3343void cpu_register_map_client(QEMUBH *bh)
ba223c29 3344{
7267c094 3345 MapClient *client = g_malloc(sizeof(*client));
ba223c29 3346
38e047b5 3347 qemu_mutex_lock(&map_client_list_lock);
e95205e1 3348 client->bh = bh;
72cf2d4f 3349 QLIST_INSERT_HEAD(&map_client_list, client, link);
33b6c2ed
FZ
3350 if (!atomic_read(&bounce.in_use)) {
3351 cpu_notify_map_clients_locked();
3352 }
38e047b5 3353 qemu_mutex_unlock(&map_client_list_lock);
ba223c29
AL
3354}
3355
38e047b5 3356void cpu_exec_init_all(void)
ba223c29 3357{
38e047b5 3358 qemu_mutex_init(&ram_list.mutex);
20bccb82
PM
3359 /* The data structures we set up here depend on knowing the page size,
3360 * so no more changes can be made after this point.
3361 * In an ideal world, nothing we did before we had finished the
3362 * machine setup would care about the target page size, and we could
3363 * do this much later, rather than requiring board models to state
3364 * up front what their requirements are.
3365 */
3366 finalize_target_page_bits();
38e047b5 3367 io_mem_init();
680a4783 3368 memory_map_init();
38e047b5 3369 qemu_mutex_init(&map_client_list_lock);
ba223c29
AL
3370}
3371
e95205e1 3372void cpu_unregister_map_client(QEMUBH *bh)
ba223c29
AL
3373{
3374 MapClient *client;
3375
e95205e1
FZ
3376 qemu_mutex_lock(&map_client_list_lock);
3377 QLIST_FOREACH(client, &map_client_list, link) {
3378 if (client->bh == bh) {
3379 cpu_unregister_map_client_do(client);
3380 break;
3381 }
ba223c29 3382 }
e95205e1 3383 qemu_mutex_unlock(&map_client_list_lock);
ba223c29
AL
3384}
3385
3386static void cpu_notify_map_clients(void)
3387{
38e047b5 3388 qemu_mutex_lock(&map_client_list_lock);
33b6c2ed 3389 cpu_notify_map_clients_locked();
38e047b5 3390 qemu_mutex_unlock(&map_client_list_lock);
ba223c29
AL
3391}
3392
16620684 3393static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
eace72b7 3394 bool is_write, MemTxAttrs attrs)
51644ab7 3395{
5c8a00ce 3396 MemoryRegion *mr;
51644ab7
PB
3397 hwaddr l, xlat;
3398
3399 while (len > 0) {
3400 l = len;
efa99a2f 3401 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
5c8a00ce
PB
3402 if (!memory_access_is_direct(mr, is_write)) {
3403 l = memory_access_size(mr, l, addr);
eace72b7 3404 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
51644ab7
PB
3405 return false;
3406 }
3407 }
3408
3409 len -= l;
3410 addr += l;
3411 }
3412 return true;
3413}
3414
16620684 3415bool address_space_access_valid(AddressSpace *as, hwaddr addr,
fddffa42
PM
3416 int len, bool is_write,
3417 MemTxAttrs attrs)
16620684 3418{
11e732a5
PB
3419 FlatView *fv;
3420 bool result;
3421
3422 rcu_read_lock();
3423 fv = address_space_to_flatview(as);
eace72b7 3424 result = flatview_access_valid(fv, addr, len, is_write, attrs);
11e732a5
PB
3425 rcu_read_unlock();
3426 return result;
16620684
AK
3427}
3428
715c31ec 3429static hwaddr
16620684 3430flatview_extend_translation(FlatView *fv, hwaddr addr,
53d0790d
PM
3431 hwaddr target_len,
3432 MemoryRegion *mr, hwaddr base, hwaddr len,
3433 bool is_write, MemTxAttrs attrs)
715c31ec
PB
3434{
3435 hwaddr done = 0;
3436 hwaddr xlat;
3437 MemoryRegion *this_mr;
3438
3439 for (;;) {
3440 target_len -= len;
3441 addr += len;
3442 done += len;
3443 if (target_len == 0) {
3444 return done;
3445 }
3446
3447 len = target_len;
16620684 3448 this_mr = flatview_translate(fv, addr, &xlat,
efa99a2f 3449 &len, is_write, attrs);
715c31ec
PB
3450 if (this_mr != mr || xlat != base + done) {
3451 return done;
3452 }
3453 }
3454}
3455
6d16c2f8
AL
3456/* Map a physical memory region into a host virtual address.
3457 * May map a subset of the requested range, given by and returned in *plen.
3458 * May return NULL if resources needed to perform the mapping are exhausted.
3459 * Use only for reads OR writes - not for read-modify-write operations.
ba223c29
AL
3460 * Use cpu_register_map_client() to know when retrying the map operation is
3461 * likely to succeed.
6d16c2f8 3462 */
ac1970fb 3463void *address_space_map(AddressSpace *as,
a8170e5e
AK
3464 hwaddr addr,
3465 hwaddr *plen,
f26404fb
PM
3466 bool is_write,
3467 MemTxAttrs attrs)
6d16c2f8 3468{
a8170e5e 3469 hwaddr len = *plen;
715c31ec
PB
3470 hwaddr l, xlat;
3471 MemoryRegion *mr;
e81bcda5 3472 void *ptr;
ad0c60fa 3473 FlatView *fv;
6d16c2f8 3474
e3127ae0
PB
3475 if (len == 0) {
3476 return NULL;
3477 }
38bee5dc 3478
e3127ae0 3479 l = len;
41063e1e 3480 rcu_read_lock();
ad0c60fa 3481 fv = address_space_to_flatview(as);
efa99a2f 3482 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
41063e1e 3483
e3127ae0 3484 if (!memory_access_is_direct(mr, is_write)) {
c2cba0ff 3485 if (atomic_xchg(&bounce.in_use, true)) {
41063e1e 3486 rcu_read_unlock();
e3127ae0 3487 return NULL;
6d16c2f8 3488 }
e85d9db5
KW
3489 /* Avoid unbounded allocations */
3490 l = MIN(l, TARGET_PAGE_SIZE);
3491 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
e3127ae0
PB
3492 bounce.addr = addr;
3493 bounce.len = l;
d3e71559
PB
3494
3495 memory_region_ref(mr);
3496 bounce.mr = mr;
e3127ae0 3497 if (!is_write) {
16620684 3498 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
5c9eb028 3499 bounce.buffer, l);
8ab934f9 3500 }
6d16c2f8 3501
41063e1e 3502 rcu_read_unlock();
e3127ae0
PB
3503 *plen = l;
3504 return bounce.buffer;
3505 }
3506
e3127ae0 3507
d3e71559 3508 memory_region_ref(mr);
16620684 3509 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
53d0790d 3510 l, is_write, attrs);
f5aa69bd 3511 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
e81bcda5
PB
3512 rcu_read_unlock();
3513
3514 return ptr;
6d16c2f8
AL
3515}
3516
ac1970fb 3517/* Unmaps a memory region previously mapped by address_space_map().
6d16c2f8
AL
3518 * Will also mark the memory as dirty if is_write == 1. access_len gives
3519 * the amount of memory that was actually read or written by the caller.
3520 */
a8170e5e
AK
3521void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3522 int is_write, hwaddr access_len)
6d16c2f8
AL
3523{
3524 if (buffer != bounce.buffer) {
d3e71559
PB
3525 MemoryRegion *mr;
3526 ram_addr_t addr1;
3527
07bdaa41 3528 mr = memory_region_from_host(buffer, &addr1);
d3e71559 3529 assert(mr != NULL);
6d16c2f8 3530 if (is_write) {
845b6214 3531 invalidate_and_set_dirty(mr, addr1, access_len);
6d16c2f8 3532 }
868bb33f 3533 if (xen_enabled()) {
e41d7c69 3534 xen_invalidate_map_cache_entry(buffer);
050a0ddf 3535 }
d3e71559 3536 memory_region_unref(mr);
6d16c2f8
AL
3537 return;
3538 }
3539 if (is_write) {
5c9eb028
PM
3540 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3541 bounce.buffer, access_len);
6d16c2f8 3542 }
f8a83245 3543 qemu_vfree(bounce.buffer);
6d16c2f8 3544 bounce.buffer = NULL;
d3e71559 3545 memory_region_unref(bounce.mr);
c2cba0ff 3546 atomic_mb_set(&bounce.in_use, false);
ba223c29 3547 cpu_notify_map_clients();
6d16c2f8 3548}
d0ecd2aa 3549
a8170e5e
AK
3550void *cpu_physical_memory_map(hwaddr addr,
3551 hwaddr *plen,
ac1970fb
AK
3552 int is_write)
3553{
f26404fb
PM
3554 return address_space_map(&address_space_memory, addr, plen, is_write,
3555 MEMTXATTRS_UNSPECIFIED);
ac1970fb
AK
3556}
3557
a8170e5e
AK
3558void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3559 int is_write, hwaddr access_len)
ac1970fb
AK
3560{
3561 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3562}
3563
0ce265ff
PB
3564#define ARG1_DECL AddressSpace *as
3565#define ARG1 as
3566#define SUFFIX
3567#define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3568#define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3569#define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3570#define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3571#define RCU_READ_LOCK(...) rcu_read_lock()
3572#define RCU_READ_UNLOCK(...) rcu_read_unlock()
3573#include "memory_ldst.inc.c"
1e78bcc1 3574
1f4e496e
PB
3575int64_t address_space_cache_init(MemoryRegionCache *cache,
3576 AddressSpace *as,
3577 hwaddr addr,
3578 hwaddr len,
3579 bool is_write)
3580{
48564041
PB
3581 AddressSpaceDispatch *d;
3582 hwaddr l;
3583 MemoryRegion *mr;
3584
3585 assert(len > 0);
3586
3587 l = len;
3588 cache->fv = address_space_get_flatview(as);
3589 d = flatview_to_dispatch(cache->fv);
3590 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3591
3592 mr = cache->mrs.mr;
3593 memory_region_ref(mr);
3594 if (memory_access_is_direct(mr, is_write)) {
53d0790d
PM
3595 /* We don't care about the memory attributes here as we're only
3596 * doing this if we found actual RAM, which behaves the same
3597 * regardless of attributes; so UNSPECIFIED is fine.
3598 */
48564041 3599 l = flatview_extend_translation(cache->fv, addr, len, mr,
53d0790d
PM
3600 cache->xlat, l, is_write,
3601 MEMTXATTRS_UNSPECIFIED);
48564041
PB
3602 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3603 } else {
3604 cache->ptr = NULL;
3605 }
3606
3607 cache->len = l;
3608 cache->is_write = is_write;
3609 return l;
1f4e496e
PB
3610}
3611
3612void address_space_cache_invalidate(MemoryRegionCache *cache,
3613 hwaddr addr,
3614 hwaddr access_len)
3615{
48564041
PB
3616 assert(cache->is_write);
3617 if (likely(cache->ptr)) {
3618 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3619 }
1f4e496e
PB
3620}
3621
3622void address_space_cache_destroy(MemoryRegionCache *cache)
3623{
48564041
PB
3624 if (!cache->mrs.mr) {
3625 return;
3626 }
3627
3628 if (xen_enabled()) {
3629 xen_invalidate_map_cache_entry(cache->ptr);
3630 }
3631 memory_region_unref(cache->mrs.mr);
3632 flatview_unref(cache->fv);
3633 cache->mrs.mr = NULL;
3634 cache->fv = NULL;
3635}
3636
3637/* Called from RCU critical section. This function has the same
3638 * semantics as address_space_translate, but it only works on a
3639 * predefined range of a MemoryRegion that was mapped with
3640 * address_space_cache_init.
3641 */
3642static inline MemoryRegion *address_space_translate_cached(
3643 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
bc6b1cec 3644 hwaddr *plen, bool is_write, MemTxAttrs attrs)
48564041
PB
3645{
3646 MemoryRegionSection section;
3647 MemoryRegion *mr;
3648 IOMMUMemoryRegion *iommu_mr;
3649 AddressSpace *target_as;
3650
3651 assert(!cache->ptr);
3652 *xlat = addr + cache->xlat;
3653
3654 mr = cache->mrs.mr;
3655 iommu_mr = memory_region_get_iommu(mr);
3656 if (!iommu_mr) {
3657 /* MMIO region. */
3658 return mr;
3659 }
3660
3661 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3662 NULL, is_write, true,
2f7b009c 3663 &target_as, attrs);
48564041
PB
3664 return section.mr;
3665}
3666
3667/* Called from RCU critical section. address_space_read_cached uses this
3668 * out of line function when the target is an MMIO or IOMMU region.
3669 */
3670void
3671address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3672 void *buf, int len)
3673{
3674 hwaddr addr1, l;
3675 MemoryRegion *mr;
3676
3677 l = len;
bc6b1cec
PM
3678 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3679 MEMTXATTRS_UNSPECIFIED);
48564041
PB
3680 flatview_read_continue(cache->fv,
3681 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3682 addr1, l, mr);
3683}
3684
3685/* Called from RCU critical section. address_space_write_cached uses this
3686 * out of line function when the target is an MMIO or IOMMU region.
3687 */
3688void
3689address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3690 const void *buf, int len)
3691{
3692 hwaddr addr1, l;
3693 MemoryRegion *mr;
3694
3695 l = len;
bc6b1cec
PM
3696 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3697 MEMTXATTRS_UNSPECIFIED);
48564041
PB
3698 flatview_write_continue(cache->fv,
3699 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3700 addr1, l, mr);
1f4e496e
PB
3701}
3702
3703#define ARG1_DECL MemoryRegionCache *cache
3704#define ARG1 cache
48564041
PB
3705#define SUFFIX _cached_slow
3706#define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3707#define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3708#define MAP_RAM(mr, ofs) (cache->ptr + (ofs - cache->xlat))
90c4fe5f 3709#define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
48564041
PB
3710#define RCU_READ_LOCK() ((void)0)
3711#define RCU_READ_UNLOCK() ((void)0)
1f4e496e
PB
3712#include "memory_ldst.inc.c"
3713
5e2972fd 3714/* virtual memory access for debug (includes writing to ROM) */
f17ec444 3715int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
b448f2f3 3716 uint8_t *buf, int len, int is_write)
13eb76e0
FB
3717{
3718 int l;
a8170e5e 3719 hwaddr phys_addr;
9b3c35e0 3720 target_ulong page;
13eb76e0 3721
79ca7a1b 3722 cpu_synchronize_state(cpu);
13eb76e0 3723 while (len > 0) {
5232e4c7
PM
3724 int asidx;
3725 MemTxAttrs attrs;
3726
13eb76e0 3727 page = addr & TARGET_PAGE_MASK;
5232e4c7
PM
3728 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3729 asidx = cpu_asidx_from_attrs(cpu, attrs);
13eb76e0
FB
3730 /* if no physical page mapped, return an error */
3731 if (phys_addr == -1)
3732 return -1;
3733 l = (page + TARGET_PAGE_SIZE) - addr;
3734 if (l > len)
3735 l = len;
5e2972fd 3736 phys_addr += (addr & ~TARGET_PAGE_MASK);
2e38847b 3737 if (is_write) {
5232e4c7
PM
3738 cpu_physical_memory_write_rom(cpu->cpu_ases[asidx].as,
3739 phys_addr, buf, l);
2e38847b 3740 } else {
5232e4c7
PM
3741 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3742 MEMTXATTRS_UNSPECIFIED,
5c9eb028 3743 buf, l, 0);
2e38847b 3744 }
13eb76e0
FB
3745 len -= l;
3746 buf += l;
3747 addr += l;
3748 }
3749 return 0;
3750}
038629a6
DDAG
3751
3752/*
3753 * Allows code that needs to deal with migration bitmaps etc to still be built
3754 * target independent.
3755 */
20afaed9 3756size_t qemu_target_page_size(void)
038629a6 3757{
20afaed9 3758 return TARGET_PAGE_SIZE;
038629a6
DDAG
3759}
3760
46d702b1
JQ
3761int qemu_target_page_bits(void)
3762{
3763 return TARGET_PAGE_BITS;
3764}
3765
3766int qemu_target_page_bits_min(void)
3767{
3768 return TARGET_PAGE_BITS_MIN;
3769}
a68fe89c 3770#endif
13eb76e0 3771
8e4a424b
BS
3772/*
3773 * A helper function for the _utterly broken_ virtio device model to find out if
3774 * it's running on a big endian machine. Don't do this at home kids!
3775 */
98ed8ecf
GK
3776bool target_words_bigendian(void);
3777bool target_words_bigendian(void)
8e4a424b
BS
3778{
3779#if defined(TARGET_WORDS_BIGENDIAN)
3780 return true;
3781#else
3782 return false;
3783#endif
3784}
3785
76f35538 3786#ifndef CONFIG_USER_ONLY
a8170e5e 3787bool cpu_physical_memory_is_io(hwaddr phys_addr)
76f35538 3788{
5c8a00ce 3789 MemoryRegion*mr;
149f54b5 3790 hwaddr l = 1;
41063e1e 3791 bool res;
76f35538 3792
41063e1e 3793 rcu_read_lock();
5c8a00ce 3794 mr = address_space_translate(&address_space_memory,
bc6b1cec
PM
3795 phys_addr, &phys_addr, &l, false,
3796 MEMTXATTRS_UNSPECIFIED);
76f35538 3797
41063e1e
PB
3798 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3799 rcu_read_unlock();
3800 return res;
76f35538 3801}
bd2fa51f 3802
e3807054 3803int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
bd2fa51f
MH
3804{
3805 RAMBlock *block;
e3807054 3806 int ret = 0;
bd2fa51f 3807
0dc3f44a 3808 rcu_read_lock();
99e15582 3809 RAMBLOCK_FOREACH(block) {
e3807054
DDAG
3810 ret = func(block->idstr, block->host, block->offset,
3811 block->used_length, opaque);
3812 if (ret) {
3813 break;
3814 }
bd2fa51f 3815 }
0dc3f44a 3816 rcu_read_unlock();
e3807054 3817 return ret;
bd2fa51f 3818}
d3a5038c 3819
b895de50
CLG
3820int qemu_ram_foreach_migratable_block(RAMBlockIterFunc func, void *opaque)
3821{
3822 RAMBlock *block;
3823 int ret = 0;
3824
3825 rcu_read_lock();
3826 RAMBLOCK_FOREACH(block) {
3827 if (!qemu_ram_is_migratable(block)) {
3828 continue;
3829 }
3830 ret = func(block->idstr, block->host, block->offset,
3831 block->used_length, opaque);
3832 if (ret) {
3833 break;
3834 }
3835 }
3836 rcu_read_unlock();
3837 return ret;
3838}
3839
d3a5038c
DDAG
3840/*
3841 * Unmap pages of memory from start to start+length such that
3842 * they a) read as 0, b) Trigger whatever fault mechanism
3843 * the OS provides for postcopy.
3844 * The pages must be unmapped by the end of the function.
3845 * Returns: 0 on success, none-0 on failure
3846 *
3847 */
3848int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3849{
3850 int ret = -1;
3851
3852 uint8_t *host_startaddr = rb->host + start;
3853
3854 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
3855 error_report("ram_block_discard_range: Unaligned start address: %p",
3856 host_startaddr);
3857 goto err;
3858 }
3859
3860 if ((start + length) <= rb->used_length) {
db144f70 3861 bool need_madvise, need_fallocate;
d3a5038c
DDAG
3862 uint8_t *host_endaddr = host_startaddr + length;
3863 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
3864 error_report("ram_block_discard_range: Unaligned end address: %p",
3865 host_endaddr);
3866 goto err;
3867 }
3868
3869 errno = ENOTSUP; /* If we are missing MADVISE etc */
3870
db144f70
DDAG
3871 /* The logic here is messy;
3872 * madvise DONTNEED fails for hugepages
3873 * fallocate works on hugepages and shmem
3874 */
3875 need_madvise = (rb->page_size == qemu_host_page_size);
3876 need_fallocate = rb->fd != -1;
3877 if (need_fallocate) {
3878 /* For a file, this causes the area of the file to be zero'd
3879 * if read, and for hugetlbfs also causes it to be unmapped
3880 * so a userfault will trigger.
e2fa71f5
DDAG
3881 */
3882#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3883 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3884 start, length);
db144f70
DDAG
3885 if (ret) {
3886 ret = -errno;
3887 error_report("ram_block_discard_range: Failed to fallocate "
3888 "%s:%" PRIx64 " +%zx (%d)",
3889 rb->idstr, start, length, ret);
3890 goto err;
3891 }
3892#else
3893 ret = -ENOSYS;
3894 error_report("ram_block_discard_range: fallocate not available/file"
3895 "%s:%" PRIx64 " +%zx (%d)",
3896 rb->idstr, start, length, ret);
3897 goto err;
e2fa71f5
DDAG
3898#endif
3899 }
db144f70
DDAG
3900 if (need_madvise) {
3901 /* For normal RAM this causes it to be unmapped,
3902 * for shared memory it causes the local mapping to disappear
3903 * and to fall back on the file contents (which we just
3904 * fallocate'd away).
3905 */
3906#if defined(CONFIG_MADVISE)
3907 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3908 if (ret) {
3909 ret = -errno;
3910 error_report("ram_block_discard_range: Failed to discard range "
3911 "%s:%" PRIx64 " +%zx (%d)",
3912 rb->idstr, start, length, ret);
3913 goto err;
3914 }
3915#else
3916 ret = -ENOSYS;
3917 error_report("ram_block_discard_range: MADVISE not available"
d3a5038c
DDAG
3918 "%s:%" PRIx64 " +%zx (%d)",
3919 rb->idstr, start, length, ret);
db144f70
DDAG
3920 goto err;
3921#endif
d3a5038c 3922 }
db144f70
DDAG
3923 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3924 need_madvise, need_fallocate, ret);
d3a5038c
DDAG
3925 } else {
3926 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3927 "/%zx/" RAM_ADDR_FMT")",
3928 rb->idstr, start, length, rb->used_length);
3929 }
3930
3931err:
3932 return ret;
3933}
3934
ec3f8c99 3935#endif
a0be0c58
YZ
3936
3937void page_size_init(void)
3938{
3939 /* NOTE: we can always suppose that qemu_host_page_size >=
3940 TARGET_PAGE_SIZE */
a0be0c58
YZ
3941 if (qemu_host_page_size == 0) {
3942 qemu_host_page_size = qemu_real_host_page_size;
3943 }
3944 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
3945 qemu_host_page_size = TARGET_PAGE_SIZE;
3946 }
3947 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;
3948}
5e8fd947
AK
3949
3950#if !defined(CONFIG_USER_ONLY)
3951
3952static void mtree_print_phys_entries(fprintf_function mon, void *f,
3953 int start, int end, int skip, int ptr)
3954{
3955 if (start == end - 1) {
3956 mon(f, "\t%3d ", start);
3957 } else {
3958 mon(f, "\t%3d..%-3d ", start, end - 1);
3959 }
3960 mon(f, " skip=%d ", skip);
3961 if (ptr == PHYS_MAP_NODE_NIL) {
3962 mon(f, " ptr=NIL");
3963 } else if (!skip) {
3964 mon(f, " ptr=#%d", ptr);
3965 } else {
3966 mon(f, " ptr=[%d]", ptr);
3967 }
3968 mon(f, "\n");
3969}
3970
3971#define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3972 int128_sub((size), int128_one())) : 0)
3973
3974void mtree_print_dispatch(fprintf_function mon, void *f,
3975 AddressSpaceDispatch *d, MemoryRegion *root)
3976{
3977 int i;
3978
3979 mon(f, " Dispatch\n");
3980 mon(f, " Physical sections\n");
3981
3982 for (i = 0; i < d->map.sections_nb; ++i) {
3983 MemoryRegionSection *s = d->map.sections + i;
3984 const char *names[] = { " [unassigned]", " [not dirty]",
3985 " [ROM]", " [watch]" };
3986
3987 mon(f, " #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx " %s%s%s%s%s",
3988 i,
3989 s->offset_within_address_space,
3990 s->offset_within_address_space + MR_SIZE(s->mr->size),
3991 s->mr->name ? s->mr->name : "(noname)",
3992 i < ARRAY_SIZE(names) ? names[i] : "",
3993 s->mr == root ? " [ROOT]" : "",
3994 s == d->mru_section ? " [MRU]" : "",
3995 s->mr->is_iommu ? " [iommu]" : "");
3996
3997 if (s->mr->alias) {
3998 mon(f, " alias=%s", s->mr->alias->name ?
3999 s->mr->alias->name : "noname");
4000 }
4001 mon(f, "\n");
4002 }
4003
4004 mon(f, " Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
4005 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
4006 for (i = 0; i < d->map.nodes_nb; ++i) {
4007 int j, jprev;
4008 PhysPageEntry prev;
4009 Node *n = d->map.nodes + i;
4010
4011 mon(f, " [%d]\n", i);
4012
4013 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
4014 PhysPageEntry *pe = *n + j;
4015
4016 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
4017 continue;
4018 }
4019
4020 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
4021
4022 jprev = j;
4023 prev = *pe;
4024 }
4025
4026 if (jprev != ARRAY_SIZE(*n)) {
4027 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
4028 }
4029 }
4030}
4031
4032#endif