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