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