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