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