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