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