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