blob: bda475a719d5d4db3b5773bc12b1c95287bad345 [file] [log] [blame]
bellard54936002003-05-13 00:25:15 +00001/*
Paolo Bonzinid9f24bf2020-10-06 09:05:29 +02002 * RAM allocation and memory access
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard54936002003-05-13 00:25:15 +00004 * 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
Chetan Pant61f3c912020-10-23 12:44:24 +00009 * version 2.1 of the License, or (at your option) any later version.
bellard54936002003-05-13 00:25:15 +000010 *
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
Blue Swirl8167ee82009-07-16 20:47:01 +000017 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
bellard54936002003-05-13 00:25:15 +000018 */
Markus Armbruster14a48c12019-05-23 16:35:05 +020019
Peter Maydell7b31bbc2016-01-26 18:16:56 +000020#include "qemu/osdep.h"
Marc-André Lureauec5f7ca2022-03-23 19:57:34 +040021#include "exec/page-vary.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010022#include "qapi/error.h"
bellard54936002003-05-13 00:25:15 +000023
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020024#include "qemu/cutils.h"
Richard Henderson084cfca2020-12-14 08:02:33 -060025#include "qemu/cacheflush.h"
Markus Armbrustere2c1c342022-12-21 14:35:49 +010026#include "qemu/hbitmap.h"
Peter Maydellb85ea5f2022-02-08 20:08:52 +000027#include "qemu/madvise.h"
Claudio Fontana78271682021-02-04 17:39:23 +010028
29#ifdef CONFIG_TCG
30#include "hw/core/tcg-cpu-ops.h"
31#endif /* CONFIG_TCG */
32
Paolo Bonzini63c91552016-03-15 13:18:37 +010033#include "exec/exec-all.h"
Juan Quintela51180422017-04-24 20:50:19 +020034#include "exec/target_page.h"
Paolo Bonzini741da0d2014-06-27 08:40:04 +020035#include "hw/qdev-core.h"
Fam Zhengc7e002c2017-07-14 10:15:08 +080036#include "hw/qdev-properties.h"
Marcel Apfelbaum47c8ca52015-02-04 17:43:54 +020037#include "hw/boards.h"
Paolo Bonzini33c11872016-03-15 16:58:45 +010038#include "hw/xen/xen.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010039#include "sysemu/kvm.h"
Markus Armbruster14a48c12019-05-23 16:35:05 +020040#include "sysemu/tcg.h"
Alexander Bulekova028ede2020-02-19 23:11:09 -050041#include "sysemu/qtest.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010042#include "qemu/timer.h"
43#include "qemu/config-file.h"
Andreas Färber75a34032013-09-02 16:57:02 +020044#include "qemu/error-report.h"
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +020045#include "qemu/qemu-print.h"
Philippe Mathieu-Daudé3ab6fdc2021-12-15 19:24:21 +010046#include "qemu/log.h"
Peter Maydell5df022c2022-02-26 18:07:23 +000047#include "qemu/memalign.h"
Paolo Bonzini741da0d2014-06-27 08:40:04 +020048#include "exec/memory.h"
Paolo Bonzinidf43d492016-03-16 10:24:54 +010049#include "exec/ioport.h"
Paolo Bonzini741da0d2014-06-27 08:40:04 +020050#include "sysemu/dma.h"
Markus Armbrusterb58c5c22019-08-12 07:23:55 +020051#include "sysemu/hostmem.h"
Christian Borntraeger79ca7a12017-03-07 15:19:08 +010052#include "sysemu/hw_accel.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010053#include "sysemu/xen-mapcache.h"
Paolo Bonzini243af022020-02-04 12:20:10 +010054#include "trace/trace-root.h"
Dr. David Alan Gilbertd3a50382017-02-24 18:28:32 +000055
Dr. David Alan Gilberte2fa71f2017-02-24 18:28:33 +000056#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
Dr. David Alan Gilberte2fa71f2017-02-24 18:28:33 +000057#include <linux/falloc.h>
58#endif
59
Mike Day0dc3f442013-09-05 14:41:35 -040060#include "qemu/rcu_queue.h"
Jan Kiszka4840f102015-06-18 18:47:22 +020061#include "qemu/main-loop.h"
Paolo Bonzini3b9bd3f2020-12-16 13:27:58 +010062#include "exec/translate-all.h"
Pavel Dovgalyuk76159362015-09-17 19:25:07 +030063#include "sysemu/replay.h"
Blue Swirl0cac1b62012-04-09 16:50:52 +000064
Paolo Bonzini022c62c2012-12-17 18:19:49 +010065#include "exec/memory-internal.h"
Juan Quintela220c3eb2013-10-14 17:13:59 +020066#include "exec/ram_addr.h"
Avi Kivity67d95c12011-12-15 15:25:22 +020067
Beata Michalska61c490e2019-11-21 00:08:41 +000068#include "qemu/pmem.h"
69
Bharata B Rao9dfeca72016-05-12 09:18:12 +053070#include "migration/vmstate.h"
71
Michael S. Tsirkinb35ba302013-11-11 17:52:07 +020072#include "qemu/range.h"
Michael S. Tsirkin794e8f32015-09-24 14:41:17 +030073#ifndef _WIN32
74#include "qemu/mmap-alloc.h"
75#endif
Michael S. Tsirkinb35ba302013-11-11 17:52:07 +020076
Peter Xube9b23c2017-05-12 12:17:41 +080077#include "monitor/monitor.h"
78
Jingqi Liuce317be2020-04-29 16:50:09 +080079#ifdef CONFIG_LIBDAXCTL
80#include <daxctl/libdaxctl.h>
81#endif
82
blueswir1db7b5422007-05-26 17:36:03 +000083//#define DEBUG_SUBPAGE
ths1196be32007-03-17 15:17:58 +000084
Mike Day0dc3f442013-09-05 14:41:35 -040085/* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
86 * are protected by the ramlist lock.
87 */
Mike Day0d53d9f2015-01-21 13:45:24 +010088RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
Avi Kivity62152b82011-07-26 14:26:14 +030089
90static MemoryRegion *system_memory;
Avi Kivity309cb472011-08-08 16:09:03 +030091static MemoryRegion *system_io;
Avi Kivity62152b82011-07-26 14:26:14 +030092
Avi Kivityf6790af2012-10-02 20:13:51 +020093AddressSpace address_space_io;
94AddressSpace address_space_memory;
Avi Kivity2673a5d2012-10-02 18:49:28 +020095
Jan Kiszkaacc9d802013-05-26 21:55:37 +020096static MemoryRegion io_mem_unassigned;
Avi Kivity4346ae32012-02-10 17:00:01 +020097
Paolo Bonzini1db8abb2013-05-21 12:07:21 +020098typedef struct PhysPageEntry PhysPageEntry;
99
100struct PhysPageEntry {
Michael S. Tsirkin9736e552013-11-11 14:42:43 +0200101 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
Michael S. Tsirkin8b795762013-11-11 14:51:56 +0200102 uint32_t skip : 6;
Michael S. Tsirkin9736e552013-11-11 14:42:43 +0200103 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
Michael S. Tsirkin8b795762013-11-11 14:51:56 +0200104 uint32_t ptr : 26;
Paolo Bonzini1db8abb2013-05-21 12:07:21 +0200105};
106
Michael S. Tsirkin8b795762013-11-11 14:51:56 +0200107#define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
108
Paolo Bonzini03f49952013-11-07 17:14:36 +0100109/* Size of the L2 (and L3, etc) page tables. */
Paolo Bonzini57271d62013-11-07 17:14:37 +0100110#define ADDR_SPACE_BITS 64
Paolo Bonzini03f49952013-11-07 17:14:36 +0100111
Michael S. Tsirkin026736c2013-11-13 20:13:03 +0200112#define P_L2_BITS 9
Paolo Bonzini03f49952013-11-07 17:14:36 +0100113#define P_L2_SIZE (1 << P_L2_BITS)
114
115#define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
116
117typedef PhysPageEntry Node[P_L2_SIZE];
Paolo Bonzini0475d942013-05-29 12:28:21 +0200118
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200119typedef struct PhysPageMap {
Paolo Bonzini79e2b9a2015-01-21 12:09:14 +0100120 struct rcu_head rcu;
121
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200122 unsigned sections_nb;
123 unsigned sections_nb_alloc;
124 unsigned nodes_nb;
125 unsigned nodes_nb_alloc;
126 Node *nodes;
127 MemoryRegionSection *sections;
128} PhysPageMap;
129
Paolo Bonzini1db8abb2013-05-21 12:07:21 +0200130struct AddressSpaceDispatch {
Fam Zheng729633c2016-03-01 14:18:24 +0800131 MemoryRegionSection *mru_section;
Paolo Bonzini1db8abb2013-05-21 12:07:21 +0200132 /* This is a multi-level map on the physical address space.
133 * The bottom level has pointers to MemoryRegionSections.
134 */
135 PhysPageEntry phys_map;
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200136 PhysPageMap map;
Paolo Bonzini1db8abb2013-05-21 12:07:21 +0200137};
138
Jan Kiszka90260c62013-05-26 21:46:51 +0200139#define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
140typedef struct subpage_t {
141 MemoryRegion iomem;
Alexey Kardashevskiy16620682017-09-21 18:50:58 +1000142 FlatView *fv;
Jan Kiszka90260c62013-05-26 21:46:51 +0200143 hwaddr base;
Vijaya Kumar K2615fab2016-10-24 16:26:49 +0100144 uint16_t sub_section[];
Jan Kiszka90260c62013-05-26 21:46:51 +0200145} subpage_t;
146
Liu Ping Fanb41aac42013-05-29 11:09:17 +0200147#define PHYS_SECTION_UNASSIGNED 0
Avi Kivity5312bd82012-02-12 18:32:55 +0200148
pbrooke2eef172008-06-08 01:09:01 +0000149static void io_mem_init(void);
Avi Kivity62152b82011-07-26 14:26:14 +0300150static void memory_map_init(void);
Paolo Bonzini9458a9a2018-02-06 18:37:39 +0100151static void tcg_log_global_after_sync(MemoryListener *listener);
Edgar E. Iglesias09daed82013-12-17 13:06:51 +1000152static void tcg_commit(MemoryListener *listener);
pbrooke2eef172008-06-08 01:09:01 +0000153
Peter Maydell32857f42015-10-01 15:29:50 +0100154/**
155 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
156 * @cpu: the CPU whose AddressSpace this is
157 * @as: the AddressSpace itself
158 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
159 * @tcg_as_listener: listener for tracking changes to the AddressSpace
160 */
161struct CPUAddressSpace {
162 CPUState *cpu;
163 AddressSpace *as;
164 struct AddressSpaceDispatch *memory_dispatch;
165 MemoryListener tcg_as_listener;
166};
167
Gerd Hoffmann8deaf122017-04-21 11:16:25 +0200168struct DirtyBitmapSnapshot {
169 ram_addr_t start;
170 ram_addr_t end;
171 unsigned long dirty[];
172};
173
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200174static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
Avi Kivityf7bf5462012-02-13 20:12:05 +0200175{
Peter Lieven101420b2016-07-15 12:03:50 +0200176 static unsigned alloc_hint = 16;
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200177 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
Wei Yangc95cfd02019-03-21 16:25:52 +0800178 map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200179 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
Peter Lieven101420b2016-07-15 12:03:50 +0200180 alloc_hint = map->nodes_nb_alloc;
Avi Kivityf7bf5462012-02-13 20:12:05 +0200181 }
182}
183
Paolo Bonzinidb946042015-05-21 15:12:29 +0200184static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
Avi Kivityd6f2ea22012-02-12 20:12:49 +0200185{
186 unsigned i;
Michael S. Tsirkin8b795762013-11-11 14:51:56 +0200187 uint32_t ret;
Paolo Bonzinidb946042015-05-21 15:12:29 +0200188 PhysPageEntry e;
189 PhysPageEntry *p;
Avi Kivityd6f2ea22012-02-12 20:12:49 +0200190
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200191 ret = map->nodes_nb++;
Paolo Bonzinidb946042015-05-21 15:12:29 +0200192 p = map->nodes[ret];
Avi Kivityd6f2ea22012-02-12 20:12:49 +0200193 assert(ret != PHYS_MAP_NODE_NIL);
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200194 assert(ret != map->nodes_nb_alloc);
Paolo Bonzinidb946042015-05-21 15:12:29 +0200195
196 e.skip = leaf ? 0 : 1;
197 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
Paolo Bonzini03f49952013-11-07 17:14:36 +0100198 for (i = 0; i < P_L2_SIZE; ++i) {
Paolo Bonzinidb946042015-05-21 15:12:29 +0200199 memcpy(&p[i], &e, sizeof(e));
Avi Kivityd6f2ea22012-02-12 20:12:49 +0200200 }
Avi Kivityf7bf5462012-02-13 20:12:05 +0200201 return ret;
Avi Kivityd6f2ea22012-02-12 20:12:49 +0200202}
203
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200204static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
Wei Yang56b15072019-03-21 16:25:50 +0800205 hwaddr *index, uint64_t *nb, uint16_t leaf,
Avi Kivity29990972012-02-13 20:21:20 +0200206 int level)
Avi Kivityf7bf5462012-02-13 20:12:05 +0200207{
208 PhysPageEntry *p;
Paolo Bonzini03f49952013-11-07 17:14:36 +0100209 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
Avi Kivityf7bf5462012-02-13 20:12:05 +0200210
Michael S. Tsirkin9736e552013-11-11 14:42:43 +0200211 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
Paolo Bonzinidb946042015-05-21 15:12:29 +0200212 lp->ptr = phys_map_node_alloc(map, level == 0);
Avi Kivityf7bf5462012-02-13 20:12:05 +0200213 }
Paolo Bonzinidb946042015-05-21 15:12:29 +0200214 p = map->nodes[lp->ptr];
Paolo Bonzini03f49952013-11-07 17:14:36 +0100215 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
Avi Kivityf7bf5462012-02-13 20:12:05 +0200216
Paolo Bonzini03f49952013-11-07 17:14:36 +0100217 while (*nb && lp < &p[P_L2_SIZE]) {
Avi Kivity07f07b32012-02-13 20:45:32 +0200218 if ((*index & (step - 1)) == 0 && *nb >= step) {
Michael S. Tsirkin9736e552013-11-11 14:42:43 +0200219 lp->skip = 0;
Avi Kivityc19e8802012-02-13 20:25:31 +0200220 lp->ptr = leaf;
Avi Kivity07f07b32012-02-13 20:45:32 +0200221 *index += step;
222 *nb -= step;
Avi Kivity29990972012-02-13 20:21:20 +0200223 } else {
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200224 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
Avi Kivity29990972012-02-13 20:21:20 +0200225 }
226 ++lp;
Avi Kivityf7bf5462012-02-13 20:12:05 +0200227 }
228}
229
Avi Kivityac1970f2012-10-03 16:22:53 +0200230static void phys_page_set(AddressSpaceDispatch *d,
Wei Yang56b15072019-03-21 16:25:50 +0800231 hwaddr index, uint64_t nb,
Avi Kivity29990972012-02-13 20:21:20 +0200232 uint16_t leaf)
bellard92e873b2004-05-21 14:52:29 +0000233{
Avi Kivity29990972012-02-13 20:21:20 +0200234 /* Wildly overreserve - it doesn't matter much. */
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200235 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
bellard92e873b2004-05-21 14:52:29 +0000236
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200237 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
bellard92e873b2004-05-21 14:52:29 +0000238}
239
Michael S. Tsirkinb35ba302013-11-11 17:52:07 +0200240/* Compact a non leaf page entry. Simply detect that the entry has a single child,
241 * and update our entry so we can skip it and go directly to the destination.
242 */
Marc-André Lureauefee6782016-09-28 16:37:20 +0400243static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
Michael S. Tsirkinb35ba302013-11-11 17:52:07 +0200244{
245 unsigned valid_ptr = P_L2_SIZE;
246 int valid = 0;
247 PhysPageEntry *p;
248 int i;
249
250 if (lp->ptr == PHYS_MAP_NODE_NIL) {
251 return;
252 }
253
254 p = nodes[lp->ptr];
255 for (i = 0; i < P_L2_SIZE; i++) {
256 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
257 continue;
258 }
259
260 valid_ptr = i;
261 valid++;
262 if (p[i].skip) {
Marc-André Lureauefee6782016-09-28 16:37:20 +0400263 phys_page_compact(&p[i], nodes);
Michael S. Tsirkinb35ba302013-11-11 17:52:07 +0200264 }
265 }
266
267 /* We can only compress if there's only one child. */
268 if (valid != 1) {
269 return;
270 }
271
272 assert(valid_ptr < P_L2_SIZE);
273
274 /* Don't compress if it won't fit in the # of bits we have. */
Wei Yang526ca232019-03-21 16:25:55 +0800275 if (P_L2_LEVELS >= (1 << 6) &&
276 lp->skip + p[valid_ptr].skip >= (1 << 6)) {
Michael S. Tsirkinb35ba302013-11-11 17:52:07 +0200277 return;
278 }
279
280 lp->ptr = p[valid_ptr].ptr;
281 if (!p[valid_ptr].skip) {
282 /* If our only child is a leaf, make this a leaf. */
283 /* By design, we should have made this node a leaf to begin with so we
284 * should never reach here.
285 * But since it's so simple to handle this, let's do it just in case we
286 * change this rule.
287 */
288 lp->skip = 0;
289 } else {
290 lp->skip += p[valid_ptr].skip;
291 }
292}
293
Alexey Kardashevskiy8629d3f2017-09-21 18:51:00 +1000294void address_space_dispatch_compact(AddressSpaceDispatch *d)
Michael S. Tsirkinb35ba302013-11-11 17:52:07 +0200295{
Michael S. Tsirkinb35ba302013-11-11 17:52:07 +0200296 if (d->phys_map.skip) {
Marc-André Lureauefee6782016-09-28 16:37:20 +0400297 phys_page_compact(&d->phys_map, d->map.nodes);
Michael S. Tsirkinb35ba302013-11-11 17:52:07 +0200298 }
299}
300
Fam Zheng29cb5332016-03-01 14:18:23 +0800301static inline bool section_covers_addr(const MemoryRegionSection *section,
302 hwaddr addr)
303{
304 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
305 * the section must cover the entire address space.
306 */
Richard Henderson258dfaa2016-06-29 15:48:03 -0700307 return int128_gethi(section->size) ||
Fam Zheng29cb5332016-03-01 14:18:23 +0800308 range_covers_byte(section->offset_within_address_space,
Richard Henderson258dfaa2016-06-29 15:48:03 -0700309 int128_getlo(section->size), addr);
Fam Zheng29cb5332016-03-01 14:18:23 +0800310}
311
Peter Xu003a0cf2017-05-15 16:50:57 +0800312static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
bellard92e873b2004-05-21 14:52:29 +0000313{
Peter Xu003a0cf2017-05-15 16:50:57 +0800314 PhysPageEntry lp = d->phys_map, *p;
315 Node *nodes = d->map.nodes;
316 MemoryRegionSection *sections = d->map.sections;
Michael S. Tsirkin97115a82013-11-13 20:08:19 +0200317 hwaddr index = addr >> TARGET_PAGE_BITS;
Avi Kivity31ab2b42012-02-13 16:44:19 +0200318 int i;
Avi Kivityf1f6e3b2011-11-20 17:52:22 +0200319
Michael S. Tsirkin9736e552013-11-11 14:42:43 +0200320 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
Avi Kivityc19e8802012-02-13 20:25:31 +0200321 if (lp.ptr == PHYS_MAP_NODE_NIL) {
Paolo Bonzini9affd6f2013-05-29 12:09:47 +0200322 return &sections[PHYS_SECTION_UNASSIGNED];
Avi Kivity31ab2b42012-02-13 16:44:19 +0200323 }
Paolo Bonzini9affd6f2013-05-29 12:09:47 +0200324 p = nodes[lp.ptr];
Paolo Bonzini03f49952013-11-07 17:14:36 +0100325 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
Avi Kivityf1f6e3b2011-11-20 17:52:22 +0200326 }
Michael S. Tsirkinb35ba302013-11-11 17:52:07 +0200327
Fam Zheng29cb5332016-03-01 14:18:23 +0800328 if (section_covers_addr(&sections[lp.ptr], addr)) {
Michael S. Tsirkinb35ba302013-11-11 17:52:07 +0200329 return &sections[lp.ptr];
330 } else {
331 return &sections[PHYS_SECTION_UNASSIGNED];
332 }
Avi Kivityf3705d52012-03-08 16:16:34 +0200333}
334
Paolo Bonzini79e2b9a2015-01-21 12:09:14 +0100335/* Called from RCU critical section */
Paolo Bonzinic7086b42013-06-02 15:27:39 +0200336static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
Jan Kiszka90260c62013-05-26 21:46:51 +0200337 hwaddr addr,
338 bool resolve_subpage)
Jan Kiszka9f029602013-05-06 16:48:02 +0200339{
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100340 MemoryRegionSection *section = qatomic_read(&d->mru_section);
Jan Kiszka90260c62013-05-26 21:46:51 +0200341 subpage_t *subpage;
342
Paolo Bonzini07c114b2017-11-15 15:11:03 +0100343 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
344 !section_covers_addr(section, addr)) {
Peter Xu003a0cf2017-05-15 16:50:57 +0800345 section = phys_page_find(d, addr);
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100346 qatomic_set(&d->mru_section, section);
Fam Zheng729633c2016-03-01 14:18:24 +0800347 }
Jan Kiszka90260c62013-05-26 21:46:51 +0200348 if (resolve_subpage && section->mr->subpage) {
349 subpage = container_of(section->mr, subpage_t, iomem);
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200350 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
Jan Kiszka90260c62013-05-26 21:46:51 +0200351 }
352 return section;
Jan Kiszka9f029602013-05-06 16:48:02 +0200353}
354
Paolo Bonzini79e2b9a2015-01-21 12:09:14 +0100355/* Called from RCU critical section */
Jan Kiszka90260c62013-05-26 21:46:51 +0200356static MemoryRegionSection *
Paolo Bonzinic7086b42013-06-02 15:27:39 +0200357address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
Jan Kiszka90260c62013-05-26 21:46:51 +0200358 hwaddr *plen, bool resolve_subpage)
Paolo Bonzini149f54b2013-05-24 12:59:37 +0200359{
360 MemoryRegionSection *section;
Paolo Bonzini965eb2f2015-06-17 10:40:27 +0200361 MemoryRegion *mr;
Paolo Bonzinia87f3952014-02-07 15:47:46 +0100362 Int128 diff;
Paolo Bonzini149f54b2013-05-24 12:59:37 +0200363
Paolo Bonzinic7086b42013-06-02 15:27:39 +0200364 section = address_space_lookup_region(d, addr, resolve_subpage);
Paolo Bonzini149f54b2013-05-24 12:59:37 +0200365 /* Compute offset within MemoryRegionSection */
366 addr -= section->offset_within_address_space;
367
368 /* Compute offset within MemoryRegion */
369 *xlat = addr + section->offset_within_region;
370
Paolo Bonzini965eb2f2015-06-17 10:40:27 +0200371 mr = section->mr;
Paolo Bonzinib242e0e2015-07-04 00:24:51 +0200372
373 /* MMIO registers can be expected to perform full-width accesses based only
374 * on their address, without considering adjacent registers that could
375 * decode to completely different MemoryRegions. When such registers
376 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
377 * regions overlap wildly. For this reason we cannot clamp the accesses
378 * here.
379 *
380 * If the length is small (as is the case for address_space_ldl/stl),
381 * everything works fine. If the incoming length is large, however,
382 * the caller really has to do the clamping through memory_access_size.
383 */
Paolo Bonzini965eb2f2015-06-17 10:40:27 +0200384 if (memory_region_is_ram(mr)) {
Paolo Bonzinie4a511f2015-06-17 10:36:54 +0200385 diff = int128_sub(section->size, int128_make64(addr));
Paolo Bonzini965eb2f2015-06-17 10:40:27 +0200386 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
387 }
Paolo Bonzini149f54b2013-05-24 12:59:37 +0200388 return section;
389}
Jan Kiszka90260c62013-05-26 21:46:51 +0200390
Peter Xud5e5faf2017-10-10 11:42:45 +0200391/**
Paolo Bonzinia411c842018-03-03 17:24:04 +0100392 * address_space_translate_iommu - translate an address through an IOMMU
393 * memory region and then through the target address space.
394 *
395 * @iommu_mr: the IOMMU memory region that we start the translation from
396 * @addr: the address to be translated through the MMU
397 * @xlat: the translated address offset within the destination memory region.
398 * It cannot be %NULL.
399 * @plen_out: valid read/write length of the translated address. It
400 * cannot be %NULL.
401 * @page_mask_out: page mask for the translated address. This
402 * should only be meaningful for IOMMU translated
403 * addresses, since there may be huge pages that this bit
404 * would tell. It can be %NULL if we don't care about it.
405 * @is_write: whether the translation operation is for write
406 * @is_mmio: whether this can be MMIO, set true if it can
407 * @target_as: the address space targeted by the IOMMU
Peter Maydell2f7b0092018-05-31 14:50:53 +0100408 * @attrs: transaction attributes
Paolo Bonzinia411c842018-03-03 17:24:04 +0100409 *
410 * This function is called from RCU critical section. It is the common
411 * part of flatview_do_translate and address_space_translate_cached.
412 */
413static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
414 hwaddr *xlat,
415 hwaddr *plen_out,
416 hwaddr *page_mask_out,
417 bool is_write,
418 bool is_mmio,
Peter Maydell2f7b0092018-05-31 14:50:53 +0100419 AddressSpace **target_as,
420 MemTxAttrs attrs)
Paolo Bonzinia411c842018-03-03 17:24:04 +0100421{
422 MemoryRegionSection *section;
423 hwaddr page_mask = (hwaddr)-1;
424
425 do {
426 hwaddr addr = *xlat;
427 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
Peter Maydell2c91bcf2018-06-15 14:57:16 +0100428 int iommu_idx = 0;
429 IOMMUTLBEntry iotlb;
430
431 if (imrc->attrs_to_index) {
432 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
433 }
434
435 iotlb = imrc->translate(iommu_mr, addr, is_write ?
436 IOMMU_WO : IOMMU_RO, iommu_idx);
Paolo Bonzinia411c842018-03-03 17:24:04 +0100437
438 if (!(iotlb.perm & (1 << is_write))) {
439 goto unassigned;
440 }
441
442 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
443 | (addr & iotlb.addr_mask));
444 page_mask &= iotlb.addr_mask;
445 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
446 *target_as = iotlb.target_as;
447
448 section = address_space_translate_internal(
449 address_space_to_dispatch(iotlb.target_as), addr, xlat,
450 plen_out, is_mmio);
451
452 iommu_mr = memory_region_get_iommu(section->mr);
453 } while (unlikely(iommu_mr));
454
455 if (page_mask_out) {
456 *page_mask_out = page_mask;
457 }
458 return *section;
459
460unassigned:
461 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
462}
463
464/**
Peter Xud5e5faf2017-10-10 11:42:45 +0200465 * flatview_do_translate - translate an address in FlatView
466 *
467 * @fv: the flat view that we want to translate on
468 * @addr: the address to be translated in above address space
469 * @xlat: the translated address offset within memory region. It
470 * cannot be @NULL.
471 * @plen_out: valid read/write length of the translated address. It
472 * can be @NULL when we don't care about it.
473 * @page_mask_out: page mask for the translated address. This
474 * should only be meaningful for IOMMU translated
475 * addresses, since there may be huge pages that this bit
476 * would tell. It can be @NULL if we don't care about it.
477 * @is_write: whether the translation operation is for write
478 * @is_mmio: whether this can be MMIO, set true if it can
Paolo Bonziniad2804d2018-04-17 11:39:35 +0200479 * @target_as: the address space targeted by the IOMMU
Peter Maydell49e14aa2018-05-31 14:50:53 +0100480 * @attrs: memory transaction attributes
Peter Xud5e5faf2017-10-10 11:42:45 +0200481 *
482 * This function is called from RCU critical section
483 */
Alexey Kardashevskiy16620682017-09-21 18:50:58 +1000484static MemoryRegionSection flatview_do_translate(FlatView *fv,
485 hwaddr addr,
486 hwaddr *xlat,
Peter Xud5e5faf2017-10-10 11:42:45 +0200487 hwaddr *plen_out,
488 hwaddr *page_mask_out,
Alexey Kardashevskiy16620682017-09-21 18:50:58 +1000489 bool is_write,
490 bool is_mmio,
Peter Maydell49e14aa2018-05-31 14:50:53 +0100491 AddressSpace **target_as,
492 MemTxAttrs attrs)
Jan Kiszka90260c62013-05-26 21:46:51 +0200493{
Avi Kivity30951152012-10-30 13:47:46 +0200494 MemoryRegionSection *section;
Alexey Kardashevskiy3df9d742017-07-11 13:56:19 +1000495 IOMMUMemoryRegion *iommu_mr;
Peter Xud5e5faf2017-10-10 11:42:45 +0200496 hwaddr plen = (hwaddr)(-1);
497
Paolo Bonziniad2804d2018-04-17 11:39:35 +0200498 if (!plen_out) {
499 plen_out = &plen;
Peter Xud5e5faf2017-10-10 11:42:45 +0200500 }
Avi Kivity30951152012-10-30 13:47:46 +0200501
Paolo Bonzinia411c842018-03-03 17:24:04 +0100502 section = address_space_translate_internal(
503 flatview_to_dispatch(fv), addr, xlat,
504 plen_out, is_mmio);
Avi Kivity30951152012-10-30 13:47:46 +0200505
Paolo Bonzinia411c842018-03-03 17:24:04 +0100506 iommu_mr = memory_region_get_iommu(section->mr);
507 if (unlikely(iommu_mr)) {
508 return address_space_translate_iommu(iommu_mr, xlat,
509 plen_out, page_mask_out,
510 is_write, is_mmio,
Peter Maydell2f7b0092018-05-31 14:50:53 +0100511 target_as, attrs);
Avi Kivity30951152012-10-30 13:47:46 +0200512 }
Peter Xud5e5faf2017-10-10 11:42:45 +0200513 if (page_mask_out) {
Paolo Bonzinia411c842018-03-03 17:24:04 +0100514 /* Not behind an IOMMU, use default page size. */
515 *page_mask_out = ~TARGET_PAGE_MASK;
Peter Xud5e5faf2017-10-10 11:42:45 +0200516 }
517
Peter Xua7640402017-05-17 16:57:42 +0800518 return *section;
Peter Xua7640402017-05-17 16:57:42 +0800519}
520
521/* Called from RCU critical section */
522IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
Peter Maydell7446eb02018-05-31 14:50:53 +0100523 bool is_write, MemTxAttrs attrs)
Peter Xua7640402017-05-17 16:57:42 +0800524{
525 MemoryRegionSection section;
Peter Xu076a93d2017-10-10 11:42:46 +0200526 hwaddr xlat, page_mask;
Peter Xua7640402017-05-17 16:57:42 +0800527
Peter Xu076a93d2017-10-10 11:42:46 +0200528 /*
529 * This can never be MMIO, and we don't really care about plen,
530 * but page mask.
531 */
532 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
Peter Maydell49e14aa2018-05-31 14:50:53 +0100533 NULL, &page_mask, is_write, false, &as,
534 attrs);
Peter Xua7640402017-05-17 16:57:42 +0800535
536 /* Illegal translation */
537 if (section.mr == &io_mem_unassigned) {
538 goto iotlb_fail;
539 }
540
541 /* Convert memory region offset into address space offset */
542 xlat += section.offset_within_address_space -
543 section.offset_within_region;
544
Peter Xua7640402017-05-17 16:57:42 +0800545 return (IOMMUTLBEntry) {
Alexey Kardashevskiye76bb182017-09-21 18:50:53 +1000546 .target_as = as,
Peter Xu076a93d2017-10-10 11:42:46 +0200547 .iova = addr & ~page_mask,
548 .translated_addr = xlat & ~page_mask,
549 .addr_mask = page_mask,
Peter Xua7640402017-05-17 16:57:42 +0800550 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
551 .perm = IOMMU_RW,
552 };
553
554iotlb_fail:
555 return (IOMMUTLBEntry) {0};
556}
557
558/* Called from RCU critical section */
Alexey Kardashevskiy16620682017-09-21 18:50:58 +1000559MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
Peter Maydellefa99a22018-05-31 14:50:52 +0100560 hwaddr *plen, bool is_write,
561 MemTxAttrs attrs)
Peter Xua7640402017-05-17 16:57:42 +0800562{
563 MemoryRegion *mr;
564 MemoryRegionSection section;
Alexey Kardashevskiy16620682017-09-21 18:50:58 +1000565 AddressSpace *as = NULL;
Peter Xua7640402017-05-17 16:57:42 +0800566
567 /* This can be MMIO, so setup MMIO bit. */
Peter Xud5e5faf2017-10-10 11:42:45 +0200568 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
Peter Maydell49e14aa2018-05-31 14:50:53 +0100569 is_write, true, &as, attrs);
Peter Xua7640402017-05-17 16:57:42 +0800570 mr = section.mr;
571
Alexey Kardashevskiyfe680d02014-05-07 13:40:39 +0000572 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
Paolo Bonzinia87f3952014-02-07 15:47:46 +0100573 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
Peter Crosthwaite23820db2015-03-16 22:35:54 -0700574 *plen = MIN(page, *plen);
Paolo Bonzinia87f3952014-02-07 15:47:46 +0100575 }
576
Avi Kivity30951152012-10-30 13:47:46 +0200577 return mr;
Jan Kiszka90260c62013-05-26 21:46:51 +0200578}
579
Peter Maydell1f871c52018-06-15 14:57:16 +0100580typedef struct TCGIOMMUNotifier {
581 IOMMUNotifier n;
582 MemoryRegion *mr;
583 CPUState *cpu;
584 int iommu_idx;
585 bool active;
586} TCGIOMMUNotifier;
587
588static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
589{
590 TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
591
592 if (!notifier->active) {
593 return;
594 }
595 tlb_flush(notifier->cpu);
596 notifier->active = false;
597 /* We leave the notifier struct on the list to avoid reallocating it later.
598 * Generally the number of IOMMUs a CPU deals with will be small.
599 * In any case we can't unregister the iommu notifier from a notify
600 * callback.
601 */
602}
603
604static void tcg_register_iommu_notifier(CPUState *cpu,
605 IOMMUMemoryRegion *iommu_mr,
606 int iommu_idx)
607{
608 /* Make sure this CPU has an IOMMU notifier registered for this
609 * IOMMU/IOMMU index combination, so that we can flush its TLB
610 * when the IOMMU tells us the mappings we've cached have changed.
611 */
612 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
Philippe Mathieu-Daudébbf90192021-01-17 18:04:11 +0100613 TCGIOMMUNotifier *notifier = NULL;
Markus Armbruster805d4492020-07-22 10:40:48 +0200614 int i;
Peter Maydell1f871c52018-06-15 14:57:16 +0100615
616 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
Peter Maydell5601be32019-02-01 14:55:45 +0000617 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
Peter Maydell1f871c52018-06-15 14:57:16 +0100618 if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
619 break;
620 }
621 }
622 if (i == cpu->iommu_notifiers->len) {
623 /* Not found, add a new entry at the end of the array */
624 cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
Peter Maydell5601be32019-02-01 14:55:45 +0000625 notifier = g_new0(TCGIOMMUNotifier, 1);
626 g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
Peter Maydell1f871c52018-06-15 14:57:16 +0100627
628 notifier->mr = mr;
629 notifier->iommu_idx = iommu_idx;
630 notifier->cpu = cpu;
631 /* Rather than trying to register interest in the specific part
632 * of the iommu's address space that we've accessed and then
633 * expand it later as subsequent accesses touch more of it, we
634 * just register interest in the whole thing, on the assumption
635 * that iommu reconfiguration will be rare.
636 */
637 iommu_notifier_init(&notifier->n,
638 tcg_iommu_unmap_notify,
639 IOMMU_NOTIFIER_UNMAP,
640 0,
641 HWADDR_MAX,
642 iommu_idx);
Markus Armbruster805d4492020-07-22 10:40:48 +0200643 memory_region_register_iommu_notifier(notifier->mr, &notifier->n,
644 &error_fatal);
Peter Maydell1f871c52018-06-15 14:57:16 +0100645 }
646
647 if (!notifier->active) {
648 notifier->active = true;
649 }
650}
651
Paolo Bonzinid9f24bf2020-10-06 09:05:29 +0200652void tcg_iommu_free_notifier_list(CPUState *cpu)
Peter Maydell1f871c52018-06-15 14:57:16 +0100653{
654 /* Destroy the CPU's notifier list */
655 int i;
656 TCGIOMMUNotifier *notifier;
657
658 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
Peter Maydell5601be32019-02-01 14:55:45 +0000659 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
Peter Maydell1f871c52018-06-15 14:57:16 +0100660 memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
Peter Maydell5601be32019-02-01 14:55:45 +0000661 g_free(notifier);
Peter Maydell1f871c52018-06-15 14:57:16 +0100662 }
663 g_array_free(cpu->iommu_notifiers, true);
664}
665
Paolo Bonzinid9f24bf2020-10-06 09:05:29 +0200666void tcg_iommu_init_notifier_list(CPUState *cpu)
667{
668 cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
669}
670
Paolo Bonzini79e2b9a2015-01-21 12:09:14 +0100671/* Called from RCU critical section */
Jan Kiszka90260c62013-05-26 21:46:51 +0200672MemoryRegionSection *
Richard Henderson418ade72022-06-21 08:38:29 -0700673address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr orig_addr,
Peter Maydell1f871c52018-06-15 14:57:16 +0100674 hwaddr *xlat, hwaddr *plen,
675 MemTxAttrs attrs, int *prot)
Jan Kiszka90260c62013-05-26 21:46:51 +0200676{
Avi Kivity30951152012-10-30 13:47:46 +0200677 MemoryRegionSection *section;
Peter Maydell1f871c52018-06-15 14:57:16 +0100678 IOMMUMemoryRegion *iommu_mr;
679 IOMMUMemoryRegionClass *imrc;
680 IOMMUTLBEntry iotlb;
681 int iommu_idx;
Richard Henderson418ade72022-06-21 08:38:29 -0700682 hwaddr addr = orig_addr;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100683 AddressSpaceDispatch *d =
684 qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
Peter Maydelld7898cd2016-01-21 14:15:05 +0000685
Peter Maydell1f871c52018-06-15 14:57:16 +0100686 for (;;) {
687 section = address_space_translate_internal(d, addr, &addr, plen, false);
688
689 iommu_mr = memory_region_get_iommu(section->mr);
690 if (!iommu_mr) {
691 break;
692 }
693
694 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
695
696 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
697 tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
698 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
699 * doesn't short-cut its translation table walk.
700 */
701 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
702 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
703 | (addr & iotlb.addr_mask));
704 /* Update the caller's prot bits to remove permissions the IOMMU
705 * is giving us a failure response for. If we get down to no
706 * permissions left at all we can give up now.
707 */
708 if (!(iotlb.perm & IOMMU_RO)) {
709 *prot &= ~(PAGE_READ | PAGE_EXEC);
710 }
711 if (!(iotlb.perm & IOMMU_WO)) {
712 *prot &= ~PAGE_WRITE;
713 }
714
715 if (!*prot) {
716 goto translate_fail;
717 }
718
719 d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
720 }
Avi Kivity30951152012-10-30 13:47:46 +0200721
Alexey Kardashevskiy3df9d742017-07-11 13:56:19 +1000722 assert(!memory_region_is_iommu(section->mr));
Peter Maydell1f871c52018-06-15 14:57:16 +0100723 *xlat = addr;
Avi Kivity30951152012-10-30 13:47:46 +0200724 return section;
Peter Maydell1f871c52018-06-15 14:57:16 +0100725
726translate_fail:
Richard Henderson418ade72022-06-21 08:38:29 -0700727 /*
728 * We should be given a page-aligned address -- certainly
729 * tlb_set_page_with_attrs() does so. The page offset of xlat
730 * is used to index sections[], and PHYS_SECTION_UNASSIGNED = 0.
731 * The page portion of xlat will be logged by memory_region_access_valid()
732 * when this memory access is rejected, so use the original untranslated
733 * physical address.
734 */
735 assert((orig_addr & ~TARGET_PAGE_MASK) == 0);
736 *xlat = orig_addr;
Peter Maydell1f871c52018-06-15 14:57:16 +0100737 return &d->map.sections[PHYS_SECTION_UNASSIGNED];
Jan Kiszka90260c62013-05-26 21:46:51 +0200738}
Andreas Färber1a1562f2013-06-17 04:09:11 +0200739
Peter Xu80ceb072017-11-23 17:23:32 +0800740void cpu_address_space_init(CPUState *cpu, int asidx,
741 const char *prefix, MemoryRegion *mr)
Edgar E. Iglesias09daed82013-12-17 13:06:51 +1000742{
Peter Maydell12ebc9a2016-01-21 14:15:04 +0000743 CPUAddressSpace *newas;
Peter Xu80ceb072017-11-23 17:23:32 +0800744 AddressSpace *as = g_new0(AddressSpace, 1);
Peter Xu87a621d2017-11-23 17:23:33 +0800745 char *as_name;
Peter Xu80ceb072017-11-23 17:23:32 +0800746
747 assert(mr);
Peter Xu87a621d2017-11-23 17:23:33 +0800748 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
749 address_space_init(as, mr, as_name);
750 g_free(as_name);
Peter Maydell12ebc9a2016-01-21 14:15:04 +0000751
752 /* Target code should have set num_ases before calling us */
753 assert(asidx < cpu->num_ases);
754
Peter Maydell56943e82016-01-21 14:15:04 +0000755 if (asidx == 0) {
756 /* address space 0 gets the convenience alias */
757 cpu->as = as;
758 }
759
Peter Maydell12ebc9a2016-01-21 14:15:04 +0000760 /* KVM cannot currently support multiple address spaces. */
761 assert(asidx == 0 || !kvm_enabled());
Edgar E. Iglesias09daed82013-12-17 13:06:51 +1000762
Peter Maydell12ebc9a2016-01-21 14:15:04 +0000763 if (!cpu->cpu_ases) {
764 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
Edgar E. Iglesias09daed82013-12-17 13:06:51 +1000765 }
Peter Maydell32857f42015-10-01 15:29:50 +0100766
Peter Maydell12ebc9a2016-01-21 14:15:04 +0000767 newas = &cpu->cpu_ases[asidx];
768 newas->cpu = cpu;
769 newas->as = as;
Peter Maydell56943e82016-01-21 14:15:04 +0000770 if (tcg_enabled()) {
Paolo Bonzini9458a9a2018-02-06 18:37:39 +0100771 newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
Peter Maydell12ebc9a2016-01-21 14:15:04 +0000772 newas->tcg_as_listener.commit = tcg_commit;
Peter Xu142518b2021-08-16 21:35:52 -0400773 newas->tcg_as_listener.name = "tcg";
Peter Maydell12ebc9a2016-01-21 14:15:04 +0000774 memory_listener_register(&newas->tcg_as_listener, as);
Peter Maydell56943e82016-01-21 14:15:04 +0000775 }
Edgar E. Iglesias09daed82013-12-17 13:06:51 +1000776}
Peter Maydell651a5bc2016-01-21 14:15:05 +0000777
778AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
779{
780 /* Return the AddressSpace corresponding to the specified index */
781 return cpu->cpu_ases[asidx].as;
782}
Edgar E. Iglesias09daed82013-12-17 13:06:51 +1000783
Mike Day0dc3f442013-09-05 14:41:35 -0400784/* Called from RCU critical section */
Paolo Bonzini041603f2013-09-09 17:49:45 +0200785static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
786{
787 RAMBlock *block;
788
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100789 block = qatomic_rcu_read(&ram_list.mru_block);
Michael S. Tsirkin9b8424d2014-12-15 22:55:32 +0200790 if (block && addr - block->offset < block->max_length) {
Paolo Bonzini68851b92015-10-22 13:51:30 +0200791 return block;
Paolo Bonzini041603f2013-09-09 17:49:45 +0200792 }
Peter Xu99e15582017-05-12 12:17:39 +0800793 RAMBLOCK_FOREACH(block) {
Michael S. Tsirkin9b8424d2014-12-15 22:55:32 +0200794 if (addr - block->offset < block->max_length) {
Paolo Bonzini041603f2013-09-09 17:49:45 +0200795 goto found;
796 }
797 }
798
799 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
800 abort();
801
802found:
Paolo Bonzini43771532013-09-09 17:58:40 +0200803 /* It is safe to write mru_block outside the iothread lock. This
804 * is what happens:
805 *
806 * mru_block = xxx
807 * rcu_read_unlock()
808 * xxx removed from list
809 * rcu_read_lock()
810 * read mru_block
811 * mru_block = NULL;
812 * call_rcu(reclaim_ramblock, xxx);
813 * rcu_read_unlock()
814 *
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100815 * qatomic_rcu_set is not needed here. The block was already published
Paolo Bonzini43771532013-09-09 17:58:40 +0200816 * when it was placed into the list. Here we're just making an extra
817 * copy of the pointer.
818 */
Paolo Bonzini041603f2013-09-09 17:49:45 +0200819 ram_list.mru_block = block;
820 return block;
821}
822
Juan Quintelaa2f4d5b2013-10-10 11:49:53 +0200823static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
bellard1ccde1c2004-02-06 19:46:14 +0000824{
Peter Crosthwaite9a135652015-09-10 22:39:41 -0700825 CPUState *cpu;
Paolo Bonzini041603f2013-09-09 17:49:45 +0200826 ram_addr_t start1;
Juan Quintelaa2f4d5b2013-10-10 11:49:53 +0200827 RAMBlock *block;
828 ram_addr_t end;
829
Emilio G. Cotaf28d0df2018-06-22 13:45:31 -0400830 assert(tcg_enabled());
Juan Quintelaa2f4d5b2013-10-10 11:49:53 +0200831 end = TARGET_PAGE_ALIGN(start + length);
832 start &= TARGET_PAGE_MASK;
bellardf23db162005-08-21 19:12:28 +0000833
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +0100834 RCU_READ_LOCK_GUARD();
Paolo Bonzini041603f2013-09-09 17:49:45 +0200835 block = qemu_get_ram_block(start);
836 assert(block == qemu_get_ram_block(end - 1));
Michael S. Tsirkin1240be22014-11-12 11:44:41 +0200837 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
Peter Crosthwaite9a135652015-09-10 22:39:41 -0700838 CPU_FOREACH(cpu) {
839 tlb_reset_dirty(cpu, start1, length);
840 }
Juan Quintelad24981d2012-05-22 00:42:40 +0200841}
842
843/* Note: start and end must be within the same ram block. */
Stefan Hajnoczi03eebc92014-12-02 11:23:18 +0000844bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
845 ram_addr_t length,
846 unsigned client)
Juan Quintelad24981d2012-05-22 00:42:40 +0200847{
Stefan Hajnoczi5b82b702016-01-25 13:33:20 +0000848 DirtyMemoryBlocks *blocks;
Matt Borgerson25aa6b32020-02-18 03:19:10 -0700849 unsigned long end, page, start_page;
Stefan Hajnoczi5b82b702016-01-25 13:33:20 +0000850 bool dirty = false;
Peter Xu077874e2019-06-03 14:50:51 +0800851 RAMBlock *ramblock;
852 uint64_t mr_offset, mr_size;
Juan Quintelad24981d2012-05-22 00:42:40 +0200853
Stefan Hajnoczi03eebc92014-12-02 11:23:18 +0000854 if (length == 0) {
855 return false;
856 }
857
858 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
Matt Borgerson25aa6b32020-02-18 03:19:10 -0700859 start_page = start >> TARGET_PAGE_BITS;
860 page = start_page;
Stefan Hajnoczi5b82b702016-01-25 13:33:20 +0000861
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +0100862 WITH_RCU_READ_LOCK_GUARD() {
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100863 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +0100864 ramblock = qemu_get_ram_block(start);
865 /* Range sanity check on the ramblock */
866 assert(start >= ramblock->offset &&
867 start + length <= ramblock->offset + ramblock->used_length);
Stefan Hajnoczi5b82b702016-01-25 13:33:20 +0000868
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +0100869 while (page < end) {
870 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
871 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
872 unsigned long num = MIN(end - page,
873 DIRTY_MEMORY_BLOCK_SIZE - offset);
Stefan Hajnoczi5b82b702016-01-25 13:33:20 +0000874
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +0100875 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
876 offset, num);
877 page += num;
878 }
Stefan Hajnoczi5b82b702016-01-25 13:33:20 +0000879
Matt Borgerson25aa6b32020-02-18 03:19:10 -0700880 mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
881 mr_size = (end - start_page) << TARGET_PAGE_BITS;
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +0100882 memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
Stefan Hajnoczi5b82b702016-01-25 13:33:20 +0000883 }
884
Stefan Hajnoczi03eebc92014-12-02 11:23:18 +0000885 if (dirty && tcg_enabled()) {
Juan Quintelaa2f4d5b2013-10-10 11:49:53 +0200886 tlb_reset_dirty_range_all(start, length);
Juan Quintelad24981d2012-05-22 00:42:40 +0200887 }
Stefan Hajnoczi03eebc92014-12-02 11:23:18 +0000888
889 return dirty;
bellard1ccde1c2004-02-06 19:46:14 +0000890}
891
Gerd Hoffmann8deaf122017-04-21 11:16:25 +0200892DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
Peter Xu5dea4072019-06-03 14:50:50 +0800893 (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
Gerd Hoffmann8deaf122017-04-21 11:16:25 +0200894{
895 DirtyMemoryBlocks *blocks;
Peter Xu5dea4072019-06-03 14:50:50 +0800896 ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
Gerd Hoffmann8deaf122017-04-21 11:16:25 +0200897 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
898 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
899 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
900 DirtyBitmapSnapshot *snap;
901 unsigned long page, end, dest;
902
903 snap = g_malloc0(sizeof(*snap) +
904 ((last - first) >> (TARGET_PAGE_BITS + 3)));
905 snap->start = first;
906 snap->end = last;
907
908 page = first >> TARGET_PAGE_BITS;
909 end = last >> TARGET_PAGE_BITS;
910 dest = 0;
911
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +0100912 WITH_RCU_READ_LOCK_GUARD() {
Stefan Hajnoczid73415a2020-09-23 11:56:46 +0100913 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
Gerd Hoffmann8deaf122017-04-21 11:16:25 +0200914
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +0100915 while (page < end) {
916 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
917 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
918 unsigned long num = MIN(end - page,
919 DIRTY_MEMORY_BLOCK_SIZE - offset);
Gerd Hoffmann8deaf122017-04-21 11:16:25 +0200920
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +0100921 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
922 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
923 offset >>= BITS_PER_LEVEL;
Gerd Hoffmann8deaf122017-04-21 11:16:25 +0200924
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +0100925 bitmap_copy_and_clear_atomic(snap->dirty + dest,
926 blocks->blocks[idx] + offset,
927 num);
928 page += num;
929 dest += num >> BITS_PER_LEVEL;
930 }
Gerd Hoffmann8deaf122017-04-21 11:16:25 +0200931 }
932
Gerd Hoffmann8deaf122017-04-21 11:16:25 +0200933 if (tcg_enabled()) {
934 tlb_reset_dirty_range_all(start, length);
935 }
936
Peter Xu077874e2019-06-03 14:50:51 +0800937 memory_region_clear_dirty_bitmap(mr, offset, length);
938
Gerd Hoffmann8deaf122017-04-21 11:16:25 +0200939 return snap;
940}
941
942bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
943 ram_addr_t start,
944 ram_addr_t length)
945{
946 unsigned long page, end;
947
948 assert(start >= snap->start);
949 assert(start + length <= snap->end);
950
951 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
952 page = (start - snap->start) >> TARGET_PAGE_BITS;
953
954 while (page < end) {
955 if (test_bit(page, snap->dirty)) {
956 return true;
957 }
958 page++;
959 }
960 return false;
961}
962
Paolo Bonzini79e2b9a2015-01-21 12:09:14 +0100963/* Called from RCU critical section */
Andreas Färberbb0e6272013-09-03 13:32:01 +0200964hwaddr memory_region_section_get_iotlb(CPUState *cpu,
Richard Henderson8f5db642019-09-19 21:09:58 -0700965 MemoryRegionSection *section)
Blue Swirle5548612012-04-21 13:08:33 +0000966{
Richard Henderson8f5db642019-09-19 21:09:58 -0700967 AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
968 return section - d->map.sections;
Blue Swirle5548612012-04-21 13:08:33 +0000969}
pbrook8da3ff12008-12-01 18:59:50 +0000970
Wei Yangb797ab12019-03-21 16:25:53 +0800971static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
972 uint16_t section);
Alexey Kardashevskiy16620682017-09-21 18:50:58 +1000973static subpage_t *subpage_init(FlatView *fv, hwaddr base);
Avi Kivity54688b12012-02-09 17:34:32 +0200974
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200975static uint16_t phys_section_add(PhysPageMap *map,
976 MemoryRegionSection *section)
Avi Kivity5312bd82012-02-12 18:32:55 +0200977{
Paolo Bonzini68f3f652013-05-07 11:30:23 +0200978 /* The physical section number is ORed with a page-aligned
979 * pointer to produce the iotlb entries. Thus it should
980 * never overflow into the page-aligned value.
981 */
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200982 assert(map->sections_nb < TARGET_PAGE_SIZE);
Paolo Bonzini68f3f652013-05-07 11:30:23 +0200983
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200984 if (map->sections_nb == map->sections_nb_alloc) {
985 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
986 map->sections = g_renew(MemoryRegionSection, map->sections,
987 map->sections_nb_alloc);
Avi Kivity5312bd82012-02-12 18:32:55 +0200988 }
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200989 map->sections[map->sections_nb] = *section;
Paolo Bonzinidfde4e62013-05-06 10:46:11 +0200990 memory_region_ref(section->mr);
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +0200991 return map->sections_nb++;
Avi Kivity5312bd82012-02-12 18:32:55 +0200992}
993
Paolo Bonzini058bc4b2013-06-25 09:30:48 +0200994static void phys_section_destroy(MemoryRegion *mr)
995{
Don Slutz55b4e802015-11-30 17:11:04 -0500996 bool have_sub_page = mr->subpage;
997
Paolo Bonzinidfde4e62013-05-06 10:46:11 +0200998 memory_region_unref(mr);
999
Don Slutz55b4e802015-11-30 17:11:04 -05001000 if (have_sub_page) {
Paolo Bonzini058bc4b2013-06-25 09:30:48 +02001001 subpage_t *subpage = container_of(mr, subpage_t, iomem);
Peter Crosthwaiteb4fefef2014-06-05 23:15:52 -07001002 object_unref(OBJECT(&subpage->iomem));
Paolo Bonzini058bc4b2013-06-25 09:30:48 +02001003 g_free(subpage);
1004 }
1005}
1006
Paolo Bonzini60926662013-05-29 12:30:26 +02001007static void phys_sections_free(PhysPageMap *map)
Avi Kivity5312bd82012-02-12 18:32:55 +02001008{
Paolo Bonzini9affd6f2013-05-29 12:09:47 +02001009 while (map->sections_nb > 0) {
1010 MemoryRegionSection *section = &map->sections[--map->sections_nb];
Paolo Bonzini058bc4b2013-06-25 09:30:48 +02001011 phys_section_destroy(section->mr);
1012 }
Paolo Bonzini9affd6f2013-05-29 12:09:47 +02001013 g_free(map->sections);
1014 g_free(map->nodes);
Avi Kivity5312bd82012-02-12 18:32:55 +02001015}
1016
Alexey Kardashevskiy99503222017-09-21 18:50:59 +10001017static void register_subpage(FlatView *fv, MemoryRegionSection *section)
Avi Kivity0f0cb162012-02-13 17:14:32 +02001018{
Alexey Kardashevskiy99503222017-09-21 18:50:59 +10001019 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
Avi Kivity0f0cb162012-02-13 17:14:32 +02001020 subpage_t *subpage;
Avi Kivitya8170e52012-10-23 12:30:10 +02001021 hwaddr base = section->offset_within_address_space
Avi Kivity0f0cb162012-02-13 17:14:32 +02001022 & TARGET_PAGE_MASK;
Peter Xu003a0cf2017-05-15 16:50:57 +08001023 MemoryRegionSection *existing = phys_page_find(d, base);
Avi Kivity0f0cb162012-02-13 17:14:32 +02001024 MemoryRegionSection subsection = {
1025 .offset_within_address_space = base,
Paolo Bonzini052e87b2013-05-27 10:08:27 +02001026 .size = int128_make64(TARGET_PAGE_SIZE),
Avi Kivity0f0cb162012-02-13 17:14:32 +02001027 };
Avi Kivitya8170e52012-10-23 12:30:10 +02001028 hwaddr start, end;
Avi Kivity0f0cb162012-02-13 17:14:32 +02001029
Avi Kivityf3705d52012-03-08 16:16:34 +02001030 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
Avi Kivity0f0cb162012-02-13 17:14:32 +02001031
Avi Kivityf3705d52012-03-08 16:16:34 +02001032 if (!(existing->mr->subpage)) {
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10001033 subpage = subpage_init(fv, base);
1034 subsection.fv = fv;
Avi Kivity0f0cb162012-02-13 17:14:32 +02001035 subsection.mr = &subpage->iomem;
Avi Kivityac1970f2012-10-03 16:22:53 +02001036 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +02001037 phys_section_add(&d->map, &subsection));
Avi Kivity0f0cb162012-02-13 17:14:32 +02001038 } else {
Avi Kivityf3705d52012-03-08 16:16:34 +02001039 subpage = container_of(existing->mr, subpage_t, iomem);
Avi Kivity0f0cb162012-02-13 17:14:32 +02001040 }
1041 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
Paolo Bonzini052e87b2013-05-27 10:08:27 +02001042 end = start + int128_get64(section->size) - 1;
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +02001043 subpage_register(subpage, start, end,
1044 phys_section_add(&d->map, section));
Avi Kivity0f0cb162012-02-13 17:14:32 +02001045}
1046
1047
Alexey Kardashevskiy99503222017-09-21 18:50:59 +10001048static void register_multipage(FlatView *fv,
Paolo Bonzini052e87b2013-05-27 10:08:27 +02001049 MemoryRegionSection *section)
bellard33417e72003-08-10 21:47:01 +00001050{
Alexey Kardashevskiy99503222017-09-21 18:50:59 +10001051 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
Avi Kivitya8170e52012-10-23 12:30:10 +02001052 hwaddr start_addr = section->offset_within_address_space;
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +02001053 uint16_t section_index = phys_section_add(&d->map, section);
Paolo Bonzini052e87b2013-05-27 10:08:27 +02001054 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1055 TARGET_PAGE_BITS));
Avi Kivitydd811242012-01-02 12:17:03 +02001056
Paolo Bonzini733d5ef2013-05-27 10:47:10 +02001057 assert(num_pages);
1058 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
bellard33417e72003-08-10 21:47:01 +00001059}
1060
Wei Yang494d1992019-03-11 13:42:52 +08001061/*
1062 * The range in *section* may look like this:
1063 *
1064 * |s|PPPPPPP|s|
1065 *
1066 * where s stands for subpage and P for page.
1067 */
Alexey Kardashevskiy8629d3f2017-09-21 18:51:00 +10001068void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
Avi Kivity0f0cb162012-02-13 17:14:32 +02001069{
Wei Yang494d1992019-03-11 13:42:52 +08001070 MemoryRegionSection remain = *section;
Paolo Bonzini052e87b2013-05-27 10:08:27 +02001071 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
Avi Kivity0f0cb162012-02-13 17:14:32 +02001072
Wei Yang494d1992019-03-11 13:42:52 +08001073 /* register first subpage */
1074 if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1075 uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1076 - remain.offset_within_address_space;
Paolo Bonzini733d5ef2013-05-27 10:47:10 +02001077
Wei Yang494d1992019-03-11 13:42:52 +08001078 MemoryRegionSection now = remain;
Paolo Bonzini052e87b2013-05-27 10:08:27 +02001079 now.size = int128_min(int128_make64(left), now.size);
Alexey Kardashevskiy99503222017-09-21 18:50:59 +10001080 register_subpage(fv, &now);
Wei Yang494d1992019-03-11 13:42:52 +08001081 if (int128_eq(remain.size, now.size)) {
1082 return;
1083 }
Paolo Bonzini052e87b2013-05-27 10:08:27 +02001084 remain.size = int128_sub(remain.size, now.size);
1085 remain.offset_within_address_space += int128_get64(now.size);
1086 remain.offset_within_region += int128_get64(now.size);
Avi Kivity0f0cb162012-02-13 17:14:32 +02001087 }
Wei Yang494d1992019-03-11 13:42:52 +08001088
1089 /* register whole pages */
1090 if (int128_ge(remain.size, page_size)) {
1091 MemoryRegionSection now = remain;
1092 now.size = int128_and(now.size, int128_neg(page_size));
1093 register_multipage(fv, &now);
1094 if (int128_eq(remain.size, now.size)) {
1095 return;
1096 }
1097 remain.size = int128_sub(remain.size, now.size);
1098 remain.offset_within_address_space += int128_get64(now.size);
1099 remain.offset_within_region += int128_get64(now.size);
1100 }
1101
1102 /* register last subpage */
1103 register_subpage(fv, &remain);
Avi Kivity0f0cb162012-02-13 17:14:32 +02001104}
1105
Sheng Yang62a27442010-01-26 19:21:16 +08001106void qemu_flush_coalesced_mmio_buffer(void)
1107{
1108 if (kvm_enabled())
1109 kvm_flush_coalesced_mmio_buffer();
1110}
1111
Umesh Deshpandeb2a86582011-08-17 00:01:33 -07001112void qemu_mutex_lock_ramlist(void)
1113{
1114 qemu_mutex_lock(&ram_list.mutex);
1115}
1116
1117void qemu_mutex_unlock_ramlist(void)
1118{
1119 qemu_mutex_unlock(&ram_list.mutex);
1120}
1121
Daniel P. Berrangéca411b72021-09-08 10:35:43 +01001122GString *ram_block_format(void)
Peter Xube9b23c2017-05-12 12:17:41 +08001123{
1124 RAMBlock *block;
1125 char *psize;
Daniel P. Berrangéca411b72021-09-08 10:35:43 +01001126 GString *buf = g_string_new("");
Peter Xube9b23c2017-05-12 12:17:41 +08001127
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +01001128 RCU_READ_LOCK_GUARD();
Ted Chendbc6ae92022-12-05 20:07:12 +08001129 g_string_append_printf(buf, "%24s %8s %18s %18s %18s %18s %3s\n",
1130 "Block Name", "PSize", "Offset", "Used", "Total",
1131 "HVA", "RO");
1132
Peter Xube9b23c2017-05-12 12:17:41 +08001133 RAMBLOCK_FOREACH(block) {
1134 psize = size_to_str(block->page_size);
Daniel P. Berrangéca411b72021-09-08 10:35:43 +01001135 g_string_append_printf(buf, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
Ted Chendbc6ae92022-12-05 20:07:12 +08001136 " 0x%016" PRIx64 " 0x%016" PRIx64 " %3s\n",
1137 block->idstr, psize,
Daniel P. Berrangéca411b72021-09-08 10:35:43 +01001138 (uint64_t)block->offset,
1139 (uint64_t)block->used_length,
Ted Chendbc6ae92022-12-05 20:07:12 +08001140 (uint64_t)block->max_length,
1141 (uint64_t)(uintptr_t)block->host,
1142 block->mr->readonly ? "ro" : "rw");
1143
Peter Xube9b23c2017-05-12 12:17:41 +08001144 g_free(psize);
1145 }
Daniel P. Berrangéca411b72021-09-08 10:35:43 +01001146
1147 return buf;
Peter Xube9b23c2017-05-12 12:17:41 +08001148}
1149
David Hildenbrand905b7ee2019-04-17 13:31:43 +02001150static int find_min_backend_pagesize(Object *obj, void *opaque)
Alexey Kardashevskiy9c607662017-03-02 13:36:11 +11001151{
Alexey Kardashevskiy9c607662017-03-02 13:36:11 +11001152 long *hpsize_min = opaque;
1153
1154 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
David Gibson7d5489e2019-03-26 14:33:33 +11001155 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1156 long hpsize = host_memory_backend_pagesize(backend);
David Gibson2b108082018-04-03 15:05:45 +10001157
David Gibson7d5489e2019-03-26 14:33:33 +11001158 if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
David Gibson0de6e2a2018-04-03 14:55:11 +10001159 *hpsize_min = hpsize;
Alexey Kardashevskiy9c607662017-03-02 13:36:11 +11001160 }
1161 }
1162
1163 return 0;
1164}
1165
David Hildenbrand905b7ee2019-04-17 13:31:43 +02001166static int find_max_backend_pagesize(Object *obj, void *opaque)
1167{
1168 long *hpsize_max = opaque;
1169
1170 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1171 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1172 long hpsize = host_memory_backend_pagesize(backend);
1173
1174 if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1175 *hpsize_max = hpsize;
1176 }
1177 }
1178
1179 return 0;
1180}
1181
1182/*
1183 * TODO: We assume right now that all mapped host memory backends are
1184 * used as RAM, however some might be used for different purposes.
1185 */
1186long qemu_minrampagesize(void)
Alexey Kardashevskiy9c607662017-03-02 13:36:11 +11001187{
1188 long hpsize = LONG_MAX;
Igor Mammedovad1172d2020-02-19 11:09:47 -05001189 Object *memdev_root = object_resolve_path("/objects", NULL);
Alexey Kardashevskiy9c607662017-03-02 13:36:11 +11001190
Igor Mammedovad1172d2020-02-19 11:09:47 -05001191 object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
Alexey Kardashevskiy9c607662017-03-02 13:36:11 +11001192 return hpsize;
1193}
David Hildenbrand905b7ee2019-04-17 13:31:43 +02001194
1195long qemu_maxrampagesize(void)
1196{
Igor Mammedovad1172d2020-02-19 11:09:47 -05001197 long pagesize = 0;
David Hildenbrand905b7ee2019-04-17 13:31:43 +02001198 Object *memdev_root = object_resolve_path("/objects", NULL);
1199
Igor Mammedovad1172d2020-02-19 11:09:47 -05001200 object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
David Hildenbrand905b7ee2019-04-17 13:31:43 +02001201 return pagesize;
1202}
Alexey Kardashevskiy9c607662017-03-02 13:36:11 +11001203
Hikaru Nishidad5dbde42018-09-24 21:32:05 +09001204#ifdef CONFIG_POSIX
Haozhong Zhangd6af99c2016-10-27 12:22:58 +08001205static int64_t get_file_size(int fd)
1206{
Stefan Hajnoczi72d41eb2019-08-30 10:30:56 +01001207 int64_t size;
1208#if defined(__linux__)
1209 struct stat st;
1210
1211 if (fstat(fd, &st) < 0) {
1212 return -errno;
1213 }
1214
1215 /* Special handling for devdax character devices */
1216 if (S_ISCHR(st.st_mode)) {
1217 g_autofree char *subsystem_path = NULL;
1218 g_autofree char *subsystem = NULL;
1219
1220 subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1221 major(st.st_rdev), minor(st.st_rdev));
1222 subsystem = g_file_read_link(subsystem_path, NULL);
1223
1224 if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
1225 g_autofree char *size_path = NULL;
1226 g_autofree char *size_str = NULL;
1227
1228 size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
1229 major(st.st_rdev), minor(st.st_rdev));
1230
1231 if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
1232 return g_ascii_strtoll(size_str, NULL, 0);
1233 }
1234 }
1235 }
1236#endif /* defined(__linux__) */
1237
1238 /* st.st_size may be zero for special files yet lseek(2) works */
1239 size = lseek(fd, 0, SEEK_END);
Haozhong Zhangd6af99c2016-10-27 12:22:58 +08001240 if (size < 0) {
1241 return -errno;
1242 }
1243 return size;
1244}
1245
Jingqi Liuce317be2020-04-29 16:50:09 +08001246static int64_t get_file_align(int fd)
1247{
1248 int64_t align = -1;
1249#if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1250 struct stat st;
1251
1252 if (fstat(fd, &st) < 0) {
1253 return -errno;
1254 }
1255
1256 /* Special handling for devdax character devices */
1257 if (S_ISCHR(st.st_mode)) {
1258 g_autofree char *path = NULL;
1259 g_autofree char *rpath = NULL;
1260 struct daxctl_ctx *ctx;
1261 struct daxctl_region *region;
1262 int rc = 0;
1263
1264 path = g_strdup_printf("/sys/dev/char/%d:%d",
1265 major(st.st_rdev), minor(st.st_rdev));
1266 rpath = realpath(path, NULL);
Peter Maydell8efdb7b2021-08-12 16:15:25 +01001267 if (!rpath) {
1268 return -errno;
1269 }
Jingqi Liuce317be2020-04-29 16:50:09 +08001270
1271 rc = daxctl_new(&ctx);
1272 if (rc) {
1273 return -1;
1274 }
1275
1276 daxctl_region_foreach(ctx, region) {
1277 if (strstr(rpath, daxctl_region_get_path(region))) {
1278 align = daxctl_region_get_align(region);
1279 break;
1280 }
1281 }
1282 daxctl_unref(ctx);
1283 }
1284#endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1285
1286 return align;
1287}
1288
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001289static int file_ram_open(const char *path,
1290 const char *region_name,
Stefan Hajnoczi369d6dc2021-01-04 17:13:18 +00001291 bool readonly,
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001292 bool *created,
1293 Error **errp)
Marcelo Tosattic9027602010-03-01 20:25:08 -03001294{
1295 char *filename;
Peter Feiner8ca761f2013-03-04 13:54:25 -05001296 char *sanitized_name;
1297 char *c;
Paolo Bonzini5c3ece72016-03-17 15:53:13 +01001298 int fd = -1;
Marcelo Tosattic9027602010-03-01 20:25:08 -03001299
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001300 *created = false;
Markus Armbrusterfd97fd42016-03-07 20:25:13 +01001301 for (;;) {
Stefan Hajnoczi369d6dc2021-01-04 17:13:18 +00001302 fd = open(path, readonly ? O_RDONLY : O_RDWR);
Markus Armbrusterfd97fd42016-03-07 20:25:13 +01001303 if (fd >= 0) {
1304 /* @path names an existing file, use it */
1305 break;
1306 }
1307 if (errno == ENOENT) {
1308 /* @path names a file that doesn't exist, create it */
1309 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1310 if (fd >= 0) {
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001311 *created = true;
Markus Armbrusterfd97fd42016-03-07 20:25:13 +01001312 break;
1313 }
1314 } else if (errno == EISDIR) {
1315 /* @path names a directory, create a file there */
1316 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001317 sanitized_name = g_strdup(region_name);
Markus Armbrusterfd97fd42016-03-07 20:25:13 +01001318 for (c = sanitized_name; *c != '\0'; c++) {
1319 if (*c == '/') {
1320 *c = '_';
1321 }
1322 }
1323
1324 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1325 sanitized_name);
1326 g_free(sanitized_name);
1327
1328 fd = mkstemp(filename);
1329 if (fd >= 0) {
1330 unlink(filename);
1331 g_free(filename);
1332 break;
1333 }
1334 g_free(filename);
1335 }
1336 if (errno != EEXIST && errno != EINTR) {
1337 error_setg_errno(errp, errno,
1338 "can't open backing store %s for guest RAM",
1339 path);
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001340 return -1;
Markus Armbrusterfd97fd42016-03-07 20:25:13 +01001341 }
1342 /*
1343 * Try again on EINTR and EEXIST. The latter happens when
1344 * something else creates the file between our two open().
1345 */
1346 }
1347
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001348 return fd;
1349}
1350
1351static void *file_ram_alloc(RAMBlock *block,
1352 ram_addr_t memory,
1353 int fd,
Stefan Hajnoczi369d6dc2021-01-04 17:13:18 +00001354 bool readonly,
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001355 bool truncate,
Jagannathan Raman44a4ff32021-01-29 11:46:04 -05001356 off_t offset,
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001357 Error **errp)
1358{
David Hildenbrandb444f5c2021-05-10 13:43:20 +02001359 uint32_t qemu_map_flags;
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001360 void *area;
1361
Dr. David Alan Gilbert863e9622016-09-29 20:09:37 +01001362 block->page_size = qemu_fd_getpagesize(fd);
Haozhong Zhang98376842017-12-11 15:28:04 +08001363 if (block->mr->align % block->page_size) {
1364 error_setg(errp, "alignment 0x%" PRIx64
1365 " must be multiples of page size 0x%zx",
1366 block->mr->align, block->page_size);
1367 return NULL;
David Hildenbrand61362b72018-06-07 17:47:05 +02001368 } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1369 error_setg(errp, "alignment 0x%" PRIx64
1370 " must be a power of two", block->mr->align);
1371 return NULL;
Alexander Graf4b870dc2023-04-03 22:14:21 +00001372 } else if (offset % block->page_size) {
1373 error_setg(errp, "offset 0x%" PRIx64
1374 " must be multiples of page size 0x%zx",
1375 offset, block->page_size);
1376 return NULL;
Haozhong Zhang98376842017-12-11 15:28:04 +08001377 }
1378 block->mr->align = MAX(block->page_size, block->mr->align);
Haozhong Zhang83606682016-10-24 20:49:37 +08001379#if defined(__s390x__)
1380 if (kvm_enabled()) {
1381 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1382 }
1383#endif
Marcelo Tosattic9027602010-03-01 20:25:08 -03001384
Dr. David Alan Gilbert863e9622016-09-29 20:09:37 +01001385 if (memory < block->page_size) {
Hu Tao557529d2014-09-09 13:28:00 +08001386 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
Dr. David Alan Gilbert863e9622016-09-29 20:09:37 +01001387 "or larger than page size 0x%zx",
1388 memory, block->page_size);
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001389 return NULL;
Haozhong Zhang1775f112016-11-02 09:05:51 +08001390 }
1391
Dr. David Alan Gilbert863e9622016-09-29 20:09:37 +01001392 memory = ROUND_UP(memory, block->page_size);
Marcelo Tosattic9027602010-03-01 20:25:08 -03001393
1394 /*
1395 * ftruncate is not supported by hugetlbfs in older
1396 * hosts, so don't bother bailing out on errors.
1397 * If anything goes wrong with it under other filesystems,
1398 * mmap will fail.
Haozhong Zhangd6af99c2016-10-27 12:22:58 +08001399 *
1400 * Do not truncate the non-empty backend file to avoid corrupting
1401 * the existing data in the file. Disabling shrinking is not
1402 * enough. For example, the current vNVDIMM implementation stores
1403 * the guest NVDIMM labels at the end of the backend file. If the
1404 * backend file is later extended, QEMU will not be able to find
1405 * those labels. Therefore, extending the non-empty backend file
1406 * is disabled as well.
Marcelo Tosattic9027602010-03-01 20:25:08 -03001407 */
Alexander Graf4b870dc2023-04-03 22:14:21 +00001408 if (truncate && ftruncate(fd, offset + memory)) {
Yoshiaki Tamura9742bf22010-08-18 13:30:13 +09001409 perror("ftruncate");
Paolo Bonzini7f56e742014-05-14 17:43:20 +08001410 }
Marcelo Tosattic9027602010-03-01 20:25:08 -03001411
David Hildenbrandb444f5c2021-05-10 13:43:20 +02001412 qemu_map_flags = readonly ? QEMU_MAP_READONLY : 0;
1413 qemu_map_flags |= (block->flags & RAM_SHARED) ? QEMU_MAP_SHARED : 0;
1414 qemu_map_flags |= (block->flags & RAM_PMEM) ? QEMU_MAP_SYNC : 0;
David Hildenbrand8dbe22c2021-05-10 13:43:21 +02001415 qemu_map_flags |= (block->flags & RAM_NORESERVE) ? QEMU_MAP_NORESERVE : 0;
David Hildenbrandb444f5c2021-05-10 13:43:20 +02001416 area = qemu_ram_mmap(fd, memory, block->mr->align, qemu_map_flags, offset);
Marcelo Tosattic9027602010-03-01 20:25:08 -03001417 if (area == MAP_FAILED) {
Paolo Bonzini7f56e742014-05-14 17:43:20 +08001418 error_setg_errno(errp, errno,
Markus Armbrusterfd97fd42016-03-07 20:25:13 +01001419 "unable to map backing store for guest RAM");
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001420 return NULL;
Marcelo Tosattic9027602010-03-01 20:25:08 -03001421 }
Marcelo Tosattief36fa12013-10-28 18:51:46 -02001422
Alex Williamson04b16652010-07-02 11:13:17 -06001423 block->fd = fd;
Alexander Graf4b870dc2023-04-03 22:14:21 +00001424 block->fd_offset = offset;
Marcelo Tosattic9027602010-03-01 20:25:08 -03001425 return area;
1426}
1427#endif
1428
Dr. David Alan Gilbert154cc9e2018-01-05 17:01:37 +00001429/* Allocate space within the ram_addr_t space that governs the
1430 * dirty bitmaps.
1431 * Called with the ramlist lock held.
1432 */
Alex Williamsond17b5282010-06-25 11:08:38 -06001433static ram_addr_t find_ram_offset(ram_addr_t size)
1434{
Alex Williamson04b16652010-07-02 11:13:17 -06001435 RAMBlock *block, *next_block;
Alex Williamson3e837b22011-10-31 08:54:09 -06001436 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
Alex Williamson04b16652010-07-02 11:13:17 -06001437
Stefan Hajnoczi49cd9ac2013-03-11 10:20:21 +01001438 assert(size != 0); /* it would hand out same offset multiple times */
1439
Mike Day0dc3f442013-09-05 14:41:35 -04001440 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
Alex Williamson04b16652010-07-02 11:13:17 -06001441 return 0;
Mike Day0d53d9f2015-01-21 13:45:24 +01001442 }
Alex Williamson04b16652010-07-02 11:13:17 -06001443
Peter Xu99e15582017-05-12 12:17:39 +08001444 RAMBLOCK_FOREACH(block) {
Dr. David Alan Gilbert154cc9e2018-01-05 17:01:37 +00001445 ram_addr_t candidate, next = RAM_ADDR_MAX;
Alex Williamson04b16652010-07-02 11:13:17 -06001446
Dr. David Alan Gilbert801110a2018-01-05 17:01:38 +00001447 /* Align blocks to start on a 'long' in the bitmap
1448 * which makes the bitmap sync'ing take the fast path.
1449 */
Dr. David Alan Gilbert154cc9e2018-01-05 17:01:37 +00001450 candidate = block->offset + block->max_length;
Dr. David Alan Gilbert801110a2018-01-05 17:01:38 +00001451 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
Alex Williamson04b16652010-07-02 11:13:17 -06001452
Dr. David Alan Gilbert154cc9e2018-01-05 17:01:37 +00001453 /* Search for the closest following block
1454 * and find the gap.
1455 */
Peter Xu99e15582017-05-12 12:17:39 +08001456 RAMBLOCK_FOREACH(next_block) {
Dr. David Alan Gilbert154cc9e2018-01-05 17:01:37 +00001457 if (next_block->offset >= candidate) {
Alex Williamson04b16652010-07-02 11:13:17 -06001458 next = MIN(next, next_block->offset);
1459 }
1460 }
Dr. David Alan Gilbert154cc9e2018-01-05 17:01:37 +00001461
1462 /* If it fits remember our place and remember the size
1463 * of gap, but keep going so that we might find a smaller
1464 * gap to fill so avoiding fragmentation.
1465 */
1466 if (next - candidate >= size && next - candidate < mingap) {
1467 offset = candidate;
1468 mingap = next - candidate;
Alex Williamson04b16652010-07-02 11:13:17 -06001469 }
Dr. David Alan Gilbert154cc9e2018-01-05 17:01:37 +00001470
1471 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
Alex Williamson04b16652010-07-02 11:13:17 -06001472 }
Alex Williamson3e837b22011-10-31 08:54:09 -06001473
1474 if (offset == RAM_ADDR_MAX) {
1475 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1476 (uint64_t)size);
1477 abort();
1478 }
1479
Dr. David Alan Gilbert154cc9e2018-01-05 17:01:37 +00001480 trace_find_ram_offset(size, offset);
1481
Alex Williamson04b16652010-07-02 11:13:17 -06001482 return offset;
1483}
1484
David Hildenbrandc1361802018-06-20 22:27:36 +02001485static unsigned long last_ram_page(void)
Alex Williamson04b16652010-07-02 11:13:17 -06001486{
Alex Williamsond17b5282010-06-25 11:08:38 -06001487 RAMBlock *block;
1488 ram_addr_t last = 0;
1489
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +01001490 RCU_READ_LOCK_GUARD();
Peter Xu99e15582017-05-12 12:17:39 +08001491 RAMBLOCK_FOREACH(block) {
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001492 last = MAX(last, block->offset + block->max_length);
Mike Day0d53d9f2015-01-21 13:45:24 +01001493 }
Juan Quintelab8c48992017-03-21 17:44:30 +01001494 return last >> TARGET_PAGE_BITS;
Alex Williamsond17b5282010-06-25 11:08:38 -06001495}
1496
Jason Baronddb97f12012-08-02 15:44:16 -04001497static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1498{
1499 int ret;
Jason Baronddb97f12012-08-02 15:44:16 -04001500
1501 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
Marcel Apfelbaum47c8ca52015-02-04 17:43:54 +02001502 if (!machine_dump_guest_core(current_machine)) {
Jason Baronddb97f12012-08-02 15:44:16 -04001503 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1504 if (ret) {
1505 perror("qemu_madvise");
1506 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1507 "but dump_guest_core=off specified\n");
1508 }
1509 }
1510}
1511
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00001512const char *qemu_ram_get_idstr(RAMBlock *rb)
1513{
1514 return rb->idstr;
1515}
1516
Yury Kotov754cb9c2019-02-15 20:45:44 +03001517void *qemu_ram_get_host_addr(RAMBlock *rb)
1518{
1519 return rb->host;
1520}
1521
1522ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
1523{
1524 return rb->offset;
1525}
1526
1527ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
1528{
1529 return rb->used_length;
1530}
1531
David Hildenbrand082851a2021-04-29 13:26:59 +02001532ram_addr_t qemu_ram_get_max_length(RAMBlock *rb)
1533{
1534 return rb->max_length;
1535}
1536
Dr. David Alan Gilbert463a4ac2017-03-07 18:36:36 +00001537bool qemu_ram_is_shared(RAMBlock *rb)
1538{
1539 return rb->flags & RAM_SHARED;
1540}
1541
David Hildenbrand8dbe22c2021-05-10 13:43:21 +02001542bool qemu_ram_is_noreserve(RAMBlock *rb)
1543{
1544 return rb->flags & RAM_NORESERVE;
1545}
1546
Dr. David Alan Gilbert2ce16642018-03-12 17:20:58 +00001547/* Note: Only set at the start of postcopy */
1548bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1549{
1550 return rb->flags & RAM_UF_ZEROPAGE;
1551}
1552
1553void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1554{
1555 rb->flags |= RAM_UF_ZEROPAGE;
1556}
1557
Cédric Le Goaterb895de52018-05-14 08:57:00 +02001558bool qemu_ram_is_migratable(RAMBlock *rb)
1559{
1560 return rb->flags & RAM_MIGRATABLE;
1561}
1562
1563void qemu_ram_set_migratable(RAMBlock *rb)
1564{
1565 rb->flags |= RAM_MIGRATABLE;
1566}
1567
1568void qemu_ram_unset_migratable(RAMBlock *rb)
1569{
1570 rb->flags &= ~RAM_MIGRATABLE;
1571}
1572
Steve Sistareb0182e52023-06-07 08:18:36 -07001573bool qemu_ram_is_named_file(RAMBlock *rb)
1574{
1575 return rb->flags & RAM_NAMED_FILE;
1576}
1577
Stefan Hajnoczi6d998f32022-10-13 14:59:05 -04001578int qemu_ram_get_fd(RAMBlock *rb)
1579{
1580 return rb->fd;
1581}
1582
Mike Dayae3a7042013-09-05 14:41:35 -04001583/* Called with iothread lock held. */
Gongleifa53a0e2016-05-10 10:04:59 +08001584void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
Hu Tao20cfe882014-04-02 15:13:26 +08001585{
Gongleifa53a0e2016-05-10 10:04:59 +08001586 RAMBlock *block;
Hu Tao20cfe882014-04-02 15:13:26 +08001587
Avi Kivityc5705a72011-12-20 15:59:12 +02001588 assert(new_block);
1589 assert(!new_block->idstr[0]);
Cam Macdonell84b89d72010-07-26 18:10:57 -06001590
Anthony Liguori09e5ab62012-02-03 12:28:43 -06001591 if (dev) {
1592 char *id = qdev_get_dev_path(dev);
Cam Macdonell84b89d72010-07-26 18:10:57 -06001593 if (id) {
1594 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
Anthony Liguori7267c092011-08-20 22:09:37 -05001595 g_free(id);
Cam Macdonell84b89d72010-07-26 18:10:57 -06001596 }
1597 }
1598 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1599
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +01001600 RCU_READ_LOCK_GUARD();
Peter Xu99e15582017-05-12 12:17:39 +08001601 RAMBLOCK_FOREACH(block) {
Gongleifa53a0e2016-05-10 10:04:59 +08001602 if (block != new_block &&
1603 !strcmp(block->idstr, new_block->idstr)) {
Cam Macdonell84b89d72010-07-26 18:10:57 -06001604 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1605 new_block->idstr);
1606 abort();
1607 }
1608 }
Avi Kivityc5705a72011-12-20 15:59:12 +02001609}
1610
Mike Dayae3a7042013-09-05 14:41:35 -04001611/* Called with iothread lock held. */
Gongleifa53a0e2016-05-10 10:04:59 +08001612void qemu_ram_unset_idstr(RAMBlock *block)
Hu Tao20cfe882014-04-02 15:13:26 +08001613{
Mike Dayae3a7042013-09-05 14:41:35 -04001614 /* FIXME: arch_init.c assumes that this is not called throughout
1615 * migration. Ignore the problem since hot-unplug during migration
1616 * does not work anyway.
1617 */
Hu Tao20cfe882014-04-02 15:13:26 +08001618 if (block) {
1619 memset(block->idstr, 0, sizeof(block->idstr));
1620 }
1621}
1622
Dr. David Alan Gilbert863e9622016-09-29 20:09:37 +01001623size_t qemu_ram_pagesize(RAMBlock *rb)
1624{
1625 return rb->page_size;
1626}
1627
Dr. David Alan Gilbert67f11b52017-02-24 18:28:34 +00001628/* Returns the largest size of page in use */
1629size_t qemu_ram_pagesize_largest(void)
1630{
1631 RAMBlock *block;
1632 size_t largest = 0;
1633
Peter Xu99e15582017-05-12 12:17:39 +08001634 RAMBLOCK_FOREACH(block) {
Dr. David Alan Gilbert67f11b52017-02-24 18:28:34 +00001635 largest = MAX(largest, qemu_ram_pagesize(block));
1636 }
1637
1638 return largest;
1639}
1640
Luiz Capitulino8490fc72012-09-05 16:50:16 -03001641static int memory_try_enable_merging(void *addr, size_t len)
1642{
Marcel Apfelbaum75cc7f02015-02-04 17:43:55 +02001643 if (!machine_mem_merge(current_machine)) {
Luiz Capitulino8490fc72012-09-05 16:50:16 -03001644 /* disabled by the user */
1645 return 0;
1646 }
1647
1648 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1649}
1650
David Hildenbrandc7c0e722021-04-29 13:27:02 +02001651/*
1652 * Resizing RAM while migrating can result in the migration being canceled.
1653 * Care has to be taken if the guest might have already detected the memory.
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001654 *
1655 * As memory core doesn't know how is memory accessed, it is up to
1656 * resize callback to update device state and/or add assertions to detect
1657 * misuse, if necessary.
1658 */
Gongleifa53a0e2016-05-10 10:04:59 +08001659int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001660{
David Hildenbrand8f443042021-04-29 13:27:00 +02001661 const ram_addr_t oldsize = block->used_length;
David Hildenbrandce4adc02020-04-03 11:18:27 +01001662 const ram_addr_t unaligned_size = newsize;
1663
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001664 assert(block);
1665
Dr. David Alan Gilbert4ed023c2015-11-05 18:11:16 +00001666 newsize = HOST_PAGE_ALIGN(newsize);
Michael S. Tsirkin129ddaf2015-02-17 10:15:30 +01001667
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001668 if (block->used_length == newsize) {
David Hildenbrandce4adc02020-04-03 11:18:27 +01001669 /*
1670 * We don't have to resize the ram block (which only knows aligned
1671 * sizes), however, we have to notify if the unaligned size changed.
1672 */
1673 if (unaligned_size != memory_region_size(block->mr)) {
1674 memory_region_set_size(block->mr, unaligned_size);
1675 if (block->resized) {
1676 block->resized(block->idstr, unaligned_size, block->host);
1677 }
1678 }
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001679 return 0;
1680 }
1681
1682 if (!(block->flags & RAM_RESIZEABLE)) {
1683 error_setg_errno(errp, EINVAL,
Pankaj Guptaa3a92902020-10-22 13:13:02 +02001684 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1685 " != 0x" RAM_ADDR_FMT, block->idstr,
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001686 newsize, block->used_length);
1687 return -EINVAL;
1688 }
1689
1690 if (block->max_length < newsize) {
1691 error_setg_errno(errp, EINVAL,
Pankaj Guptaa3a92902020-10-22 13:13:02 +02001692 "Size too large: %s: 0x" RAM_ADDR_FMT
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001693 " > 0x" RAM_ADDR_FMT, block->idstr,
1694 newsize, block->max_length);
1695 return -EINVAL;
1696 }
1697
David Hildenbrand8f443042021-04-29 13:27:00 +02001698 /* Notify before modifying the ram block and touching the bitmaps. */
1699 if (block->host) {
1700 ram_block_notify_resize(block->host, oldsize, newsize);
1701 }
1702
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001703 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1704 block->used_length = newsize;
Paolo Bonzini58d27072015-03-23 11:56:01 +01001705 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1706 DIRTY_CLIENTS_ALL);
David Hildenbrandce4adc02020-04-03 11:18:27 +01001707 memory_region_set_size(block->mr, unaligned_size);
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001708 if (block->resized) {
David Hildenbrandce4adc02020-04-03 11:18:27 +01001709 block->resized(block->idstr, unaligned_size, block->host);
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001710 }
1711 return 0;
1712}
1713
Beata Michalska61c490e2019-11-21 00:08:41 +00001714/*
1715 * Trigger sync on the given ram block for range [start, start + length]
1716 * with the backing store if one is available.
1717 * Otherwise no-op.
1718 * @Note: this is supposed to be a synchronous op.
1719 */
Philippe Mathieu-Daudéab7e41e2020-05-08 08:24:56 +02001720void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
Beata Michalska61c490e2019-11-21 00:08:41 +00001721{
Beata Michalska61c490e2019-11-21 00:08:41 +00001722 /* The requested range should fit in within the block range */
1723 g_assert((start + length) <= block->used_length);
1724
1725#ifdef CONFIG_LIBPMEM
1726 /* The lack of support for pmem should not block the sync */
1727 if (ramblock_is_pmem(block)) {
Anthony PERARD5d4c9542019-12-19 15:43:22 +00001728 void *addr = ramblock_ptr(block, start);
Beata Michalska61c490e2019-11-21 00:08:41 +00001729 pmem_persist(addr, length);
1730 return;
1731 }
1732#endif
1733 if (block->fd >= 0) {
1734 /**
1735 * Case there is no support for PMEM or the memory has not been
1736 * specified as persistent (or is not one) - use the msync.
1737 * Less optimal but still achieves the same goal
1738 */
Anthony PERARD5d4c9542019-12-19 15:43:22 +00001739 void *addr = ramblock_ptr(block, start);
Beata Michalska61c490e2019-11-21 00:08:41 +00001740 if (qemu_msync(addr, length, block->fd)) {
1741 warn_report("%s: failed to sync memory range: start: "
1742 RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
1743 __func__, start, length);
1744 }
1745 }
1746}
1747
Stefan Hajnoczi5b82b702016-01-25 13:33:20 +00001748/* Called with ram_list.mutex held */
1749static void dirty_memory_extend(ram_addr_t old_ram_size,
1750 ram_addr_t new_ram_size)
1751{
1752 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1753 DIRTY_MEMORY_BLOCK_SIZE);
1754 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1755 DIRTY_MEMORY_BLOCK_SIZE);
1756 int i;
1757
1758 /* Only need to extend if block count increased */
1759 if (new_num_blocks <= old_num_blocks) {
1760 return;
1761 }
1762
1763 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1764 DirtyMemoryBlocks *old_blocks;
1765 DirtyMemoryBlocks *new_blocks;
1766 int j;
1767
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001768 old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
Stefan Hajnoczi5b82b702016-01-25 13:33:20 +00001769 new_blocks = g_malloc(sizeof(*new_blocks) +
1770 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1771
1772 if (old_num_blocks) {
1773 memcpy(new_blocks->blocks, old_blocks->blocks,
1774 old_num_blocks * sizeof(old_blocks->blocks[0]));
1775 }
1776
1777 for (j = old_num_blocks; j < new_num_blocks; j++) {
1778 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1779 }
1780
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001781 qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
Stefan Hajnoczi5b82b702016-01-25 13:33:20 +00001782
1783 if (old_blocks) {
1784 g_free_rcu(old_blocks, rcu);
1785 }
1786 }
1787}
1788
David Hildenbrand7ce18ca2021-04-06 10:01:24 +02001789static void ram_block_add(RAMBlock *new_block, Error **errp)
Avi Kivityc5705a72011-12-20 15:59:12 +02001790{
David Hildenbrand8dbe22c2021-05-10 13:43:21 +02001791 const bool noreserve = qemu_ram_is_noreserve(new_block);
David Hildenbrand7ce18ca2021-04-06 10:01:24 +02001792 const bool shared = qemu_ram_is_shared(new_block);
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001793 RAMBlock *block;
Mike Day0d53d9f2015-01-21 13:45:24 +01001794 RAMBlock *last_block = NULL;
Juan Quintela2152f5c2013-10-08 13:52:02 +02001795 ram_addr_t old_ram_size, new_ram_size;
Markus Armbruster37aa7a02016-01-14 16:09:39 +01001796 Error *err = NULL;
Juan Quintela2152f5c2013-10-08 13:52:02 +02001797
Juan Quintelab8c48992017-03-21 17:44:30 +01001798 old_ram_size = last_ram_page();
Avi Kivityc5705a72011-12-20 15:59:12 +02001799
Umesh Deshpandeb2a86582011-08-17 00:01:33 -07001800 qemu_mutex_lock_ramlist();
Michael S. Tsirkin9b8424d2014-12-15 22:55:32 +02001801 new_block->offset = find_ram_offset(new_block->max_length);
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001802
1803 if (!new_block->host) {
1804 if (xen_enabled()) {
Michael S. Tsirkin9b8424d2014-12-15 22:55:32 +02001805 xen_ram_alloc(new_block->offset, new_block->max_length,
Markus Armbruster37aa7a02016-01-14 16:09:39 +01001806 new_block->mr, &err);
1807 if (err) {
1808 error_propagate(errp, err);
1809 qemu_mutex_unlock_ramlist();
Paolo Bonzini39c350e2016-03-09 18:14:01 +01001810 return;
Markus Armbruster37aa7a02016-01-14 16:09:39 +01001811 }
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001812 } else {
David Hildenbrand25459eb2021-03-03 14:09:16 +01001813 new_block->host = qemu_anon_ram_alloc(new_block->max_length,
1814 &new_block->mr->align,
David Hildenbrand8dbe22c2021-05-10 13:43:21 +02001815 shared, noreserve);
Markus Armbruster39228252013-07-31 15:11:11 +02001816 if (!new_block->host) {
Hu Taoef701d72014-09-09 13:27:54 +08001817 error_setg_errno(errp, errno,
1818 "cannot set up guest memory '%s'",
1819 memory_region_name(new_block->mr));
1820 qemu_mutex_unlock_ramlist();
Paolo Bonzini39c350e2016-03-09 18:14:01 +01001821 return;
Markus Armbruster39228252013-07-31 15:11:11 +02001822 }
Michael S. Tsirkin9b8424d2014-12-15 22:55:32 +02001823 memory_try_enable_merging(new_block->host, new_block->max_length);
Yoshiaki Tamura6977dfe2010-08-18 15:41:49 +09001824 }
1825 }
Cam Macdonell84b89d72010-07-26 18:10:57 -06001826
Li Zhijiandd631692015-07-02 20:18:06 +08001827 new_ram_size = MAX(old_ram_size,
1828 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1829 if (new_ram_size > old_ram_size) {
Stefan Hajnoczi5b82b702016-01-25 13:33:20 +00001830 dirty_memory_extend(old_ram_size, new_ram_size);
Li Zhijiandd631692015-07-02 20:18:06 +08001831 }
Mike Day0d53d9f2015-01-21 13:45:24 +01001832 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1833 * QLIST (which has an RCU-friendly variant) does not have insertion at
1834 * tail, so save the last element in last_block.
1835 */
Peter Xu99e15582017-05-12 12:17:39 +08001836 RAMBLOCK_FOREACH(block) {
Mike Day0d53d9f2015-01-21 13:45:24 +01001837 last_block = block;
Michael S. Tsirkin9b8424d2014-12-15 22:55:32 +02001838 if (block->max_length < new_block->max_length) {
Paolo Bonziniabb26d62012-11-14 16:00:51 +01001839 break;
1840 }
1841 }
1842 if (block) {
Mike Day0dc3f442013-09-05 14:41:35 -04001843 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
Mike Day0d53d9f2015-01-21 13:45:24 +01001844 } else if (last_block) {
Mike Day0dc3f442013-09-05 14:41:35 -04001845 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
Mike Day0d53d9f2015-01-21 13:45:24 +01001846 } else { /* list is empty */
Mike Day0dc3f442013-09-05 14:41:35 -04001847 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
Paolo Bonziniabb26d62012-11-14 16:00:51 +01001848 }
Paolo Bonzini0d6d3c82012-11-14 15:45:02 +01001849 ram_list.mru_block = NULL;
Cam Macdonell84b89d72010-07-26 18:10:57 -06001850
Mike Day0dc3f442013-09-05 14:41:35 -04001851 /* Write list before version */
1852 smp_wmb();
Umesh Deshpandef798b072011-08-18 11:41:17 -07001853 ram_list.version++;
Umesh Deshpandeb2a86582011-08-17 00:01:33 -07001854 qemu_mutex_unlock_ramlist();
Umesh Deshpandef798b072011-08-18 11:41:17 -07001855
Michael S. Tsirkin9b8424d2014-12-15 22:55:32 +02001856 cpu_physical_memory_set_dirty_range(new_block->offset,
Paolo Bonzini58d27072015-03-23 11:56:01 +01001857 new_block->used_length,
1858 DIRTY_CLIENTS_ALL);
Cam Macdonell84b89d72010-07-26 18:10:57 -06001859
Paolo Bonzinia904c912015-01-21 16:18:35 +01001860 if (new_block->host) {
1861 qemu_ram_setup_dump(new_block->host, new_block->max_length);
1862 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
Alexander Bulekova028ede2020-02-19 23:11:09 -05001863 /*
1864 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
1865 * Configure it unless the machine is a qtest server, in which case
1866 * KVM is not used and it may be forked (eg for fuzzing purposes).
1867 */
1868 if (!qtest_enabled()) {
1869 qemu_madvise(new_block->host, new_block->max_length,
1870 QEMU_MADV_DONTFORK);
1871 }
David Hildenbrand8f443042021-04-29 13:27:00 +02001872 ram_block_notify_add(new_block->host, new_block->used_length,
1873 new_block->max_length);
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001874 }
Cam Macdonell84b89d72010-07-26 18:10:57 -06001875}
1876
Hikaru Nishidad5dbde42018-09-24 21:32:05 +09001877#ifdef CONFIG_POSIX
Marc-André Lureau38b33622017-06-02 18:12:23 +04001878RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
Jagannathan Raman44a4ff32021-01-29 11:46:04 -05001879 uint32_t ram_flags, int fd, off_t offset,
1880 bool readonly, Error **errp)
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001881{
1882 RAMBlock *new_block;
Hu Taoef701d72014-09-09 13:27:54 +08001883 Error *local_err = NULL;
Jingqi Liuce317be2020-04-29 16:50:09 +08001884 int64_t file_size, file_align;
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001885
Junyan Hea4de8552018-07-18 15:48:00 +08001886 /* Just support these ram flags by now. */
Sean Christopherson56918a12021-07-19 19:21:04 +08001887 assert((ram_flags & ~(RAM_SHARED | RAM_PMEM | RAM_NORESERVE |
Steve Sistareb0182e52023-06-07 08:18:36 -07001888 RAM_PROTECTED | RAM_NAMED_FILE)) == 0);
Junyan Hea4de8552018-07-18 15:48:00 +08001889
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001890 if (xen_enabled()) {
Paolo Bonzini7f56e742014-05-14 17:43:20 +08001891 error_setg(errp, "-mem-path not supported with Xen");
Fam Zheng528f46a2016-03-01 14:18:18 +08001892 return NULL;
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001893 }
1894
Marc-André Lureaue45e7ae2017-06-02 18:12:21 +04001895 if (kvm_enabled() && !kvm_has_sync_mmu()) {
1896 error_setg(errp,
1897 "host lacks kvm mmu notifiers, -mem-path unsupported");
1898 return NULL;
1899 }
1900
Dr. David Alan Gilbert4ed023c2015-11-05 18:11:16 +00001901 size = HOST_PAGE_ALIGN(size);
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001902 file_size = get_file_size(fd);
Alexander Graf4b870dc2023-04-03 22:14:21 +00001903 if (file_size > offset && file_size < (offset + size)) {
Igor Mammedovc001c3b2020-02-19 11:09:48 -05001904 error_setg(errp, "backing store size 0x%" PRIx64
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001905 " does not match 'size' option 0x" RAM_ADDR_FMT,
Igor Mammedovc001c3b2020-02-19 11:09:48 -05001906 file_size, size);
Marc-André Lureau8d37b032017-06-02 18:12:22 +04001907 return NULL;
1908 }
1909
Jingqi Liuce317be2020-04-29 16:50:09 +08001910 file_align = get_file_align(fd);
Peter Maydell8f1bdb02021-08-12 16:06:24 +01001911 if (file_align > 0 && file_align > mr->align) {
Jingqi Liuce317be2020-04-29 16:50:09 +08001912 error_setg(errp, "backing store align 0x%" PRIx64
Jingqi Liu5f509752020-04-29 16:50:10 +08001913 " is larger than 'align' option 0x%" PRIx64,
Jingqi Liuce317be2020-04-29 16:50:09 +08001914 file_align, mr->align);
1915 return NULL;
1916 }
1917
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001918 new_block = g_malloc0(sizeof(*new_block));
1919 new_block->mr = mr;
Michael S. Tsirkin9b8424d2014-12-15 22:55:32 +02001920 new_block->used_length = size;
1921 new_block->max_length = size;
Junyan Hecbfc0172018-07-18 15:47:58 +08001922 new_block->flags = ram_flags;
Stefan Hajnoczi369d6dc2021-01-04 17:13:18 +00001923 new_block->host = file_ram_alloc(new_block, size, fd, readonly,
Jagannathan Raman44a4ff32021-01-29 11:46:04 -05001924 !file_size, offset, errp);
Paolo Bonzini7f56e742014-05-14 17:43:20 +08001925 if (!new_block->host) {
1926 g_free(new_block);
Fam Zheng528f46a2016-03-01 14:18:18 +08001927 return NULL;
Paolo Bonzini7f56e742014-05-14 17:43:20 +08001928 }
1929
David Hildenbrand7ce18ca2021-04-06 10:01:24 +02001930 ram_block_add(new_block, &local_err);
Hu Taoef701d72014-09-09 13:27:54 +08001931 if (local_err) {
1932 g_free(new_block);
1933 error_propagate(errp, local_err);
Fam Zheng528f46a2016-03-01 14:18:18 +08001934 return NULL;
Hu Taoef701d72014-09-09 13:27:54 +08001935 }
Fam Zheng528f46a2016-03-01 14:18:18 +08001936 return new_block;
Marc-André Lureau38b33622017-06-02 18:12:23 +04001937
1938}
1939
1940
1941RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
Junyan Hecbfc0172018-07-18 15:47:58 +08001942 uint32_t ram_flags, const char *mem_path,
Alexander Graf4b870dc2023-04-03 22:14:21 +00001943 off_t offset, bool readonly, Error **errp)
Marc-André Lureau38b33622017-06-02 18:12:23 +04001944{
1945 int fd;
1946 bool created;
1947 RAMBlock *block;
1948
Stefan Hajnoczi369d6dc2021-01-04 17:13:18 +00001949 fd = file_ram_open(mem_path, memory_region_name(mr), readonly, &created,
1950 errp);
Marc-André Lureau38b33622017-06-02 18:12:23 +04001951 if (fd < 0) {
1952 return NULL;
1953 }
1954
Alexander Graf4b870dc2023-04-03 22:14:21 +00001955 block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, offset, readonly,
1956 errp);
Marc-André Lureau38b33622017-06-02 18:12:23 +04001957 if (!block) {
1958 if (created) {
1959 unlink(mem_path);
1960 }
1961 close(fd);
1962 return NULL;
1963 }
1964
1965 return block;
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001966}
Paolo Bonzini0b183fc2014-05-14 17:43:19 +08001967#endif
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001968
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001969static
Fam Zheng528f46a2016-03-01 14:18:18 +08001970RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
1971 void (*resized)(const char*,
1972 uint64_t length,
1973 void *host),
David Hildenbrandebef62d2021-05-10 13:43:19 +02001974 void *host, uint32_t ram_flags,
Fam Zheng528f46a2016-03-01 14:18:18 +08001975 MemoryRegion *mr, Error **errp)
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001976{
1977 RAMBlock *new_block;
Hu Taoef701d72014-09-09 13:27:54 +08001978 Error *local_err = NULL;
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001979
David Hildenbrand8dbe22c2021-05-10 13:43:21 +02001980 assert((ram_flags & ~(RAM_SHARED | RAM_RESIZEABLE | RAM_PREALLOC |
1981 RAM_NORESERVE)) == 0);
David Hildenbrandebef62d2021-05-10 13:43:19 +02001982 assert(!host ^ (ram_flags & RAM_PREALLOC));
1983
Dr. David Alan Gilbert4ed023c2015-11-05 18:11:16 +00001984 size = HOST_PAGE_ALIGN(size);
1985 max_size = HOST_PAGE_ALIGN(max_size);
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001986 new_block = g_malloc0(sizeof(*new_block));
1987 new_block->mr = mr;
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001988 new_block->resized = resized;
Michael S. Tsirkin9b8424d2014-12-15 22:55:32 +02001989 new_block->used_length = size;
1990 new_block->max_length = max_size;
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02001991 assert(max_size >= size);
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001992 new_block->fd = -1;
Marc-André Lureau8e3b0cb2022-03-23 19:57:22 +04001993 new_block->page_size = qemu_real_host_page_size();
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08001994 new_block->host = host;
David Hildenbrandebef62d2021-05-10 13:43:19 +02001995 new_block->flags = ram_flags;
David Hildenbrand7ce18ca2021-04-06 10:01:24 +02001996 ram_block_add(new_block, &local_err);
Hu Taoef701d72014-09-09 13:27:54 +08001997 if (local_err) {
1998 g_free(new_block);
1999 error_propagate(errp, local_err);
Fam Zheng528f46a2016-03-01 14:18:18 +08002000 return NULL;
Hu Taoef701d72014-09-09 13:27:54 +08002001 }
Fam Zheng528f46a2016-03-01 14:18:18 +08002002 return new_block;
Paolo Bonzinie1c57ab2014-05-14 17:43:18 +08002003}
2004
Fam Zheng528f46a2016-03-01 14:18:18 +08002005RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02002006 MemoryRegion *mr, Error **errp)
2007{
David Hildenbrandebef62d2021-05-10 13:43:19 +02002008 return qemu_ram_alloc_internal(size, size, NULL, host, RAM_PREALLOC, mr,
2009 errp);
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02002010}
2011
David Hildenbrandebef62d2021-05-10 13:43:19 +02002012RAMBlock *qemu_ram_alloc(ram_addr_t size, uint32_t ram_flags,
Marcel Apfelbaum06329cc2017-12-13 16:37:37 +02002013 MemoryRegion *mr, Error **errp)
pbrook94a6b542009-04-11 17:15:54 +00002014{
David Hildenbrand8dbe22c2021-05-10 13:43:21 +02002015 assert((ram_flags & ~(RAM_SHARED | RAM_NORESERVE)) == 0);
David Hildenbrandebef62d2021-05-10 13:43:19 +02002016 return qemu_ram_alloc_internal(size, size, NULL, NULL, ram_flags, mr, errp);
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02002017}
2018
Fam Zheng528f46a2016-03-01 14:18:18 +08002019RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
Michael S. Tsirkin62be4e32014-11-12 14:27:41 +02002020 void (*resized)(const char*,
2021 uint64_t length,
2022 void *host),
2023 MemoryRegion *mr, Error **errp)
2024{
David Hildenbrandebef62d2021-05-10 13:43:19 +02002025 return qemu_ram_alloc_internal(size, maxsz, resized, NULL,
2026 RAM_RESIZEABLE, mr, errp);
pbrook94a6b542009-04-11 17:15:54 +00002027}
bellarde9a1ab12007-02-08 23:08:38 +00002028
Paolo Bonzini43771532013-09-09 17:58:40 +02002029static void reclaim_ramblock(RAMBlock *block)
2030{
2031 if (block->flags & RAM_PREALLOC) {
2032 ;
2033 } else if (xen_enabled()) {
2034 xen_invalidate_map_cache_entry(block->host);
2035#ifndef _WIN32
2036 } else if (block->fd >= 0) {
Murilo Opsfelder Araujo53adb9d2019-01-30 21:36:05 -02002037 qemu_ram_munmap(block->fd, block->host, block->max_length);
Paolo Bonzini43771532013-09-09 17:58:40 +02002038 close(block->fd);
2039#endif
2040 } else {
2041 qemu_anon_ram_free(block->host, block->max_length);
2042 }
2043 g_free(block);
2044}
2045
Fam Zhengf1060c52016-03-01 14:18:22 +08002046void qemu_ram_free(RAMBlock *block)
bellarde9a1ab12007-02-08 23:08:38 +00002047{
Marc-André Lureau85bc2a12016-03-29 13:20:51 +02002048 if (!block) {
2049 return;
2050 }
2051
Paolo Bonzini0987d732016-12-21 00:31:36 +08002052 if (block->host) {
David Hildenbrand8f443042021-04-29 13:27:00 +02002053 ram_block_notify_remove(block->host, block->used_length,
2054 block->max_length);
Paolo Bonzini0987d732016-12-21 00:31:36 +08002055 }
2056
Umesh Deshpandeb2a86582011-08-17 00:01:33 -07002057 qemu_mutex_lock_ramlist();
Fam Zhengf1060c52016-03-01 14:18:22 +08002058 QLIST_REMOVE_RCU(block, next);
2059 ram_list.mru_block = NULL;
2060 /* Write list before version */
2061 smp_wmb();
2062 ram_list.version++;
2063 call_rcu(block, reclaim_ramblock, rcu);
Umesh Deshpandeb2a86582011-08-17 00:01:33 -07002064 qemu_mutex_unlock_ramlist();
bellarde9a1ab12007-02-08 23:08:38 +00002065}
2066
Huang Yingcd19cfa2011-03-02 08:56:19 +01002067#ifndef _WIN32
2068void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2069{
2070 RAMBlock *block;
2071 ram_addr_t offset;
2072 int flags;
2073 void *area, *vaddr;
2074
Peter Xu99e15582017-05-12 12:17:39 +08002075 RAMBLOCK_FOREACH(block) {
Huang Yingcd19cfa2011-03-02 08:56:19 +01002076 offset = addr - block->offset;
Michael S. Tsirkin9b8424d2014-12-15 22:55:32 +02002077 if (offset < block->max_length) {
Michael S. Tsirkin1240be22014-11-12 11:44:41 +02002078 vaddr = ramblock_ptr(block, offset);
Paolo Bonzini7bd4f432014-05-14 17:43:22 +08002079 if (block->flags & RAM_PREALLOC) {
Huang Yingcd19cfa2011-03-02 08:56:19 +01002080 ;
Markus Armbrusterdfeaf2a2013-07-31 15:11:05 +02002081 } else if (xen_enabled()) {
2082 abort();
Huang Yingcd19cfa2011-03-02 08:56:19 +01002083 } else {
2084 flags = MAP_FIXED;
David Hildenbranddbb92ee2021-04-06 10:01:26 +02002085 flags |= block->flags & RAM_SHARED ?
2086 MAP_SHARED : MAP_PRIVATE;
David Hildenbrandd94e0bc2021-05-10 13:43:22 +02002087 flags |= block->flags & RAM_NORESERVE ? MAP_NORESERVE : 0;
Markus Armbruster3435f392013-07-31 15:11:07 +02002088 if (block->fd >= 0) {
Markus Armbruster3435f392013-07-31 15:11:07 +02002089 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
Alexander Graf4b870dc2023-04-03 22:14:21 +00002090 flags, block->fd, offset + block->fd_offset);
Huang Yingcd19cfa2011-03-02 08:56:19 +01002091 } else {
David Hildenbranddbb92ee2021-04-06 10:01:26 +02002092 flags |= MAP_ANONYMOUS;
Huang Yingcd19cfa2011-03-02 08:56:19 +01002093 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2094 flags, -1, 0);
Huang Yingcd19cfa2011-03-02 08:56:19 +01002095 }
2096 if (area != vaddr) {
Alistair Francis493d89b2018-02-03 09:43:14 +01002097 error_report("Could not remap addr: "
2098 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2099 length, addr);
Huang Yingcd19cfa2011-03-02 08:56:19 +01002100 exit(1);
2101 }
Luiz Capitulino8490fc72012-09-05 16:50:16 -03002102 memory_try_enable_merging(vaddr, length);
Jason Baronddb97f12012-08-02 15:44:16 -04002103 qemu_ram_setup_dump(vaddr, length);
Huang Yingcd19cfa2011-03-02 08:56:19 +01002104 }
Huang Yingcd19cfa2011-03-02 08:56:19 +01002105 }
2106 }
2107}
2108#endif /* !_WIN32 */
2109
Paolo Bonzini1b5ec232013-05-06 14:36:15 +02002110/* Return a host pointer to ram allocated with qemu_ram_alloc.
Mike Dayae3a7042013-09-05 14:41:35 -04002111 * This should not be used for general purpose DMA. Use address_space_map
2112 * or address_space_rw instead. For local memory (e.g. video ram) that the
2113 * device owns, use memory_region_get_ram_ptr.
Mike Day0dc3f442013-09-05 14:41:35 -04002114 *
Paolo Bonzini49b24af2015-12-16 10:30:47 +01002115 * Called within RCU critical section.
Paolo Bonzini1b5ec232013-05-06 14:36:15 +02002116 */
Paolo Bonzini0878d0e2016-02-22 11:02:12 +01002117void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
Paolo Bonzini1b5ec232013-05-06 14:36:15 +02002118{
Gonglei3655cb92016-02-20 10:35:20 +08002119 RAMBlock *block = ram_block;
2120
2121 if (block == NULL) {
2122 block = qemu_get_ram_block(addr);
Paolo Bonzini0878d0e2016-02-22 11:02:12 +01002123 addr -= block->offset;
Gonglei3655cb92016-02-20 10:35:20 +08002124 }
Mike Dayae3a7042013-09-05 14:41:35 -04002125
2126 if (xen_enabled() && block->host == NULL) {
Paolo Bonzini0d6d3c82012-11-14 15:45:02 +01002127 /* We need to check if the requested address is in the RAM
2128 * because we don't want to map the entire memory in QEMU.
2129 * In that case just map until the end of the page.
2130 */
2131 if (block->offset == 0) {
Stefano Stabellini1ff7c592017-05-03 14:00:35 -07002132 return xen_map_cache(addr, 0, 0, false);
Paolo Bonzini0d6d3c82012-11-14 15:45:02 +01002133 }
Mike Dayae3a7042013-09-05 14:41:35 -04002134
Stefano Stabellini1ff7c592017-05-03 14:00:35 -07002135 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
Paolo Bonzini0d6d3c82012-11-14 15:45:02 +01002136 }
Paolo Bonzini0878d0e2016-02-22 11:02:12 +01002137 return ramblock_ptr(block, addr);
pbrookdc828ca2009-04-09 22:21:07 +00002138}
2139
Paolo Bonzini0878d0e2016-02-22 11:02:12 +01002140/* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
Mike Dayae3a7042013-09-05 14:41:35 -04002141 * but takes a size argument.
Mike Day0dc3f442013-09-05 14:41:35 -04002142 *
Paolo Bonzinie81bcda2015-12-16 10:31:26 +01002143 * Called within RCU critical section.
Mike Dayae3a7042013-09-05 14:41:35 -04002144 */
Gonglei3655cb92016-02-20 10:35:20 +08002145static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
Anthony PERARDf5aa69b2017-07-26 17:53:26 +01002146 hwaddr *size, bool lock)
Stefano Stabellini38bee5d2011-05-19 18:35:45 +01002147{
Gonglei3655cb92016-02-20 10:35:20 +08002148 RAMBlock *block = ram_block;
Stefano Stabellini8ab934f2011-06-27 18:26:06 +01002149 if (*size == 0) {
2150 return NULL;
2151 }
Paolo Bonzinie81bcda2015-12-16 10:31:26 +01002152
Gonglei3655cb92016-02-20 10:35:20 +08002153 if (block == NULL) {
2154 block = qemu_get_ram_block(addr);
Paolo Bonzini0878d0e2016-02-22 11:02:12 +01002155 addr -= block->offset;
Gonglei3655cb92016-02-20 10:35:20 +08002156 }
Paolo Bonzini0878d0e2016-02-22 11:02:12 +01002157 *size = MIN(*size, block->max_length - addr);
Paolo Bonzinie81bcda2015-12-16 10:31:26 +01002158
2159 if (xen_enabled() && block->host == NULL) {
2160 /* We need to check if the requested address is in the RAM
2161 * because we don't want to map the entire memory in QEMU.
2162 * In that case just map the requested area.
2163 */
2164 if (block->offset == 0) {
Anthony PERARDf5aa69b2017-07-26 17:53:26 +01002165 return xen_map_cache(addr, *size, lock, lock);
Stefano Stabellini38bee5d2011-05-19 18:35:45 +01002166 }
2167
Anthony PERARDf5aa69b2017-07-26 17:53:26 +01002168 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
Stefano Stabellini38bee5d2011-05-19 18:35:45 +01002169 }
Paolo Bonzinie81bcda2015-12-16 10:31:26 +01002170
Paolo Bonzini0878d0e2016-02-22 11:02:12 +01002171 return ramblock_ptr(block, addr);
Stefano Stabellini38bee5d2011-05-19 18:35:45 +01002172}
2173
Dr. David Alan Gilbertf90bb712018-03-12 17:20:57 +00002174/* Return the offset of a hostpointer within a ramblock */
2175ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2176{
2177 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2178 assert((uintptr_t)host >= (uintptr_t)rb->host);
2179 assert(res < rb->max_length);
2180
2181 return res;
2182}
2183
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002184/*
2185 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2186 * in that RAMBlock.
2187 *
2188 * ptr: Host pointer to look up
2189 * round_offset: If true round the result offset down to a page boundary
2190 * *ram_addr: set to result ram_addr
2191 * *offset: set to result offset within the RAMBlock
2192 *
2193 * Returns: RAMBlock (or NULL if not found)
Mike Dayae3a7042013-09-05 14:41:35 -04002194 *
2195 * By the time this function returns, the returned pointer is not protected
2196 * by RCU anymore. If the caller is not within an RCU critical section and
2197 * does not hold the iothread lock, it must have other means of protecting the
2198 * pointer, such as a reference to the region that includes the incoming
2199 * ram_addr_t.
2200 */
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002201RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002202 ram_addr_t *offset)
pbrook5579c7f2009-04-11 14:47:08 +00002203{
pbrook94a6b542009-04-11 17:15:54 +00002204 RAMBlock *block;
2205 uint8_t *host = ptr;
2206
Jan Kiszka868bb332011-06-21 22:59:09 +02002207 if (xen_enabled()) {
Paolo Bonzinif615f392016-05-26 10:07:50 +02002208 ram_addr_t ram_addr;
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +01002209 RCU_READ_LOCK_GUARD();
Paolo Bonzinif615f392016-05-26 10:07:50 +02002210 ram_addr = xen_ram_addr_from_mapcache(ptr);
2211 block = qemu_get_ram_block(ram_addr);
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002212 if (block) {
Anthony PERARDd6b6aec2016-06-09 16:56:17 +01002213 *offset = ram_addr - block->offset;
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002214 }
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002215 return block;
Stefano Stabellini712c2b42011-05-19 18:35:46 +01002216 }
2217
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +01002218 RCU_READ_LOCK_GUARD();
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01002219 block = qatomic_rcu_read(&ram_list.mru_block);
Michael S. Tsirkin9b8424d2014-12-15 22:55:32 +02002220 if (block && block->host && host - block->host < block->max_length) {
Paolo Bonzini23887b72013-05-06 14:28:39 +02002221 goto found;
2222 }
2223
Peter Xu99e15582017-05-12 12:17:39 +08002224 RAMBLOCK_FOREACH(block) {
Jun Nakajima432d2682010-08-31 16:41:25 +01002225 /* This case append when the block is not mapped. */
2226 if (block->host == NULL) {
2227 continue;
2228 }
Michael S. Tsirkin9b8424d2014-12-15 22:55:32 +02002229 if (host - block->host < block->max_length) {
Paolo Bonzini23887b72013-05-06 14:28:39 +02002230 goto found;
Alex Williamsonf471a172010-06-11 11:11:42 -06002231 }
pbrook94a6b542009-04-11 17:15:54 +00002232 }
Jun Nakajima432d2682010-08-31 16:41:25 +01002233
Paolo Bonzini1b5ec232013-05-06 14:36:15 +02002234 return NULL;
Paolo Bonzini23887b72013-05-06 14:28:39 +02002235
2236found:
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002237 *offset = (host - block->host);
2238 if (round_offset) {
2239 *offset &= TARGET_PAGE_MASK;
2240 }
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002241 return block;
2242}
2243
Dr. David Alan Gilberte3dd7492015-11-05 18:10:33 +00002244/*
2245 * Finds the named RAMBlock
2246 *
2247 * name: The name of RAMBlock to find
2248 *
2249 * Returns: RAMBlock (or NULL if not found)
2250 */
2251RAMBlock *qemu_ram_block_by_name(const char *name)
2252{
2253 RAMBlock *block;
2254
Peter Xu99e15582017-05-12 12:17:39 +08002255 RAMBLOCK_FOREACH(block) {
Dr. David Alan Gilberte3dd7492015-11-05 18:10:33 +00002256 if (!strcmp(name, block->idstr)) {
2257 return block;
2258 }
2259 }
2260
2261 return NULL;
2262}
2263
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002264/* Some of the softmmu routines need to translate from a host pointer
2265 (typically a TLB entry) back to a ram offset. */
Paolo Bonzini07bdaa42016-03-25 12:55:08 +01002266ram_addr_t qemu_ram_addr_from_host(void *ptr)
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002267{
2268 RAMBlock *block;
Paolo Bonzinif615f392016-05-26 10:07:50 +02002269 ram_addr_t offset;
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002270
Paolo Bonzinif615f392016-05-26 10:07:50 +02002271 block = qemu_ram_block_from_host(ptr, false, &offset);
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002272 if (!block) {
Paolo Bonzini07bdaa42016-03-25 12:55:08 +01002273 return RAM_ADDR_INVALID;
Dr. David Alan Gilbert422148d2015-11-05 18:10:32 +00002274 }
2275
Paolo Bonzini07bdaa42016-03-25 12:55:08 +01002276 return block->offset + offset;
Marcelo Tosattie8902612010-10-11 15:31:19 -03002277}
Alex Williamsonf471a172010-06-11 11:11:42 -06002278
Richard Henderson97e03462022-08-10 12:04:15 -07002279ram_addr_t qemu_ram_addr_from_host_nofail(void *ptr)
2280{
2281 ram_addr_t ram_addr;
2282
2283 ram_addr = qemu_ram_addr_from_host(ptr);
2284 if (ram_addr == RAM_ADDR_INVALID) {
2285 error_report("Bad ram pointer %p", ptr);
2286 abort();
2287 }
2288 return ram_addr;
2289}
2290
Paolo Bonzinib2a44fc2018-03-05 00:19:49 +01002291static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
Philippe Mathieu-Daudéa152be42020-02-19 19:52:44 +01002292 MemTxAttrs attrs, void *buf, hwaddr len);
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002293static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
Philippe Mathieu-Daudéa152be42020-02-19 19:52:44 +01002294 const void *buf, hwaddr len);
Li Zhijian0c249ff2019-01-17 20:49:01 +08002295static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
Peter Maydelleace72b2018-05-31 14:50:52 +01002296 bool is_write, MemTxAttrs attrs);
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002297
Peter Maydellf25a49e2015-04-26 16:49:24 +01002298static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2299 unsigned len, MemTxAttrs attrs)
blueswir1db7b5422007-05-26 17:36:03 +00002300{
Jan Kiszkaacc9d802013-05-26 21:55:37 +02002301 subpage_t *subpage = opaque;
Paolo Bonziniff6cff72014-12-22 13:11:39 +01002302 uint8_t buf[8];
Peter Maydell5c9eb022015-04-26 16:49:24 +01002303 MemTxResult res;
Paolo Bonzini791af8c2013-05-24 16:10:39 +02002304
blueswir1db7b5422007-05-26 17:36:03 +00002305#if defined(DEBUG_SUBPAGE)
Philippe Mathieu-Daudé883f2c52023-01-10 22:29:47 +01002306 printf("%s: subpage %p len %u addr " HWADDR_FMT_plx "\n", __func__,
Jan Kiszkaacc9d802013-05-26 21:55:37 +02002307 subpage, len, addr);
blueswir1db7b5422007-05-26 17:36:03 +00002308#endif
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002309 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
Peter Maydell5c9eb022015-04-26 16:49:24 +01002310 if (res) {
2311 return res;
Peter Maydellf25a49e2015-04-26 16:49:24 +01002312 }
Peter Maydell6d3ede52018-06-15 14:57:14 +01002313 *data = ldn_p(buf, len);
2314 return MEMTX_OK;
blueswir1db7b5422007-05-26 17:36:03 +00002315}
2316
Peter Maydellf25a49e2015-04-26 16:49:24 +01002317static MemTxResult subpage_write(void *opaque, hwaddr addr,
2318 uint64_t value, unsigned len, MemTxAttrs attrs)
blueswir1db7b5422007-05-26 17:36:03 +00002319{
Jan Kiszkaacc9d802013-05-26 21:55:37 +02002320 subpage_t *subpage = opaque;
Paolo Bonziniff6cff72014-12-22 13:11:39 +01002321 uint8_t buf[8];
Jan Kiszkaacc9d802013-05-26 21:55:37 +02002322
blueswir1db7b5422007-05-26 17:36:03 +00002323#if defined(DEBUG_SUBPAGE)
Philippe Mathieu-Daudé883f2c52023-01-10 22:29:47 +01002324 printf("%s: subpage %p len %u addr " HWADDR_FMT_plx
Jan Kiszkaacc9d802013-05-26 21:55:37 +02002325 " value %"PRIx64"\n",
2326 __func__, subpage, len, addr, value);
blueswir1db7b5422007-05-26 17:36:03 +00002327#endif
Peter Maydell6d3ede52018-06-15 14:57:14 +01002328 stn_p(buf, len, value);
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002329 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
blueswir1db7b5422007-05-26 17:36:03 +00002330}
2331
Paolo Bonzinic353e4c2013-05-24 14:02:39 +02002332static bool subpage_accepts(void *opaque, hwaddr addr,
Peter Maydell8372d382018-05-31 14:50:52 +01002333 unsigned len, bool is_write,
2334 MemTxAttrs attrs)
Paolo Bonzinic353e4c2013-05-24 14:02:39 +02002335{
Jan Kiszkaacc9d802013-05-26 21:55:37 +02002336 subpage_t *subpage = opaque;
Paolo Bonzinic353e4c2013-05-24 14:02:39 +02002337#if defined(DEBUG_SUBPAGE)
Philippe Mathieu-Daudé883f2c52023-01-10 22:29:47 +01002338 printf("%s: subpage %p %c len %u addr " HWADDR_FMT_plx "\n",
Jan Kiszkaacc9d802013-05-26 21:55:37 +02002339 __func__, subpage, is_write ? 'w' : 'r', len, addr);
Paolo Bonzinic353e4c2013-05-24 14:02:39 +02002340#endif
2341
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002342 return flatview_access_valid(subpage->fv, addr + subpage->base,
Peter Maydelleace72b2018-05-31 14:50:52 +01002343 len, is_write, attrs);
Paolo Bonzinic353e4c2013-05-24 14:02:39 +02002344}
2345
Avi Kivity70c68e42012-01-02 12:32:48 +02002346static const MemoryRegionOps subpage_ops = {
Peter Maydellf25a49e2015-04-26 16:49:24 +01002347 .read_with_attrs = subpage_read,
2348 .write_with_attrs = subpage_write,
Paolo Bonziniff6cff72014-12-22 13:11:39 +01002349 .impl.min_access_size = 1,
2350 .impl.max_access_size = 8,
2351 .valid.min_access_size = 1,
2352 .valid.max_access_size = 8,
Paolo Bonzinic353e4c2013-05-24 14:02:39 +02002353 .valid.accepts = subpage_accepts,
Avi Kivity70c68e42012-01-02 12:32:48 +02002354 .endianness = DEVICE_NATIVE_ENDIAN,
blueswir1db7b5422007-05-26 17:36:03 +00002355};
2356
Wei Yangb797ab12019-03-21 16:25:53 +08002357static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2358 uint16_t section)
blueswir1db7b5422007-05-26 17:36:03 +00002359{
2360 int idx, eidx;
2361
2362 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2363 return -1;
2364 idx = SUBPAGE_IDX(start);
2365 eidx = SUBPAGE_IDX(end);
2366#if defined(DEBUG_SUBPAGE)
Amos Kong016e9d62013-09-27 09:25:38 +08002367 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2368 __func__, mmio, start, end, idx, eidx, section);
blueswir1db7b5422007-05-26 17:36:03 +00002369#endif
blueswir1db7b5422007-05-26 17:36:03 +00002370 for (; idx <= eidx; idx++) {
Avi Kivity5312bd82012-02-12 18:32:55 +02002371 mmio->sub_section[idx] = section;
blueswir1db7b5422007-05-26 17:36:03 +00002372 }
2373
2374 return 0;
2375}
2376
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002377static subpage_t *subpage_init(FlatView *fv, hwaddr base)
blueswir1db7b5422007-05-26 17:36:03 +00002378{
Anthony Liguoric227f092009-10-01 16:12:16 -05002379 subpage_t *mmio;
blueswir1db7b5422007-05-26 17:36:03 +00002380
Wei Yangb797ab12019-03-21 16:25:53 +08002381 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
Vijaya Kumar K2615fab2016-10-24 16:26:49 +01002382 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002383 mmio->fv = fv;
aliguori1eec6142009-02-05 22:06:18 +00002384 mmio->base = base;
Paolo Bonzini2c9b15c2013-06-06 05:41:28 -04002385 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
Peter Crosthwaiteb4fefef2014-06-05 23:15:52 -07002386 NULL, TARGET_PAGE_SIZE);
Avi Kivityb3b00c72012-01-02 13:20:11 +02002387 mmio->iomem.subpage = true;
blueswir1db7b5422007-05-26 17:36:03 +00002388#if defined(DEBUG_SUBPAGE)
Philippe Mathieu-Daudé883f2c52023-01-10 22:29:47 +01002389 printf("%s: %p base " HWADDR_FMT_plx " len %08x\n", __func__,
Amos Kong016e9d62013-09-27 09:25:38 +08002390 mmio, base, TARGET_PAGE_SIZE);
blueswir1db7b5422007-05-26 17:36:03 +00002391#endif
blueswir1db7b5422007-05-26 17:36:03 +00002392
2393 return mmio;
2394}
2395
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002396static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
Avi Kivity5312bd82012-02-12 18:32:55 +02002397{
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002398 assert(fv);
Avi Kivity5312bd82012-02-12 18:32:55 +02002399 MemoryRegionSection section = {
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002400 .fv = fv,
Avi Kivity5312bd82012-02-12 18:32:55 +02002401 .mr = mr,
2402 .offset_within_address_space = 0,
2403 .offset_within_region = 0,
Paolo Bonzini052e87b2013-05-27 10:08:27 +02002404 .size = int128_2_64(),
Avi Kivity5312bd82012-02-12 18:32:55 +02002405 };
2406
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +02002407 return phys_section_add(map, &section);
Avi Kivity5312bd82012-02-12 18:32:55 +02002408}
2409
Peter Maydell2d54f192018-06-15 14:57:14 +01002410MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2411 hwaddr index, MemTxAttrs attrs)
Avi Kivityaa102232012-03-08 17:06:55 +02002412{
Peter Maydella54c87b2016-01-21 14:15:05 +00002413 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2414 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01002415 AddressSpaceDispatch *d = qatomic_rcu_read(&cpuas->memory_dispatch);
Paolo Bonzini79e2b9a2015-01-21 12:09:14 +01002416 MemoryRegionSection *sections = d->map.sections;
Paolo Bonzini9d82b5a2013-08-16 08:26:30 +02002417
Peter Maydell2d54f192018-06-15 14:57:14 +01002418 return &sections[index & ~TARGET_PAGE_MASK];
Avi Kivityaa102232012-03-08 17:06:55 +02002419}
2420
Avi Kivitye9179ce2009-06-14 11:38:52 +03002421static void io_mem_init(void)
2422{
Paolo Bonzini2c9b15c2013-06-06 05:41:28 -04002423 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
Paolo Bonzini1f6245e2014-06-13 10:48:06 +02002424 NULL, UINT64_MAX);
Avi Kivitye9179ce2009-06-14 11:38:52 +03002425}
2426
Alexey Kardashevskiy8629d3f2017-09-21 18:51:00 +10002427AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
Avi Kivityac1970f2012-10-03 16:22:53 +02002428{
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +02002429 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2430 uint16_t n;
2431
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002432 n = dummy_section(&d->map, fv, &io_mem_unassigned);
Marcel Apfelbaum53cb28c2013-12-01 14:02:23 +02002433 assert(n == PHYS_SECTION_UNASSIGNED);
Paolo Bonzini00752702013-05-29 12:13:54 +02002434
Michael S. Tsirkin9736e552013-11-11 14:42:43 +02002435 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
Alexey Kardashevskiy66a6df12017-09-21 18:50:56 +10002436
2437 return d;
Paolo Bonzini00752702013-05-29 12:13:54 +02002438}
2439
Alexey Kardashevskiy66a6df12017-09-21 18:50:56 +10002440void address_space_dispatch_free(AddressSpaceDispatch *d)
Paolo Bonzini79e2b9a2015-01-21 12:09:14 +01002441{
2442 phys_sections_free(&d->map);
2443 g_free(d);
2444}
2445
Paolo Bonzini9458a9a2018-02-06 18:37:39 +01002446static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2447{
2448}
2449
2450static void tcg_log_global_after_sync(MemoryListener *listener)
2451{
2452 CPUAddressSpace *cpuas;
2453
2454 /* Wait for the CPU to end the current TB. This avoids the following
2455 * incorrect race:
2456 *
2457 * vCPU migration
2458 * ---------------------- -------------------------
2459 * TLB check -> slow path
2460 * notdirty_mem_write
2461 * write to RAM
2462 * mark dirty
2463 * clear dirty flag
2464 * TLB check -> fast path
2465 * read memory
2466 * write to RAM
2467 *
2468 * by pushing the migration thread's memory read after the vCPU thread has
2469 * written the memory.
2470 */
Pavel Dovgalyuk86cf9e12019-09-17 12:54:06 +03002471 if (replay_mode == REPLAY_MODE_NONE) {
2472 /*
2473 * VGA can make calls to this function while updating the screen.
2474 * In record/replay mode this causes a deadlock, because
2475 * run_on_cpu waits for rr mutex. Therefore no races are possible
2476 * in this case and no need for making run_on_cpu when
Greg Kurzf18d4032021-10-15 11:29:44 +02002477 * record/replay is enabled.
Pavel Dovgalyuk86cf9e12019-09-17 12:54:06 +03002478 */
2479 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2480 run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2481 }
Paolo Bonzini9458a9a2018-02-06 18:37:39 +01002482}
2483
Avi Kivity1d711482012-10-02 18:54:45 +02002484static void tcg_commit(MemoryListener *listener)
Avi Kivity50c1e142012-02-08 21:36:02 +02002485{
Peter Maydell32857f42015-10-01 15:29:50 +01002486 CPUAddressSpace *cpuas;
2487 AddressSpaceDispatch *d;
Avi Kivity117712c2012-02-12 21:23:17 +02002488
Emilio G. Cotaf28d0df2018-06-22 13:45:31 -04002489 assert(tcg_enabled());
Avi Kivity117712c2012-02-12 21:23:17 +02002490 /* since each CPU stores ram addresses in its TLB cache, we must
2491 reset the modified entries */
Peter Maydell32857f42015-10-01 15:29:50 +01002492 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2493 cpu_reloading_memory_map();
2494 /* The CPU and TLB are protected by the iothread lock.
2495 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2496 * may have split the RCU critical section.
2497 */
Alexey Kardashevskiy66a6df12017-09-21 18:50:56 +10002498 d = address_space_to_dispatch(cpuas->as);
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01002499 qatomic_rcu_set(&cpuas->memory_dispatch, d);
Alex Bennéed10eb082016-11-14 14:17:28 +00002500 tlb_flush(cpuas->cpu);
Avi Kivity50c1e142012-02-08 21:36:02 +02002501}
2502
Avi Kivity62152b82011-07-26 14:26:14 +03002503static void memory_map_init(void)
2504{
Anthony Liguori7267c092011-08-20 22:09:37 -05002505 system_memory = g_malloc(sizeof(*system_memory));
Paolo Bonzini03f49952013-11-07 17:14:36 +01002506
Paolo Bonzini57271d62013-11-07 17:14:37 +01002507 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
Alexey Kardashevskiy7dca8042013-04-29 16:25:51 +00002508 address_space_init(&address_space_memory, system_memory, "memory");
Avi Kivity309cb472011-08-08 16:09:03 +03002509
Anthony Liguori7267c092011-08-20 22:09:37 -05002510 system_io = g_malloc(sizeof(*system_io));
Jan Kiszka3bb28b72013-09-02 18:43:30 +02002511 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2512 65536);
Alexey Kardashevskiy7dca8042013-04-29 16:25:51 +00002513 address_space_init(&address_space_io, system_io, "I/O");
Avi Kivity62152b82011-07-26 14:26:14 +03002514}
2515
2516MemoryRegion *get_system_memory(void)
2517{
2518 return system_memory;
2519}
2520
Avi Kivity309cb472011-08-08 16:09:03 +03002521MemoryRegion *get_system_io(void)
2522{
2523 return system_io;
2524}
2525
Paolo Bonzini845b6212015-03-23 11:45:53 +01002526static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
Avi Kivitya8170e52012-10-23 12:30:10 +02002527 hwaddr length)
Anthony PERARD51d7a9e2012-10-03 13:49:05 +00002528{
Paolo Bonzinie87f7772015-03-25 15:21:39 +01002529 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
Paolo Bonzini0878d0e2016-02-22 11:02:12 +01002530 addr += memory_region_get_ram_addr(mr);
2531
Paolo Bonzinie87f7772015-03-25 15:21:39 +01002532 /* No early return if dirty_log_mask is or becomes 0, because
2533 * cpu_physical_memory_set_dirty_range will still call
2534 * xen_modified_memory.
2535 */
2536 if (dirty_log_mask) {
2537 dirty_log_mask =
2538 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
Anthony PERARD51d7a9e2012-10-03 13:49:05 +00002539 }
Paolo Bonzinie87f7772015-03-25 15:21:39 +01002540 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
Paolo Bonzini5aa1ef72017-07-03 17:50:40 +02002541 assert(tcg_enabled());
Richard Hendersone506ad62023-03-06 04:30:11 +03002542 tb_invalidate_phys_range(addr, addr + length - 1);
Paolo Bonzinie87f7772015-03-25 15:21:39 +01002543 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2544 }
2545 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
Anthony PERARD51d7a9e2012-10-03 13:49:05 +00002546}
2547
Stefan Hajnoczi047be4e2019-01-29 11:46:04 +00002548void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
2549{
2550 /*
2551 * In principle this function would work on other memory region types too,
2552 * but the ROM device use case is the only one where this operation is
2553 * necessary. Other memory regions should use the
2554 * address_space_read/write() APIs.
2555 */
2556 assert(memory_region_is_romd(mr));
2557
2558 invalidate_and_set_dirty(mr, addr, size);
2559}
2560
Jagannathan Raman3123f932022-06-13 16:26:32 -04002561int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
Paolo Bonzini82f25632013-05-24 11:59:43 +02002562{
Paolo Bonzinie1622f42013-07-17 13:17:41 +02002563 unsigned access_size_max = mr->ops->valid.max_access_size;
Richard Henderson23326162013-07-08 14:55:59 -07002564
2565 /* Regions are assumed to support 1-4 byte accesses unless
2566 otherwise specified. */
Richard Henderson23326162013-07-08 14:55:59 -07002567 if (access_size_max == 0) {
2568 access_size_max = 4;
Paolo Bonzini82f25632013-05-24 11:59:43 +02002569 }
Richard Henderson23326162013-07-08 14:55:59 -07002570
2571 /* Bound the maximum access by the alignment of the address. */
2572 if (!mr->ops->impl.unaligned) {
2573 unsigned align_size_max = addr & -addr;
2574 if (align_size_max != 0 && align_size_max < access_size_max) {
2575 access_size_max = align_size_max;
2576 }
2577 }
2578
2579 /* Don't attempt accesses larger than the maximum. */
2580 if (l > access_size_max) {
2581 l = access_size_max;
2582 }
Peter Maydell6554f5c2015-07-24 13:33:10 +01002583 l = pow2floor(l);
Richard Henderson23326162013-07-08 14:55:59 -07002584
2585 return l;
Paolo Bonzini82f25632013-05-24 11:59:43 +02002586}
2587
Jagannathan Raman3123f932022-06-13 16:26:32 -04002588bool prepare_mmio_access(MemoryRegion *mr)
Paolo Bonzini125b3802015-06-18 18:47:21 +02002589{
Jan Kiszka4840f102015-06-18 18:47:22 +02002590 bool release_lock = false;
2591
Philippe Mathieu-Daudé37921852020-10-30 16:37:52 +01002592 if (!qemu_mutex_iothread_locked()) {
Jan Kiszka4840f102015-06-18 18:47:22 +02002593 qemu_mutex_lock_iothread();
Jan Kiszka4840f102015-06-18 18:47:22 +02002594 release_lock = true;
Paolo Bonzini125b3802015-06-18 18:47:21 +02002595 }
Jan Kiszka4840f102015-06-18 18:47:22 +02002596 if (mr->flush_coalesced_mmio) {
Jan Kiszka4840f102015-06-18 18:47:22 +02002597 qemu_flush_coalesced_mmio_buffer();
Jan Kiszka4840f102015-06-18 18:47:22 +02002598 }
2599
2600 return release_lock;
Paolo Bonzini125b3802015-06-18 18:47:21 +02002601}
2602
Philippe Mathieu-Daudé3ab6fdc2021-12-15 19:24:21 +01002603/**
2604 * flatview_access_allowed
2605 * @mr: #MemoryRegion to be accessed
2606 * @attrs: memory transaction attributes
2607 * @addr: address within that memory region
2608 * @len: the number of bytes to access
2609 *
2610 * Check if a memory transaction is allowed.
2611 *
2612 * Returns: true if transaction is allowed, false if denied.
2613 */
2614static bool flatview_access_allowed(MemoryRegion *mr, MemTxAttrs attrs,
2615 hwaddr addr, hwaddr len)
2616{
2617 if (likely(!attrs.memory)) {
2618 return true;
2619 }
2620 if (memory_region_is_ram(mr)) {
2621 return true;
2622 }
2623 qemu_log_mask(LOG_GUEST_ERROR,
2624 "Invalid access to non-RAM device at "
2625 "addr 0x%" HWADDR_PRIX ", size %" HWADDR_PRIu ", "
2626 "region '%s'\n", addr, len, memory_region_name(mr));
2627 return false;
2628}
2629
Paolo Bonzinia203ac72015-12-09 10:18:57 +01002630/* Called within RCU critical section. */
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002631static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
2632 MemTxAttrs attrs,
Philippe Mathieu-Daudéa152be42020-02-19 19:52:44 +01002633 const void *ptr,
Li Zhijian0c249ff2019-01-17 20:49:01 +08002634 hwaddr len, hwaddr addr1,
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002635 hwaddr l, MemoryRegion *mr)
bellard13eb76e2004-01-24 15:23:36 +00002636{
Philippe Mathieu-Daudé20804672020-02-19 18:01:32 +01002637 uint8_t *ram_ptr;
Paolo Bonzini791af8c2013-05-24 16:10:39 +02002638 uint64_t val;
Peter Maydell3b643492015-04-26 16:49:23 +01002639 MemTxResult result = MEMTX_OK;
Jan Kiszka4840f102015-06-18 18:47:22 +02002640 bool release_lock = false;
Philippe Mathieu-Daudéa152be42020-02-19 19:52:44 +01002641 const uint8_t *buf = ptr;
ths3b46e622007-09-17 08:09:54 +00002642
Paolo Bonzinia203ac72015-12-09 10:18:57 +01002643 for (;;) {
Philippe Mathieu-Daudé3ab6fdc2021-12-15 19:24:21 +01002644 if (!flatview_access_allowed(mr, attrs, addr1, l)) {
2645 result |= MEMTX_ACCESS_ERROR;
2646 /* Keep going. */
2647 } else if (!memory_access_is_direct(mr, true)) {
Paolo Bonzinieb7eeb82015-12-09 10:06:31 +01002648 release_lock |= prepare_mmio_access(mr);
2649 l = memory_access_size(mr, l, addr1);
2650 /* XXX: could force current_cpu to NULL to avoid
2651 potential bugs */
Tony Nguyen9bf825b2019-08-24 04:36:54 +10002652 val = ldn_he_p(buf, l);
Tony Nguyen3d9e7c32019-08-24 04:36:46 +10002653 result |= memory_region_dispatch_write(mr, addr1, val,
Tony Nguyen9bf825b2019-08-24 04:36:54 +10002654 size_memop(l), attrs);
bellard13eb76e2004-01-24 15:23:36 +00002655 } else {
Paolo Bonzinieb7eeb82015-12-09 10:06:31 +01002656 /* RAM case */
Philippe Mathieu-Daudé20804672020-02-19 18:01:32 +01002657 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
Akihiko Odaki4a73aee2023-01-31 12:01:55 +09002658 memmove(ram_ptr, buf, l);
Paolo Bonzinieb7eeb82015-12-09 10:06:31 +01002659 invalidate_and_set_dirty(mr, addr1, l);
bellard13eb76e2004-01-24 15:23:36 +00002660 }
Jan Kiszka4840f102015-06-18 18:47:22 +02002661
2662 if (release_lock) {
2663 qemu_mutex_unlock_iothread();
2664 release_lock = false;
2665 }
2666
bellard13eb76e2004-01-24 15:23:36 +00002667 len -= l;
2668 buf += l;
2669 addr += l;
Paolo Bonzinia203ac72015-12-09 10:18:57 +01002670
2671 if (!len) {
2672 break;
2673 }
2674
2675 l = len;
Peter Maydellefa99a22018-05-31 14:50:52 +01002676 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
bellard13eb76e2004-01-24 15:23:36 +00002677 }
Paolo Bonzinifd8aaa72013-05-21 09:56:55 +02002678
Peter Maydell3b643492015-04-26 16:49:23 +01002679 return result;
bellard13eb76e2004-01-24 15:23:36 +00002680}
bellard8df1cd02005-01-28 22:37:22 +00002681
Paolo Bonzini4c6ebbb2018-03-05 09:23:56 +01002682/* Called from RCU critical section. */
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002683static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
Philippe Mathieu-Daudéa152be42020-02-19 19:52:44 +01002684 const void *buf, hwaddr len)
Avi Kivityac1970f2012-10-03 16:22:53 +02002685{
Paolo Bonzinieb7eeb82015-12-09 10:06:31 +01002686 hwaddr l;
Paolo Bonzinieb7eeb82015-12-09 10:06:31 +01002687 hwaddr addr1;
2688 MemoryRegion *mr;
Paolo Bonzinia203ac72015-12-09 10:18:57 +01002689
Paolo Bonzini4c6ebbb2018-03-05 09:23:56 +01002690 l = len;
Peter Maydellefa99a22018-05-31 14:50:52 +01002691 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
Philippe Mathieu-Daudé3ab6fdc2021-12-15 19:24:21 +01002692 if (!flatview_access_allowed(mr, attrs, addr, len)) {
2693 return MEMTX_ACCESS_ERROR;
2694 }
Philippe Mathieu-Daudé58e74682021-12-15 19:24:20 +01002695 return flatview_write_continue(fv, addr, attrs, buf, len,
2696 addr1, l, mr);
Paolo Bonzinia203ac72015-12-09 10:18:57 +01002697}
2698
2699/* Called within RCU critical section. */
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002700MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
Philippe Mathieu-Daudéa152be42020-02-19 19:52:44 +01002701 MemTxAttrs attrs, void *ptr,
Li Zhijian0c249ff2019-01-17 20:49:01 +08002702 hwaddr len, hwaddr addr1, hwaddr l,
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10002703 MemoryRegion *mr)
Paolo Bonzinia203ac72015-12-09 10:18:57 +01002704{
Philippe Mathieu-Daudé20804672020-02-19 18:01:32 +01002705 uint8_t *ram_ptr;
Paolo Bonzinia203ac72015-12-09 10:18:57 +01002706 uint64_t val;
2707 MemTxResult result = MEMTX_OK;
Paolo Bonzinieb7eeb82015-12-09 10:06:31 +01002708 bool release_lock = false;
Philippe Mathieu-Daudéa152be42020-02-19 19:52:44 +01002709 uint8_t *buf = ptr;
Paolo Bonzinieb7eeb82015-12-09 10:06:31 +01002710
Alexander Bulekov7cac7fe2021-03-15 10:05:12 -04002711 fuzz_dma_read_cb(addr, len, mr);
Paolo Bonzinia203ac72015-12-09 10:18:57 +01002712 for (;;) {
Philippe Mathieu-Daudé3ab6fdc2021-12-15 19:24:21 +01002713 if (!flatview_access_allowed(mr, attrs, addr1, l)) {
2714 result |= MEMTX_ACCESS_ERROR;
2715 /* Keep going. */
2716 } else if (!memory_access_is_direct(mr, false)) {
Paolo Bonzinieb7eeb82015-12-09 10:06:31 +01002717 /* I/O case */
2718 release_lock |= prepare_mmio_access(mr);
2719 l = memory_access_size(mr, l, addr1);
Tony Nguyen3d9e7c32019-08-24 04:36:46 +10002720 result |= memory_region_dispatch_read(mr, addr1, &val,
Tony Nguyen9bf825b2019-08-24 04:36:54 +10002721 size_memop(l), attrs);
2722 stn_he_p(buf, l, val);
Paolo Bonzinieb7eeb82015-12-09 10:06:31 +01002723 } else {
2724 /* RAM case */
Philippe Mathieu-Daudé20804672020-02-19 18:01:32 +01002725 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2726 memcpy(buf, ram_ptr, l);
Paolo Bonzinieb7eeb82015-12-09 10:06:31 +01002727 }
2728
2729 if (release_lock) {
2730 qemu_mutex_unlock_iothread();
2731 release_lock = false;
2732 }
2733
2734 len -= l;
2735 buf += l;
2736 addr += l;
Paolo Bonzinia203ac72015-12-09 10:18:57 +01002737
2738 if (!len) {
2739 break;
2740 }
2741
2742 l = len;
Peter Maydellefa99a22018-05-31 14:50:52 +01002743 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
Paolo Bonzinieb7eeb82015-12-09 10:06:31 +01002744 }
Paolo Bonzinia203ac72015-12-09 10:18:57 +01002745
2746 return result;
2747}
2748
Paolo Bonzinib2a44fc2018-03-05 00:19:49 +01002749/* Called from RCU critical section. */
2750static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
Philippe Mathieu-Daudéa152be42020-02-19 19:52:44 +01002751 MemTxAttrs attrs, void *buf, hwaddr len)
Paolo Bonzinia203ac72015-12-09 10:18:57 +01002752{
2753 hwaddr l;
2754 hwaddr addr1;
2755 MemoryRegion *mr;
Paolo Bonzinia203ac72015-12-09 10:18:57 +01002756
Paolo Bonzinib2a44fc2018-03-05 00:19:49 +01002757 l = len;
Peter Maydellefa99a22018-05-31 14:50:52 +01002758 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
Philippe Mathieu-Daudé3ab6fdc2021-12-15 19:24:21 +01002759 if (!flatview_access_allowed(mr, attrs, addr, len)) {
2760 return MEMTX_ACCESS_ERROR;
2761 }
Paolo Bonzinib2a44fc2018-03-05 00:19:49 +01002762 return flatview_read_continue(fv, addr, attrs, buf, len,
2763 addr1, l, mr);
Avi Kivityac1970f2012-10-03 16:22:53 +02002764}
2765
Paolo Bonzinib2a44fc2018-03-05 00:19:49 +01002766MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
Philippe Mathieu-Daudédaa3dda2020-02-19 19:54:35 +01002767 MemTxAttrs attrs, void *buf, hwaddr len)
Paolo Bonzinib2a44fc2018-03-05 00:19:49 +01002768{
2769 MemTxResult result = MEMTX_OK;
2770 FlatView *fv;
2771
2772 if (len > 0) {
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +01002773 RCU_READ_LOCK_GUARD();
Paolo Bonzinib2a44fc2018-03-05 00:19:49 +01002774 fv = address_space_to_flatview(as);
2775 result = flatview_read(fv, addr, attrs, buf, len);
Paolo Bonzinib2a44fc2018-03-05 00:19:49 +01002776 }
2777
2778 return result;
2779}
2780
Paolo Bonzini4c6ebbb2018-03-05 09:23:56 +01002781MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2782 MemTxAttrs attrs,
Philippe Mathieu-Daudédaa3dda2020-02-19 19:54:35 +01002783 const void *buf, hwaddr len)
Paolo Bonzini4c6ebbb2018-03-05 09:23:56 +01002784{
2785 MemTxResult result = MEMTX_OK;
2786 FlatView *fv;
2787
2788 if (len > 0) {
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +01002789 RCU_READ_LOCK_GUARD();
Paolo Bonzini4c6ebbb2018-03-05 09:23:56 +01002790 fv = address_space_to_flatview(as);
2791 result = flatview_write(fv, addr, attrs, buf, len);
Paolo Bonzini4c6ebbb2018-03-05 09:23:56 +01002792 }
2793
2794 return result;
2795}
2796
Paolo Bonzinidb84fd92018-03-05 09:29:04 +01002797MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
Philippe Mathieu-Daudédaa3dda2020-02-19 19:54:35 +01002798 void *buf, hwaddr len, bool is_write)
Paolo Bonzinidb84fd92018-03-05 09:29:04 +01002799{
2800 if (is_write) {
2801 return address_space_write(as, addr, attrs, buf, len);
2802 } else {
2803 return address_space_read_full(as, addr, attrs, buf, len);
2804 }
2805}
2806
Philippe Mathieu-Daudé75f01c62022-01-15 21:37:23 +01002807MemTxResult address_space_set(AddressSpace *as, hwaddr addr,
2808 uint8_t c, hwaddr len, MemTxAttrs attrs)
2809{
2810#define FILLBUF_SIZE 512
2811 uint8_t fillbuf[FILLBUF_SIZE];
2812 int l;
2813 MemTxResult error = MEMTX_OK;
2814
2815 memset(fillbuf, c, FILLBUF_SIZE);
2816 while (len > 0) {
2817 l = len < FILLBUF_SIZE ? len : FILLBUF_SIZE;
2818 error |= address_space_write(as, addr, attrs, fillbuf, l);
2819 len -= l;
2820 addr += l;
2821 }
2822
2823 return error;
2824}
2825
Philippe Mathieu-Daudéd7ef71e2020-02-19 20:02:11 +01002826void cpu_physical_memory_rw(hwaddr addr, void *buf,
Philippe Mathieu-Daudé28c80bf2020-02-19 20:32:30 +01002827 hwaddr len, bool is_write)
Avi Kivityac1970f2012-10-03 16:22:53 +02002828{
Peter Maydell5c9eb022015-04-26 16:49:24 +01002829 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
2830 buf, len, is_write);
Avi Kivityac1970f2012-10-03 16:22:53 +02002831}
2832
Alexander Graf582b55a2013-12-11 14:17:44 +01002833enum write_rom_type {
2834 WRITE_DATA,
2835 FLUSH_CACHE,
2836};
2837
Peter Maydell75693e12018-12-14 13:30:48 +00002838static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
2839 hwaddr addr,
2840 MemTxAttrs attrs,
Philippe Mathieu-Daudédaa3dda2020-02-19 19:54:35 +01002841 const void *ptr,
Li Zhijian0c249ff2019-01-17 20:49:01 +08002842 hwaddr len,
Peter Maydell75693e12018-12-14 13:30:48 +00002843 enum write_rom_type type)
bellardd0ecd2a2006-04-23 17:14:48 +00002844{
Paolo Bonzini149f54b2013-05-24 12:59:37 +02002845 hwaddr l;
Philippe Mathieu-Daudé20804672020-02-19 18:01:32 +01002846 uint8_t *ram_ptr;
Paolo Bonzini149f54b2013-05-24 12:59:37 +02002847 hwaddr addr1;
Paolo Bonzini5c8a00c2013-05-29 12:42:00 +02002848 MemoryRegion *mr;
Philippe Mathieu-Daudédaa3dda2020-02-19 19:54:35 +01002849 const uint8_t *buf = ptr;
ths3b46e622007-09-17 08:09:54 +00002850
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +01002851 RCU_READ_LOCK_GUARD();
bellardd0ecd2a2006-04-23 17:14:48 +00002852 while (len > 0) {
Paolo Bonzini149f54b2013-05-24 12:59:37 +02002853 l = len;
Peter Maydell75693e12018-12-14 13:30:48 +00002854 mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
ths3b46e622007-09-17 08:09:54 +00002855
Paolo Bonzini5c8a00c2013-05-29 12:42:00 +02002856 if (!(memory_region_is_ram(mr) ||
2857 memory_region_is_romd(mr))) {
Paolo Bonzinib242e0e2015-07-04 00:24:51 +02002858 l = memory_access_size(mr, l, addr1);
bellardd0ecd2a2006-04-23 17:14:48 +00002859 } else {
bellardd0ecd2a2006-04-23 17:14:48 +00002860 /* ROM/RAM case */
Philippe Mathieu-Daudé20804672020-02-19 18:01:32 +01002861 ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
Alexander Graf582b55a2013-12-11 14:17:44 +01002862 switch (type) {
2863 case WRITE_DATA:
Philippe Mathieu-Daudé20804672020-02-19 18:01:32 +01002864 memcpy(ram_ptr, buf, l);
Paolo Bonzini845b6212015-03-23 11:45:53 +01002865 invalidate_and_set_dirty(mr, addr1, l);
Alexander Graf582b55a2013-12-11 14:17:44 +01002866 break;
2867 case FLUSH_CACHE:
Richard Henderson1da8de32020-12-12 10:38:21 -06002868 flush_idcache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr, l);
Alexander Graf582b55a2013-12-11 14:17:44 +01002869 break;
2870 }
bellardd0ecd2a2006-04-23 17:14:48 +00002871 }
2872 len -= l;
2873 buf += l;
2874 addr += l;
2875 }
Peter Maydell75693e12018-12-14 13:30:48 +00002876 return MEMTX_OK;
bellardd0ecd2a2006-04-23 17:14:48 +00002877}
2878
Alexander Graf582b55a2013-12-11 14:17:44 +01002879/* used for ROM loading : can write in RAM and ROM */
Peter Maydell3c8133f2018-12-14 13:30:48 +00002880MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
2881 MemTxAttrs attrs,
Philippe Mathieu-Daudédaa3dda2020-02-19 19:54:35 +01002882 const void *buf, hwaddr len)
Alexander Graf582b55a2013-12-11 14:17:44 +01002883{
Peter Maydell3c8133f2018-12-14 13:30:48 +00002884 return address_space_write_rom_internal(as, addr, attrs,
2885 buf, len, WRITE_DATA);
Alexander Graf582b55a2013-12-11 14:17:44 +01002886}
2887
Li Zhijian0c249ff2019-01-17 20:49:01 +08002888void cpu_flush_icache_range(hwaddr start, hwaddr len)
Alexander Graf582b55a2013-12-11 14:17:44 +01002889{
2890 /*
2891 * This function should do the same thing as an icache flush that was
2892 * triggered from within the guest. For TCG we are always cache coherent,
2893 * so there is no need to flush anything. For KVM / Xen we need to flush
2894 * the host's instruction cache at least.
2895 */
2896 if (tcg_enabled()) {
2897 return;
2898 }
2899
Peter Maydell75693e12018-12-14 13:30:48 +00002900 address_space_write_rom_internal(&address_space_memory,
2901 start, MEMTXATTRS_UNSPECIFIED,
2902 NULL, len, FLUSH_CACHE);
Alexander Graf582b55a2013-12-11 14:17:44 +01002903}
2904
aliguori6d16c2f2009-01-22 16:59:11 +00002905typedef struct {
Paolo Bonzinid3e71552013-06-28 17:33:29 +02002906 MemoryRegion *mr;
aliguori6d16c2f2009-01-22 16:59:11 +00002907 void *buffer;
Avi Kivitya8170e52012-10-23 12:30:10 +02002908 hwaddr addr;
2909 hwaddr len;
Fam Zhengc2cba0f2015-03-16 17:03:33 +08002910 bool in_use;
aliguori6d16c2f2009-01-22 16:59:11 +00002911} BounceBuffer;
2912
2913static BounceBuffer bounce;
2914
aliguoriba223c22009-01-22 16:59:16 +00002915typedef struct MapClient {
Fam Zhenge95205e2015-03-16 17:03:37 +08002916 QEMUBH *bh;
Blue Swirl72cf2d42009-09-12 07:36:22 +00002917 QLIST_ENTRY(MapClient) link;
aliguoriba223c22009-01-22 16:59:16 +00002918} MapClient;
2919
Fam Zheng38e047b2015-03-16 17:03:35 +08002920QemuMutex map_client_list_lock;
Paolo Bonzinib58deb32018-12-06 11:58:10 +01002921static QLIST_HEAD(, MapClient) map_client_list
Blue Swirl72cf2d42009-09-12 07:36:22 +00002922 = QLIST_HEAD_INITIALIZER(map_client_list);
aliguoriba223c22009-01-22 16:59:16 +00002923
Fam Zhenge95205e2015-03-16 17:03:37 +08002924static void cpu_unregister_map_client_do(MapClient *client)
aliguoriba223c22009-01-22 16:59:16 +00002925{
Blue Swirl72cf2d42009-09-12 07:36:22 +00002926 QLIST_REMOVE(client, link);
Anthony Liguori7267c092011-08-20 22:09:37 -05002927 g_free(client);
aliguoriba223c22009-01-22 16:59:16 +00002928}
2929
Fam Zheng33b6c2e2015-03-16 17:03:36 +08002930static void cpu_notify_map_clients_locked(void)
aliguoriba223c22009-01-22 16:59:16 +00002931{
2932 MapClient *client;
2933
Blue Swirl72cf2d42009-09-12 07:36:22 +00002934 while (!QLIST_EMPTY(&map_client_list)) {
2935 client = QLIST_FIRST(&map_client_list);
Fam Zhenge95205e2015-03-16 17:03:37 +08002936 qemu_bh_schedule(client->bh);
2937 cpu_unregister_map_client_do(client);
aliguoriba223c22009-01-22 16:59:16 +00002938 }
2939}
2940
Fam Zhenge95205e2015-03-16 17:03:37 +08002941void cpu_register_map_client(QEMUBH *bh)
bellardd0ecd2a2006-04-23 17:14:48 +00002942{
2943 MapClient *client = g_malloc(sizeof(*client));
2944
Fam Zheng38e047b2015-03-16 17:03:35 +08002945 qemu_mutex_lock(&map_client_list_lock);
Fam Zhenge95205e2015-03-16 17:03:37 +08002946 client->bh = bh;
bellardd0ecd2a2006-04-23 17:14:48 +00002947 QLIST_INSERT_HEAD(&map_client_list, client, link);
Paolo Bonzini33828ca2023-03-03 14:36:32 +01002948 /* Write map_client_list before reading in_use. */
2949 smp_mb();
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01002950 if (!qatomic_read(&bounce.in_use)) {
Fam Zheng33b6c2e2015-03-16 17:03:36 +08002951 cpu_notify_map_clients_locked();
2952 }
Fam Zheng38e047b2015-03-16 17:03:35 +08002953 qemu_mutex_unlock(&map_client_list_lock);
bellardd0ecd2a2006-04-23 17:14:48 +00002954}
2955
Fam Zheng38e047b2015-03-16 17:03:35 +08002956void cpu_exec_init_all(void)
2957{
2958 qemu_mutex_init(&ram_list.mutex);
Peter Maydell20bccb82016-10-24 16:26:49 +01002959 /* The data structures we set up here depend on knowing the page size,
2960 * so no more changes can be made after this point.
2961 * In an ideal world, nothing we did before we had finished the
2962 * machine setup would care about the target page size, and we could
2963 * do this much later, rather than requiring board models to state
2964 * up front what their requirements are.
2965 */
2966 finalize_target_page_bits();
Fam Zheng38e047b2015-03-16 17:03:35 +08002967 io_mem_init();
Paolo Bonzini680a4782015-11-02 09:23:52 +01002968 memory_map_init();
Fam Zheng38e047b2015-03-16 17:03:35 +08002969 qemu_mutex_init(&map_client_list_lock);
2970}
2971
Fam Zhenge95205e2015-03-16 17:03:37 +08002972void cpu_unregister_map_client(QEMUBH *bh)
bellardd0ecd2a2006-04-23 17:14:48 +00002973{
Fam Zhenge95205e2015-03-16 17:03:37 +08002974 MapClient *client;
bellardd0ecd2a2006-04-23 17:14:48 +00002975
Fam Zhenge95205e2015-03-16 17:03:37 +08002976 qemu_mutex_lock(&map_client_list_lock);
2977 QLIST_FOREACH(client, &map_client_list, link) {
2978 if (client->bh == bh) {
2979 cpu_unregister_map_client_do(client);
2980 break;
2981 }
2982 }
2983 qemu_mutex_unlock(&map_client_list_lock);
bellardd0ecd2a2006-04-23 17:14:48 +00002984}
2985
2986static void cpu_notify_map_clients(void)
2987{
Fam Zheng38e047b2015-03-16 17:03:35 +08002988 qemu_mutex_lock(&map_client_list_lock);
Fam Zheng33b6c2e2015-03-16 17:03:36 +08002989 cpu_notify_map_clients_locked();
Fam Zheng38e047b2015-03-16 17:03:35 +08002990 qemu_mutex_unlock(&map_client_list_lock);
aliguori6d16c2f2009-01-22 16:59:11 +00002991}
2992
Li Zhijian0c249ff2019-01-17 20:49:01 +08002993static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
Peter Maydelleace72b2018-05-31 14:50:52 +01002994 bool is_write, MemTxAttrs attrs)
Paolo Bonzini51644ab2013-04-11 15:40:59 +02002995{
Paolo Bonzini5c8a00c2013-05-29 12:42:00 +02002996 MemoryRegion *mr;
Paolo Bonzini51644ab2013-04-11 15:40:59 +02002997 hwaddr l, xlat;
2998
2999 while (len > 0) {
3000 l = len;
Peter Maydellefa99a22018-05-31 14:50:52 +01003001 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
Paolo Bonzini5c8a00c2013-05-29 12:42:00 +02003002 if (!memory_access_is_direct(mr, is_write)) {
3003 l = memory_access_size(mr, l, addr);
Peter Maydelleace72b2018-05-31 14:50:52 +01003004 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
Paolo Bonzini51644ab2013-04-11 15:40:59 +02003005 return false;
3006 }
3007 }
3008
3009 len -= l;
3010 addr += l;
3011 }
3012 return true;
3013}
3014
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10003015bool address_space_access_valid(AddressSpace *as, hwaddr addr,
Li Zhijian0c249ff2019-01-17 20:49:01 +08003016 hwaddr len, bool is_write,
Peter Maydellfddffa42018-05-31 14:50:52 +01003017 MemTxAttrs attrs)
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10003018{
Paolo Bonzini11e732a2018-03-05 00:23:26 +01003019 FlatView *fv;
Paolo Bonzini11e732a2018-03-05 00:23:26 +01003020
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +01003021 RCU_READ_LOCK_GUARD();
Paolo Bonzini11e732a2018-03-05 00:23:26 +01003022 fv = address_space_to_flatview(as);
Philippe Mathieu-Daudé58e74682021-12-15 19:24:20 +01003023 return flatview_access_valid(fv, addr, len, is_write, attrs);
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10003024}
3025
Paolo Bonzini715c31e2016-11-22 12:04:31 +01003026static hwaddr
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10003027flatview_extend_translation(FlatView *fv, hwaddr addr,
Peter Maydell53d07902018-05-31 14:50:52 +01003028 hwaddr target_len,
3029 MemoryRegion *mr, hwaddr base, hwaddr len,
3030 bool is_write, MemTxAttrs attrs)
Paolo Bonzini715c31e2016-11-22 12:04:31 +01003031{
3032 hwaddr done = 0;
3033 hwaddr xlat;
3034 MemoryRegion *this_mr;
3035
3036 for (;;) {
3037 target_len -= len;
3038 addr += len;
3039 done += len;
3040 if (target_len == 0) {
3041 return done;
3042 }
3043
3044 len = target_len;
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10003045 this_mr = flatview_translate(fv, addr, &xlat,
Peter Maydellefa99a22018-05-31 14:50:52 +01003046 &len, is_write, attrs);
Paolo Bonzini715c31e2016-11-22 12:04:31 +01003047 if (this_mr != mr || xlat != base + done) {
3048 return done;
3049 }
3050 }
3051}
3052
aliguori6d16c2f2009-01-22 16:59:11 +00003053/* Map a physical memory region into a host virtual address.
3054 * May map a subset of the requested range, given by and returned in *plen.
3055 * May return NULL if resources needed to perform the mapping are exhausted.
3056 * Use only for reads OR writes - not for read-modify-write operations.
aliguoriba223c22009-01-22 16:59:16 +00003057 * Use cpu_register_map_client() to know when retrying the map operation is
3058 * likely to succeed.
aliguori6d16c2f2009-01-22 16:59:11 +00003059 */
Avi Kivityac1970f2012-10-03 16:22:53 +02003060void *address_space_map(AddressSpace *as,
Avi Kivitya8170e52012-10-23 12:30:10 +02003061 hwaddr addr,
3062 hwaddr *plen,
Peter Maydellf26404f2018-05-31 14:50:52 +01003063 bool is_write,
3064 MemTxAttrs attrs)
aliguori6d16c2f2009-01-22 16:59:11 +00003065{
Avi Kivitya8170e52012-10-23 12:30:10 +02003066 hwaddr len = *plen;
Paolo Bonzini715c31e2016-11-22 12:04:31 +01003067 hwaddr l, xlat;
3068 MemoryRegion *mr;
Paolo Bonziniad0c60f2018-03-05 00:23:26 +01003069 FlatView *fv;
aliguori6d16c2f2009-01-22 16:59:11 +00003070
Paolo Bonzinie3127ae2013-06-28 17:29:27 +02003071 if (len == 0) {
3072 return NULL;
3073 }
aliguori6d16c2f2009-01-22 16:59:11 +00003074
Paolo Bonzinie3127ae2013-06-28 17:29:27 +02003075 l = len;
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +01003076 RCU_READ_LOCK_GUARD();
Paolo Bonziniad0c60f2018-03-05 00:23:26 +01003077 fv = address_space_to_flatview(as);
Peter Maydellefa99a22018-05-31 14:50:52 +01003078 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
Paolo Bonzini41063e12015-03-18 14:21:43 +01003079
Paolo Bonzinie3127ae2013-06-28 17:29:27 +02003080 if (!memory_access_is_direct(mr, is_write)) {
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01003081 if (qatomic_xchg(&bounce.in_use, true)) {
Prasad J Pandit77f55ea2020-05-26 16:47:43 +05303082 *plen = 0;
Paolo Bonzinie3127ae2013-06-28 17:29:27 +02003083 return NULL;
aliguori6d16c2f2009-01-22 16:59:11 +00003084 }
Kevin Wolfe85d9db2013-07-22 14:30:23 +02003085 /* Avoid unbounded allocations */
3086 l = MIN(l, TARGET_PAGE_SIZE);
3087 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
Paolo Bonzinie3127ae2013-06-28 17:29:27 +02003088 bounce.addr = addr;
3089 bounce.len = l;
Paolo Bonzinid3e71552013-06-28 17:33:29 +02003090
3091 memory_region_ref(mr);
3092 bounce.mr = mr;
Paolo Bonzinie3127ae2013-06-28 17:29:27 +02003093 if (!is_write) {
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10003094 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
Peter Maydell5c9eb022015-04-26 16:49:24 +01003095 bounce.buffer, l);
Stefano Stabellini8ab934f2011-06-27 18:26:06 +01003096 }
aliguori6d16c2f2009-01-22 16:59:11 +00003097
Paolo Bonzinie3127ae2013-06-28 17:29:27 +02003098 *plen = l;
3099 return bounce.buffer;
3100 }
3101
Paolo Bonzinie3127ae2013-06-28 17:29:27 +02003102
Paolo Bonzinid3e71552013-06-28 17:33:29 +02003103 memory_region_ref(mr);
Alexey Kardashevskiy16620682017-09-21 18:50:58 +10003104 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
Peter Maydell53d07902018-05-31 14:50:52 +01003105 l, is_write, attrs);
Alexander Bulekovfc1c8342021-01-20 01:02:55 -05003106 fuzz_dma_read_cb(addr, *plen, mr);
Markus Armbruster66997c42022-11-22 14:49:16 +01003107 return qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
aliguori6d16c2f2009-01-22 16:59:11 +00003108}
3109
Avi Kivityac1970f2012-10-03 16:22:53 +02003110/* Unmaps a memory region previously mapped by address_space_map().
Philippe Mathieu-Daudéae5883a2020-02-19 20:12:01 +01003111 * Will also mark the memory as dirty if is_write is true. access_len gives
aliguori6d16c2f2009-01-22 16:59:11 +00003112 * the amount of memory that was actually read or written by the caller.
3113 */
Avi Kivitya8170e52012-10-23 12:30:10 +02003114void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
Philippe Mathieu-Daudéae5883a2020-02-19 20:12:01 +01003115 bool is_write, hwaddr access_len)
aliguori6d16c2f2009-01-22 16:59:11 +00003116{
3117 if (buffer != bounce.buffer) {
Paolo Bonzinid3e71552013-06-28 17:33:29 +02003118 MemoryRegion *mr;
3119 ram_addr_t addr1;
3120
Paolo Bonzini07bdaa42016-03-25 12:55:08 +01003121 mr = memory_region_from_host(buffer, &addr1);
Paolo Bonzinid3e71552013-06-28 17:33:29 +02003122 assert(mr != NULL);
aliguori6d16c2f2009-01-22 16:59:11 +00003123 if (is_write) {
Paolo Bonzini845b6212015-03-23 11:45:53 +01003124 invalidate_and_set_dirty(mr, addr1, access_len);
aliguori6d16c2f2009-01-22 16:59:11 +00003125 }
Jan Kiszka868bb332011-06-21 22:59:09 +02003126 if (xen_enabled()) {
Jan Kiszkae41d7c62011-06-21 22:59:08 +02003127 xen_invalidate_map_cache_entry(buffer);
Anthony PERARD050a0dd2010-09-16 13:57:49 +01003128 }
Paolo Bonzinid3e71552013-06-28 17:33:29 +02003129 memory_region_unref(mr);
aliguori6d16c2f2009-01-22 16:59:11 +00003130 return;
3131 }
3132 if (is_write) {
Peter Maydell5c9eb022015-04-26 16:49:24 +01003133 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3134 bounce.buffer, access_len);
aliguori6d16c2f2009-01-22 16:59:11 +00003135 }
Herve Poussineauf8a83242010-01-24 21:23:56 +00003136 qemu_vfree(bounce.buffer);
aliguori6d16c2f2009-01-22 16:59:11 +00003137 bounce.buffer = NULL;
Paolo Bonzinid3e71552013-06-28 17:33:29 +02003138 memory_region_unref(bounce.mr);
Paolo Bonzini33828ca2023-03-03 14:36:32 +01003139 /* Clear in_use before reading map_client_list. */
Paolo Bonzini06831002023-03-03 14:37:51 +01003140 qatomic_set_mb(&bounce.in_use, false);
aliguoriba223c22009-01-22 16:59:16 +00003141 cpu_notify_map_clients();
aliguori6d16c2f2009-01-22 16:59:11 +00003142}
bellardd0ecd2a2006-04-23 17:14:48 +00003143
Avi Kivitya8170e52012-10-23 12:30:10 +02003144void *cpu_physical_memory_map(hwaddr addr,
3145 hwaddr *plen,
Philippe Mathieu-Daudé28c80bf2020-02-19 20:32:30 +01003146 bool is_write)
Avi Kivityac1970f2012-10-03 16:22:53 +02003147{
Peter Maydellf26404f2018-05-31 14:50:52 +01003148 return address_space_map(&address_space_memory, addr, plen, is_write,
3149 MEMTXATTRS_UNSPECIFIED);
Avi Kivityac1970f2012-10-03 16:22:53 +02003150}
3151
Avi Kivitya8170e52012-10-23 12:30:10 +02003152void cpu_physical_memory_unmap(void *buffer, hwaddr len,
Philippe Mathieu-Daudé28c80bf2020-02-19 20:32:30 +01003153 bool is_write, hwaddr access_len)
Avi Kivityac1970f2012-10-03 16:22:53 +02003154{
3155 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3156}
3157
Paolo Bonzini0ce265f2016-11-22 11:34:02 +01003158#define ARG1_DECL AddressSpace *as
3159#define ARG1 as
3160#define SUFFIX
3161#define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
Paolo Bonzini0ce265f2016-11-22 11:34:02 +01003162#define RCU_READ_LOCK(...) rcu_read_lock()
3163#define RCU_READ_UNLOCK(...) rcu_read_unlock()
Paolo Bonzini139c1832020-02-04 12:41:01 +01003164#include "memory_ldst.c.inc"
Alexander Graf1e78bcc2011-07-06 09:09:23 +02003165
Paolo Bonzini1f4e4962016-11-22 12:04:52 +01003166int64_t address_space_cache_init(MemoryRegionCache *cache,
3167 AddressSpace *as,
3168 hwaddr addr,
3169 hwaddr len,
3170 bool is_write)
3171{
Paolo Bonzini48564042018-03-18 18:26:36 +01003172 AddressSpaceDispatch *d;
3173 hwaddr l;
3174 MemoryRegion *mr;
Paolo Bonzini4bfb0242020-12-01 09:29:56 -05003175 Int128 diff;
Paolo Bonzini48564042018-03-18 18:26:36 +01003176
3177 assert(len > 0);
3178
3179 l = len;
3180 cache->fv = address_space_get_flatview(as);
3181 d = flatview_to_dispatch(cache->fv);
3182 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3183
Paolo Bonzini4bfb0242020-12-01 09:29:56 -05003184 /*
3185 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3186 * Take that into account to compute how many bytes are there between
3187 * cache->xlat and the end of the section.
3188 */
3189 diff = int128_sub(cache->mrs.size,
Yeqi Fu48805df2023-03-15 11:26:49 +08003190 int128_make64(cache->xlat - cache->mrs.offset_within_region));
Paolo Bonzini4bfb0242020-12-01 09:29:56 -05003191 l = int128_get64(int128_min(diff, int128_make64(l)));
3192
Paolo Bonzini48564042018-03-18 18:26:36 +01003193 mr = cache->mrs.mr;
3194 memory_region_ref(mr);
3195 if (memory_access_is_direct(mr, is_write)) {
Peter Maydell53d07902018-05-31 14:50:52 +01003196 /* We don't care about the memory attributes here as we're only
3197 * doing this if we found actual RAM, which behaves the same
3198 * regardless of attributes; so UNSPECIFIED is fine.
3199 */
Paolo Bonzini48564042018-03-18 18:26:36 +01003200 l = flatview_extend_translation(cache->fv, addr, len, mr,
Peter Maydell53d07902018-05-31 14:50:52 +01003201 cache->xlat, l, is_write,
3202 MEMTXATTRS_UNSPECIFIED);
Paolo Bonzini48564042018-03-18 18:26:36 +01003203 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3204 } else {
3205 cache->ptr = NULL;
3206 }
3207
3208 cache->len = l;
3209 cache->is_write = is_write;
3210 return l;
Paolo Bonzini1f4e4962016-11-22 12:04:52 +01003211}
3212
3213void address_space_cache_invalidate(MemoryRegionCache *cache,
3214 hwaddr addr,
3215 hwaddr access_len)
3216{
Paolo Bonzini48564042018-03-18 18:26:36 +01003217 assert(cache->is_write);
3218 if (likely(cache->ptr)) {
3219 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3220 }
Paolo Bonzini1f4e4962016-11-22 12:04:52 +01003221}
3222
3223void address_space_cache_destroy(MemoryRegionCache *cache)
3224{
Paolo Bonzini48564042018-03-18 18:26:36 +01003225 if (!cache->mrs.mr) {
3226 return;
3227 }
3228
3229 if (xen_enabled()) {
3230 xen_invalidate_map_cache_entry(cache->ptr);
3231 }
3232 memory_region_unref(cache->mrs.mr);
3233 flatview_unref(cache->fv);
3234 cache->mrs.mr = NULL;
3235 cache->fv = NULL;
3236}
3237
3238/* Called from RCU critical section. This function has the same
3239 * semantics as address_space_translate, but it only works on a
3240 * predefined range of a MemoryRegion that was mapped with
3241 * address_space_cache_init.
3242 */
3243static inline MemoryRegion *address_space_translate_cached(
3244 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
Peter Maydellbc6b1ce2018-05-31 14:50:52 +01003245 hwaddr *plen, bool is_write, MemTxAttrs attrs)
Paolo Bonzini48564042018-03-18 18:26:36 +01003246{
3247 MemoryRegionSection section;
3248 MemoryRegion *mr;
3249 IOMMUMemoryRegion *iommu_mr;
3250 AddressSpace *target_as;
3251
3252 assert(!cache->ptr);
3253 *xlat = addr + cache->xlat;
3254
3255 mr = cache->mrs.mr;
3256 iommu_mr = memory_region_get_iommu(mr);
3257 if (!iommu_mr) {
3258 /* MMIO region. */
3259 return mr;
3260 }
3261
3262 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3263 NULL, is_write, true,
Peter Maydell2f7b0092018-05-31 14:50:53 +01003264 &target_as, attrs);
Paolo Bonzini48564042018-03-18 18:26:36 +01003265 return section.mr;
3266}
3267
3268/* Called from RCU critical section. address_space_read_cached uses this
3269 * out of line function when the target is an MMIO or IOMMU region.
3270 */
Philippe Mathieu-Daudé38df19f2020-05-18 17:53:02 +02003271MemTxResult
Paolo Bonzini48564042018-03-18 18:26:36 +01003272address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
Li Zhijian0c249ff2019-01-17 20:49:01 +08003273 void *buf, hwaddr len)
Paolo Bonzini48564042018-03-18 18:26:36 +01003274{
3275 hwaddr addr1, l;
3276 MemoryRegion *mr;
3277
3278 l = len;
Peter Maydellbc6b1ce2018-05-31 14:50:52 +01003279 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3280 MEMTXATTRS_UNSPECIFIED);
Philippe Mathieu-Daudé38df19f2020-05-18 17:53:02 +02003281 return flatview_read_continue(cache->fv,
3282 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3283 addr1, l, mr);
Paolo Bonzini48564042018-03-18 18:26:36 +01003284}
3285
3286/* Called from RCU critical section. address_space_write_cached uses this
3287 * out of line function when the target is an MMIO or IOMMU region.
3288 */
Philippe Mathieu-Daudé38df19f2020-05-18 17:53:02 +02003289MemTxResult
Paolo Bonzini48564042018-03-18 18:26:36 +01003290address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
Li Zhijian0c249ff2019-01-17 20:49:01 +08003291 const void *buf, hwaddr len)
Paolo Bonzini48564042018-03-18 18:26:36 +01003292{
3293 hwaddr addr1, l;
3294 MemoryRegion *mr;
3295
3296 l = len;
Peter Maydellbc6b1ce2018-05-31 14:50:52 +01003297 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3298 MEMTXATTRS_UNSPECIFIED);
Philippe Mathieu-Daudé38df19f2020-05-18 17:53:02 +02003299 return flatview_write_continue(cache->fv,
3300 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3301 addr1, l, mr);
Paolo Bonzini1f4e4962016-11-22 12:04:52 +01003302}
3303
3304#define ARG1_DECL MemoryRegionCache *cache
3305#define ARG1 cache
Paolo Bonzini48564042018-03-18 18:26:36 +01003306#define SUFFIX _cached_slow
3307#define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
Paolo Bonzini48564042018-03-18 18:26:36 +01003308#define RCU_READ_LOCK() ((void)0)
3309#define RCU_READ_UNLOCK() ((void)0)
Paolo Bonzini139c1832020-02-04 12:41:01 +01003310#include "memory_ldst.c.inc"
Paolo Bonzini1f4e4962016-11-22 12:04:52 +01003311
aliguori5e2972f2009-03-28 17:51:36 +00003312/* virtual memory access for debug (includes writing to ROM) */
Philippe Mathieu-Daudé73842ef2022-02-03 02:13:28 +01003313int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
3314 void *ptr, size_t len, bool is_write)
bellard13eb76e2004-01-24 15:23:36 +00003315{
Avi Kivitya8170e52012-10-23 12:30:10 +02003316 hwaddr phys_addr;
Philippe Mathieu-Daudé73842ef2022-02-03 02:13:28 +01003317 vaddr l, page;
Philippe Mathieu-Daudéd7ef71e2020-02-19 20:02:11 +01003318 uint8_t *buf = ptr;
bellard13eb76e2004-01-24 15:23:36 +00003319
Christian Borntraeger79ca7a12017-03-07 15:19:08 +01003320 cpu_synchronize_state(cpu);
bellard13eb76e2004-01-24 15:23:36 +00003321 while (len > 0) {
Peter Maydell5232e4c2016-01-21 14:15:06 +00003322 int asidx;
3323 MemTxAttrs attrs;
Philippe Mathieu-Daudéddfc8b92020-05-18 17:53:03 +02003324 MemTxResult res;
Peter Maydell5232e4c2016-01-21 14:15:06 +00003325
bellard13eb76e2004-01-24 15:23:36 +00003326 page = addr & TARGET_PAGE_MASK;
Peter Maydell5232e4c2016-01-21 14:15:06 +00003327 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3328 asidx = cpu_asidx_from_attrs(cpu, attrs);
bellard13eb76e2004-01-24 15:23:36 +00003329 /* if no physical page mapped, return an error */
3330 if (phys_addr == -1)
3331 return -1;
3332 l = (page + TARGET_PAGE_SIZE) - addr;
3333 if (l > len)
3334 l = len;
aliguori5e2972f2009-03-28 17:51:36 +00003335 phys_addr += (addr & ~TARGET_PAGE_MASK);
Edgar E. Iglesias2e388472013-12-13 16:31:02 +10003336 if (is_write) {
Philippe Mathieu-Daudéddfc8b92020-05-18 17:53:03 +02003337 res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3338 attrs, buf, l);
Edgar E. Iglesias2e388472013-12-13 16:31:02 +10003339 } else {
Philippe Mathieu-Daudéddfc8b92020-05-18 17:53:03 +02003340 res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3341 attrs, buf, l);
3342 }
3343 if (res != MEMTX_OK) {
3344 return -1;
Edgar E. Iglesias2e388472013-12-13 16:31:02 +10003345 }
bellard13eb76e2004-01-24 15:23:36 +00003346 len -= l;
3347 buf += l;
3348 addr += l;
3349 }
3350 return 0;
3351}
Dr. David Alan Gilbert038629a2015-11-05 18:10:29 +00003352
3353/*
3354 * Allows code that needs to deal with migration bitmaps etc to still be built
3355 * target independent.
3356 */
Juan Quintela20afaed2017-03-21 09:09:14 +01003357size_t qemu_target_page_size(void)
Dr. David Alan Gilbert038629a2015-11-05 18:10:29 +00003358{
Juan Quintela20afaed2017-03-21 09:09:14 +01003359 return TARGET_PAGE_SIZE;
Dr. David Alan Gilbert038629a2015-11-05 18:10:29 +00003360}
3361
Philippe Mathieu-Daudéb3b408f2023-05-24 11:37:35 +02003362int qemu_target_page_mask(void)
3363{
3364 return TARGET_PAGE_MASK;
3365}
3366
Juan Quintela46d702b2017-04-24 21:03:48 +02003367int qemu_target_page_bits(void)
3368{
3369 return TARGET_PAGE_BITS;
3370}
3371
3372int qemu_target_page_bits_min(void)
3373{
3374 return TARGET_PAGE_BITS_MIN;
3375}
bellard13eb76e2004-01-24 15:23:36 +00003376
Juan Quintela62c5e182023-05-11 16:12:04 +02003377/* Convert target pages to MiB (2**20). */
3378size_t qemu_target_pages_to_MiB(size_t pages)
3379{
3380 int page_bits = TARGET_PAGE_BITS;
3381
3382 /* So far, the largest (non-huge) page size is 64k, i.e. 16 bits. */
3383 g_assert(page_bits < 20);
3384
3385 return pages >> (20 - page_bits);
3386}
3387
Avi Kivitya8170e52012-10-23 12:30:10 +02003388bool cpu_physical_memory_is_io(hwaddr phys_addr)
Wen Congyang76f35532012-05-07 12:04:18 +08003389{
Paolo Bonzini5c8a00c2013-05-29 12:42:00 +02003390 MemoryRegion*mr;
Paolo Bonzini149f54b2013-05-24 12:59:37 +02003391 hwaddr l = 1;
Wen Congyang76f35532012-05-07 12:04:18 +08003392
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +01003393 RCU_READ_LOCK_GUARD();
Paolo Bonzini5c8a00c2013-05-29 12:42:00 +02003394 mr = address_space_translate(&address_space_memory,
Peter Maydellbc6b1ce2018-05-31 14:50:52 +01003395 phys_addr, &phys_addr, &l, false,
3396 MEMTXATTRS_UNSPECIFIED);
Wen Congyang76f35532012-05-07 12:04:18 +08003397
Markus Armbruster66997c42022-11-22 14:49:16 +01003398 return !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
Wen Congyang76f35532012-05-07 12:04:18 +08003399}
Michael R. Hinesbd2fa512013-06-25 21:35:34 -04003400
Dr. David Alan Gilberte3807052015-05-21 13:24:13 +01003401int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
Michael R. Hinesbd2fa512013-06-25 21:35:34 -04003402{
3403 RAMBlock *block;
Dr. David Alan Gilberte3807052015-05-21 13:24:13 +01003404 int ret = 0;
Michael R. Hinesbd2fa512013-06-25 21:35:34 -04003405
Dr. David Alan Gilbert694ea272019-10-07 15:36:41 +01003406 RCU_READ_LOCK_GUARD();
Peter Xu99e15582017-05-12 12:17:39 +08003407 RAMBLOCK_FOREACH(block) {
Yury Kotov754cb9c2019-02-15 20:45:44 +03003408 ret = func(block, opaque);
Dr. David Alan Gilberte3807052015-05-21 13:24:13 +01003409 if (ret) {
3410 break;
3411 }
Michael R. Hinesbd2fa512013-06-25 21:35:34 -04003412 }
Dr. David Alan Gilberte3807052015-05-21 13:24:13 +01003413 return ret;
Michael R. Hinesbd2fa512013-06-25 21:35:34 -04003414}
Dr. David Alan Gilbertd3a50382017-02-24 18:28:32 +00003415
3416/*
3417 * Unmap pages of memory from start to start+length such that
3418 * they a) read as 0, b) Trigger whatever fault mechanism
3419 * the OS provides for postcopy.
3420 * The pages must be unmapped by the end of the function.
3421 * Returns: 0 on success, none-0 on failure
3422 *
3423 */
3424int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3425{
3426 int ret = -1;
3427
3428 uint8_t *host_startaddr = rb->host + start;
3429
Marc-André Lureau619bd312020-01-03 11:39:58 +04003430 if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
Dr. David Alan Gilbertd3a50382017-02-24 18:28:32 +00003431 error_report("ram_block_discard_range: Unaligned start address: %p",
3432 host_startaddr);
3433 goto err;
3434 }
3435
David Hildenbranddcdc4602021-04-29 13:27:03 +02003436 if ((start + length) <= rb->max_length) {
Dr. David Alan Gilbertdb144f72018-03-12 17:20:56 +00003437 bool need_madvise, need_fallocate;
Marc-André Lureau619bd312020-01-03 11:39:58 +04003438 if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
Wei Yang72821d92019-07-12 11:27:04 +08003439 error_report("ram_block_discard_range: Unaligned length: %zx",
3440 length);
Dr. David Alan Gilbertd3a50382017-02-24 18:28:32 +00003441 goto err;
3442 }
3443
3444 errno = ENOTSUP; /* If we are missing MADVISE etc */
3445
Dr. David Alan Gilbertdb144f72018-03-12 17:20:56 +00003446 /* The logic here is messy;
3447 * madvise DONTNEED fails for hugepages
3448 * fallocate works on hugepages and shmem
David Hildenbrandcdfa56c2021-04-06 10:01:25 +02003449 * shared anonymous memory requires madvise REMOVE
Dr. David Alan Gilbertdb144f72018-03-12 17:20:56 +00003450 */
3451 need_madvise = (rb->page_size == qemu_host_page_size);
3452 need_fallocate = rb->fd != -1;
3453 if (need_fallocate) {
3454 /* For a file, this causes the area of the file to be zero'd
3455 * if read, and for hugetlbfs also causes it to be unmapped
3456 * so a userfault will trigger.
Dr. David Alan Gilberte2fa71f2017-02-24 18:28:33 +00003457 */
3458#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3459 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3460 start, length);
Dr. David Alan Gilbertdb144f72018-03-12 17:20:56 +00003461 if (ret) {
3462 ret = -errno;
3463 error_report("ram_block_discard_range: Failed to fallocate "
3464 "%s:%" PRIx64 " +%zx (%d)",
3465 rb->idstr, start, length, ret);
3466 goto err;
3467 }
3468#else
3469 ret = -ENOSYS;
3470 error_report("ram_block_discard_range: fallocate not available/file"
Dr. David Alan Gilbertd3a50382017-02-24 18:28:32 +00003471 "%s:%" PRIx64 " +%zx (%d)",
3472 rb->idstr, start, length, ret);
Dr. David Alan Gilbertdb144f72018-03-12 17:20:56 +00003473 goto err;
3474#endif
Dr. David Alan Gilbertd3a50382017-02-24 18:28:32 +00003475 }
Dr. David Alan Gilbertdb144f72018-03-12 17:20:56 +00003476 if (need_madvise) {
3477 /* For normal RAM this causes it to be unmapped,
3478 * for shared memory it causes the local mapping to disappear
3479 * and to fall back on the file contents (which we just
3480 * fallocate'd away).
3481 */
3482#if defined(CONFIG_MADVISE)
David Hildenbrandcdfa56c2021-04-06 10:01:25 +02003483 if (qemu_ram_is_shared(rb) && rb->fd < 0) {
3484 ret = madvise(host_startaddr, length, QEMU_MADV_REMOVE);
3485 } else {
3486 ret = madvise(host_startaddr, length, QEMU_MADV_DONTNEED);
3487 }
Dr. David Alan Gilbertdb144f72018-03-12 17:20:56 +00003488 if (ret) {
3489 ret = -errno;
3490 error_report("ram_block_discard_range: Failed to discard range "
3491 "%s:%" PRIx64 " +%zx (%d)",
3492 rb->idstr, start, length, ret);
3493 goto err;
3494 }
3495#else
3496 ret = -ENOSYS;
3497 error_report("ram_block_discard_range: MADVISE not available"
3498 "%s:%" PRIx64 " +%zx (%d)",
3499 rb->idstr, start, length, ret);
3500 goto err;
3501#endif
3502 }
3503 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3504 need_madvise, need_fallocate, ret);
Dr. David Alan Gilbertd3a50382017-02-24 18:28:32 +00003505 } else {
3506 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3507 "/%zx/" RAM_ADDR_FMT")",
David Hildenbranddcdc4602021-04-29 13:27:03 +02003508 rb->idstr, start, length, rb->max_length);
Dr. David Alan Gilbertd3a50382017-02-24 18:28:32 +00003509 }
3510
3511err:
3512 return ret;
3513}
3514
Junyan Hea4de8552018-07-18 15:48:00 +08003515bool ramblock_is_pmem(RAMBlock *rb)
3516{
3517 return rb->flags & RAM_PMEM;
3518}
3519
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003520static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003521{
3522 if (start == end - 1) {
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003523 qemu_printf("\t%3d ", start);
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003524 } else {
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003525 qemu_printf("\t%3d..%-3d ", start, end - 1);
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003526 }
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003527 qemu_printf(" skip=%d ", skip);
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003528 if (ptr == PHYS_MAP_NODE_NIL) {
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003529 qemu_printf(" ptr=NIL");
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003530 } else if (!skip) {
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003531 qemu_printf(" ptr=#%d", ptr);
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003532 } else {
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003533 qemu_printf(" ptr=[%d]", ptr);
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003534 }
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003535 qemu_printf("\n");
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003536}
3537
3538#define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3539 int128_sub((size), int128_one())) : 0)
3540
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003541void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003542{
3543 int i;
3544
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003545 qemu_printf(" Dispatch\n");
3546 qemu_printf(" Physical sections\n");
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003547
3548 for (i = 0; i < d->map.sections_nb; ++i) {
3549 MemoryRegionSection *s = d->map.sections + i;
3550 const char *names[] = { " [unassigned]", " [not dirty]",
3551 " [ROM]", " [watch]" };
3552
Philippe Mathieu-Daudé883f2c52023-01-10 22:29:47 +01003553 qemu_printf(" #%d @" HWADDR_FMT_plx ".." HWADDR_FMT_plx
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003554 " %s%s%s%s%s",
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003555 i,
3556 s->offset_within_address_space,
Zhenzhong Duanf9c307c2022-06-22 17:59:12 +08003557 s->offset_within_address_space + MR_SIZE(s->size),
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003558 s->mr->name ? s->mr->name : "(noname)",
3559 i < ARRAY_SIZE(names) ? names[i] : "",
3560 s->mr == root ? " [ROOT]" : "",
3561 s == d->mru_section ? " [MRU]" : "",
3562 s->mr->is_iommu ? " [iommu]" : "");
3563
3564 if (s->mr->alias) {
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003565 qemu_printf(" alias=%s", s->mr->alias->name ?
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003566 s->mr->alias->name : "noname");
3567 }
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003568 qemu_printf("\n");
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003569 }
3570
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003571 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003572 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3573 for (i = 0; i < d->map.nodes_nb; ++i) {
3574 int j, jprev;
3575 PhysPageEntry prev;
3576 Node *n = d->map.nodes + i;
3577
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003578 qemu_printf(" [%d]\n", i);
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003579
3580 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3581 PhysPageEntry *pe = *n + j;
3582
3583 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3584 continue;
3585 }
3586
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003587 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003588
3589 jprev = j;
3590 prev = *pe;
3591 }
3592
3593 if (jprev != ARRAY_SIZE(*n)) {
Markus Armbrusterb6b71cb2019-04-17 21:17:56 +02003594 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
Alexey Kardashevskiy5e8fd942017-09-21 18:51:06 +10003595 }
3596 }
3597}
3598
David Hildenbrand7e6d32e2021-04-13 11:55:29 +02003599/* Require any discards to work. */
David Hildenbrand98da4912021-04-13 11:55:28 +02003600static unsigned int ram_block_discard_required_cnt;
David Hildenbrand7e6d32e2021-04-13 11:55:29 +02003601/* Require only coordinated discards to work. */
3602static unsigned int ram_block_coordinated_discard_required_cnt;
3603/* Disable any discards. */
David Hildenbrand98da4912021-04-13 11:55:28 +02003604static unsigned int ram_block_discard_disabled_cnt;
David Hildenbrand7e6d32e2021-04-13 11:55:29 +02003605/* Disable only uncoordinated discards. */
3606static unsigned int ram_block_uncoordinated_discard_disabled_cnt;
David Hildenbrand98da4912021-04-13 11:55:28 +02003607static QemuMutex ram_block_discard_disable_mutex;
3608
3609static void ram_block_discard_disable_mutex_lock(void)
3610{
3611 static gsize initialized;
3612
3613 if (g_once_init_enter(&initialized)) {
3614 qemu_mutex_init(&ram_block_discard_disable_mutex);
3615 g_once_init_leave(&initialized, 1);
3616 }
3617 qemu_mutex_lock(&ram_block_discard_disable_mutex);
3618}
3619
3620static void ram_block_discard_disable_mutex_unlock(void)
3621{
3622 qemu_mutex_unlock(&ram_block_discard_disable_mutex);
3623}
David Hildenbrandd24f31d2020-06-26 09:22:29 +02003624
3625int ram_block_discard_disable(bool state)
3626{
David Hildenbrand98da4912021-04-13 11:55:28 +02003627 int ret = 0;
David Hildenbrandd24f31d2020-06-26 09:22:29 +02003628
David Hildenbrand98da4912021-04-13 11:55:28 +02003629 ram_block_discard_disable_mutex_lock();
David Hildenbrandd24f31d2020-06-26 09:22:29 +02003630 if (!state) {
David Hildenbrand98da4912021-04-13 11:55:28 +02003631 ram_block_discard_disabled_cnt--;
David Hildenbrand7e6d32e2021-04-13 11:55:29 +02003632 } else if (ram_block_discard_required_cnt ||
3633 ram_block_coordinated_discard_required_cnt) {
David Hildenbrand98da4912021-04-13 11:55:28 +02003634 ret = -EBUSY;
David Hildenbrand7e6d32e2021-04-13 11:55:29 +02003635 } else {
3636 ram_block_discard_disabled_cnt++;
3637 }
3638 ram_block_discard_disable_mutex_unlock();
3639 return ret;
3640}
3641
3642int ram_block_uncoordinated_discard_disable(bool state)
3643{
3644 int ret = 0;
3645
3646 ram_block_discard_disable_mutex_lock();
3647 if (!state) {
3648 ram_block_uncoordinated_discard_disabled_cnt--;
3649 } else if (ram_block_discard_required_cnt) {
3650 ret = -EBUSY;
3651 } else {
3652 ram_block_uncoordinated_discard_disabled_cnt++;
David Hildenbrandd24f31d2020-06-26 09:22:29 +02003653 }
David Hildenbrand98da4912021-04-13 11:55:28 +02003654 ram_block_discard_disable_mutex_unlock();
3655 return ret;
David Hildenbrandd24f31d2020-06-26 09:22:29 +02003656}
3657
3658int ram_block_discard_require(bool state)
3659{
David Hildenbrand98da4912021-04-13 11:55:28 +02003660 int ret = 0;
David Hildenbrandd24f31d2020-06-26 09:22:29 +02003661
David Hildenbrand98da4912021-04-13 11:55:28 +02003662 ram_block_discard_disable_mutex_lock();
David Hildenbrandd24f31d2020-06-26 09:22:29 +02003663 if (!state) {
David Hildenbrand98da4912021-04-13 11:55:28 +02003664 ram_block_discard_required_cnt--;
David Hildenbrand7e6d32e2021-04-13 11:55:29 +02003665 } else if (ram_block_discard_disabled_cnt ||
3666 ram_block_uncoordinated_discard_disabled_cnt) {
David Hildenbrand98da4912021-04-13 11:55:28 +02003667 ret = -EBUSY;
David Hildenbrand7e6d32e2021-04-13 11:55:29 +02003668 } else {
3669 ram_block_discard_required_cnt++;
3670 }
3671 ram_block_discard_disable_mutex_unlock();
3672 return ret;
3673}
3674
3675int ram_block_coordinated_discard_require(bool state)
3676{
3677 int ret = 0;
3678
3679 ram_block_discard_disable_mutex_lock();
3680 if (!state) {
3681 ram_block_coordinated_discard_required_cnt--;
3682 } else if (ram_block_discard_disabled_cnt) {
3683 ret = -EBUSY;
3684 } else {
3685 ram_block_coordinated_discard_required_cnt++;
David Hildenbrandd24f31d2020-06-26 09:22:29 +02003686 }
David Hildenbrand98da4912021-04-13 11:55:28 +02003687 ram_block_discard_disable_mutex_unlock();
3688 return ret;
David Hildenbrandd24f31d2020-06-26 09:22:29 +02003689}
3690
3691bool ram_block_discard_is_disabled(void)
3692{
David Hildenbrand7e6d32e2021-04-13 11:55:29 +02003693 return qatomic_read(&ram_block_discard_disabled_cnt) ||
3694 qatomic_read(&ram_block_uncoordinated_discard_disabled_cnt);
David Hildenbrandd24f31d2020-06-26 09:22:29 +02003695}
3696
3697bool ram_block_discard_is_required(void)
3698{
David Hildenbrand7e6d32e2021-04-13 11:55:29 +02003699 return qatomic_read(&ram_block_discard_required_cnt) ||
3700 qatomic_read(&ram_block_coordinated_discard_required_cnt);
David Hildenbrandd24f31d2020-06-26 09:22:29 +02003701}