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