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