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