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