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