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