Merge remote-tracking branch 'remotes/mst/tags/for_upstream' into staging
[qemu.git] / softmmu / physmem.c
1 /*
2 * RAM allocation and memory access
3 *
4 * Copyright (c) 2003 Fabrice Bellard
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "qemu/osdep.h"
21 #include "qemu-common.h"
22 #include "qapi/error.h"
23
24 #include "qemu/cutils.h"
25 #include "qemu/cacheflush.h"
26
27 #ifdef CONFIG_TCG
28 #include "hw/core/tcg-cpu-ops.h"
29 #endif /* CONFIG_TCG */
30
31 #include "exec/exec-all.h"
32 #include "exec/target_page.h"
33 #include "hw/qdev-core.h"
34 #include "hw/qdev-properties.h"
35 #include "hw/boards.h"
36 #include "hw/xen/xen.h"
37 #include "sysemu/kvm.h"
38 #include "sysemu/tcg.h"
39 #include "sysemu/qtest.h"
40 #include "qemu/timer.h"
41 #include "qemu/config-file.h"
42 #include "qemu/error-report.h"
43 #include "qemu/qemu-print.h"
44 #include "exec/memory.h"
45 #include "exec/ioport.h"
46 #include "sysemu/dma.h"
47 #include "sysemu/hostmem.h"
48 #include "sysemu/hw_accel.h"
49 #include "sysemu/xen-mapcache.h"
50 #include "trace/trace-root.h"
51
52 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
53 #include <linux/falloc.h>
54 #endif
55
56 #include "qemu/rcu_queue.h"
57 #include "qemu/main-loop.h"
58 #include "exec/translate-all.h"
59 #include "sysemu/replay.h"
60
61 #include "exec/memory-internal.h"
62 #include "exec/ram_addr.h"
63 #include "exec/log.h"
64
65 #include "qemu/pmem.h"
66
67 #include "migration/vmstate.h"
68
69 #include "qemu/range.h"
70 #ifndef _WIN32
71 #include "qemu/mmap-alloc.h"
72 #endif
73
74 #include "monitor/monitor.h"
75
76 #ifdef CONFIG_LIBDAXCTL
77 #include <daxctl/libdaxctl.h>
78 #endif
79
80 //#define DEBUG_SUBPAGE
81
82 /* ram_list is read under rcu_read_lock()/rcu_read_unlock(). Writes
83 * are protected by the ramlist lock.
84 */
85 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
86
87 static MemoryRegion *system_memory;
88 static MemoryRegion *system_io;
89
90 AddressSpace address_space_io;
91 AddressSpace address_space_memory;
92
93 static MemoryRegion io_mem_unassigned;
94
95 typedef struct PhysPageEntry PhysPageEntry;
96
97 struct PhysPageEntry {
98 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
99 uint32_t skip : 6;
100 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
101 uint32_t ptr : 26;
102 };
103
104 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
105
106 /* Size of the L2 (and L3, etc) page tables. */
107 #define ADDR_SPACE_BITS 64
108
109 #define P_L2_BITS 9
110 #define P_L2_SIZE (1 << P_L2_BITS)
111
112 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
113
114 typedef PhysPageEntry Node[P_L2_SIZE];
115
116 typedef struct PhysPageMap {
117 struct rcu_head rcu;
118
119 unsigned sections_nb;
120 unsigned sections_nb_alloc;
121 unsigned nodes_nb;
122 unsigned nodes_nb_alloc;
123 Node *nodes;
124 MemoryRegionSection *sections;
125 } PhysPageMap;
126
127 struct AddressSpaceDispatch {
128 MemoryRegionSection *mru_section;
129 /* This is a multi-level map on the physical address space.
130 * The bottom level has pointers to MemoryRegionSections.
131 */
132 PhysPageEntry phys_map;
133 PhysPageMap map;
134 };
135
136 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
137 typedef struct subpage_t {
138 MemoryRegion iomem;
139 FlatView *fv;
140 hwaddr base;
141 uint16_t sub_section[];
142 } subpage_t;
143
144 #define PHYS_SECTION_UNASSIGNED 0
145
146 static void io_mem_init(void);
147 static void memory_map_init(void);
148 static void tcg_log_global_after_sync(MemoryListener *listener);
149 static void tcg_commit(MemoryListener *listener);
150
151 /**
152 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
153 * @cpu: the CPU whose AddressSpace this is
154 * @as: the AddressSpace itself
155 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
156 * @tcg_as_listener: listener for tracking changes to the AddressSpace
157 */
158 struct CPUAddressSpace {
159 CPUState *cpu;
160 AddressSpace *as;
161 struct AddressSpaceDispatch *memory_dispatch;
162 MemoryListener tcg_as_listener;
163 };
164
165 struct DirtyBitmapSnapshot {
166 ram_addr_t start;
167 ram_addr_t end;
168 unsigned long dirty[];
169 };
170
171 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
172 {
173 static unsigned alloc_hint = 16;
174 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
175 map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
176 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
177 alloc_hint = map->nodes_nb_alloc;
178 }
179 }
180
181 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
182 {
183 unsigned i;
184 uint32_t ret;
185 PhysPageEntry e;
186 PhysPageEntry *p;
187
188 ret = map->nodes_nb++;
189 p = map->nodes[ret];
190 assert(ret != PHYS_MAP_NODE_NIL);
191 assert(ret != map->nodes_nb_alloc);
192
193 e.skip = leaf ? 0 : 1;
194 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
195 for (i = 0; i < P_L2_SIZE; ++i) {
196 memcpy(&p[i], &e, sizeof(e));
197 }
198 return ret;
199 }
200
201 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
202 hwaddr *index, uint64_t *nb, uint16_t leaf,
203 int level)
204 {
205 PhysPageEntry *p;
206 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
207
208 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
209 lp->ptr = phys_map_node_alloc(map, level == 0);
210 }
211 p = map->nodes[lp->ptr];
212 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
213
214 while (*nb && lp < &p[P_L2_SIZE]) {
215 if ((*index & (step - 1)) == 0 && *nb >= step) {
216 lp->skip = 0;
217 lp->ptr = leaf;
218 *index += step;
219 *nb -= step;
220 } else {
221 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
222 }
223 ++lp;
224 }
225 }
226
227 static void phys_page_set(AddressSpaceDispatch *d,
228 hwaddr index, uint64_t nb,
229 uint16_t leaf)
230 {
231 /* Wildly overreserve - it doesn't matter much. */
232 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
233
234 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
235 }
236
237 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
238 * and update our entry so we can skip it and go directly to the destination.
239 */
240 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
241 {
242 unsigned valid_ptr = P_L2_SIZE;
243 int valid = 0;
244 PhysPageEntry *p;
245 int i;
246
247 if (lp->ptr == PHYS_MAP_NODE_NIL) {
248 return;
249 }
250
251 p = nodes[lp->ptr];
252 for (i = 0; i < P_L2_SIZE; i++) {
253 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
254 continue;
255 }
256
257 valid_ptr = i;
258 valid++;
259 if (p[i].skip) {
260 phys_page_compact(&p[i], nodes);
261 }
262 }
263
264 /* We can only compress if there's only one child. */
265 if (valid != 1) {
266 return;
267 }
268
269 assert(valid_ptr < P_L2_SIZE);
270
271 /* Don't compress if it won't fit in the # of bits we have. */
272 if (P_L2_LEVELS >= (1 << 6) &&
273 lp->skip + p[valid_ptr].skip >= (1 << 6)) {
274 return;
275 }
276
277 lp->ptr = p[valid_ptr].ptr;
278 if (!p[valid_ptr].skip) {
279 /* If our only child is a leaf, make this a leaf. */
280 /* By design, we should have made this node a leaf to begin with so we
281 * should never reach here.
282 * But since it's so simple to handle this, let's do it just in case we
283 * change this rule.
284 */
285 lp->skip = 0;
286 } else {
287 lp->skip += p[valid_ptr].skip;
288 }
289 }
290
291 void address_space_dispatch_compact(AddressSpaceDispatch *d)
292 {
293 if (d->phys_map.skip) {
294 phys_page_compact(&d->phys_map, d->map.nodes);
295 }
296 }
297
298 static inline bool section_covers_addr(const MemoryRegionSection *section,
299 hwaddr addr)
300 {
301 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
302 * the section must cover the entire address space.
303 */
304 return int128_gethi(section->size) ||
305 range_covers_byte(section->offset_within_address_space,
306 int128_getlo(section->size), addr);
307 }
308
309 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
310 {
311 PhysPageEntry lp = d->phys_map, *p;
312 Node *nodes = d->map.nodes;
313 MemoryRegionSection *sections = d->map.sections;
314 hwaddr index = addr >> TARGET_PAGE_BITS;
315 int i;
316
317 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
318 if (lp.ptr == PHYS_MAP_NODE_NIL) {
319 return &sections[PHYS_SECTION_UNASSIGNED];
320 }
321 p = nodes[lp.ptr];
322 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
323 }
324
325 if (section_covers_addr(&sections[lp.ptr], addr)) {
326 return &sections[lp.ptr];
327 } else {
328 return &sections[PHYS_SECTION_UNASSIGNED];
329 }
330 }
331
332 /* Called from RCU critical section */
333 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
334 hwaddr addr,
335 bool resolve_subpage)
336 {
337 MemoryRegionSection *section = qatomic_read(&d->mru_section);
338 subpage_t *subpage;
339
340 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
341 !section_covers_addr(section, addr)) {
342 section = phys_page_find(d, addr);
343 qatomic_set(&d->mru_section, section);
344 }
345 if (resolve_subpage && section->mr->subpage) {
346 subpage = container_of(section->mr, subpage_t, iomem);
347 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
348 }
349 return section;
350 }
351
352 /* Called from RCU critical section */
353 static MemoryRegionSection *
354 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
355 hwaddr *plen, bool resolve_subpage)
356 {
357 MemoryRegionSection *section;
358 MemoryRegion *mr;
359 Int128 diff;
360
361 section = address_space_lookup_region(d, addr, resolve_subpage);
362 /* Compute offset within MemoryRegionSection */
363 addr -= section->offset_within_address_space;
364
365 /* Compute offset within MemoryRegion */
366 *xlat = addr + section->offset_within_region;
367
368 mr = section->mr;
369
370 /* MMIO registers can be expected to perform full-width accesses based only
371 * on their address, without considering adjacent registers that could
372 * decode to completely different MemoryRegions. When such registers
373 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
374 * regions overlap wildly. For this reason we cannot clamp the accesses
375 * here.
376 *
377 * If the length is small (as is the case for address_space_ldl/stl),
378 * everything works fine. If the incoming length is large, however,
379 * the caller really has to do the clamping through memory_access_size.
380 */
381 if (memory_region_is_ram(mr)) {
382 diff = int128_sub(section->size, int128_make64(addr));
383 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
384 }
385 return section;
386 }
387
388 /**
389 * address_space_translate_iommu - translate an address through an IOMMU
390 * memory region and then through the target address space.
391 *
392 * @iommu_mr: the IOMMU memory region that we start the translation from
393 * @addr: the address to be translated through the MMU
394 * @xlat: the translated address offset within the destination memory region.
395 * It cannot be %NULL.
396 * @plen_out: valid read/write length of the translated address. It
397 * cannot be %NULL.
398 * @page_mask_out: page mask for the translated address. This
399 * should only be meaningful for IOMMU translated
400 * addresses, since there may be huge pages that this bit
401 * would tell. It can be %NULL if we don't care about it.
402 * @is_write: whether the translation operation is for write
403 * @is_mmio: whether this can be MMIO, set true if it can
404 * @target_as: the address space targeted by the IOMMU
405 * @attrs: transaction attributes
406 *
407 * This function is called from RCU critical section. It is the common
408 * part of flatview_do_translate and address_space_translate_cached.
409 */
410 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
411 hwaddr *xlat,
412 hwaddr *plen_out,
413 hwaddr *page_mask_out,
414 bool is_write,
415 bool is_mmio,
416 AddressSpace **target_as,
417 MemTxAttrs attrs)
418 {
419 MemoryRegionSection *section;
420 hwaddr page_mask = (hwaddr)-1;
421
422 do {
423 hwaddr addr = *xlat;
424 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
425 int iommu_idx = 0;
426 IOMMUTLBEntry iotlb;
427
428 if (imrc->attrs_to_index) {
429 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
430 }
431
432 iotlb = imrc->translate(iommu_mr, addr, is_write ?
433 IOMMU_WO : IOMMU_RO, iommu_idx);
434
435 if (!(iotlb.perm & (1 << is_write))) {
436 goto unassigned;
437 }
438
439 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
440 | (addr & iotlb.addr_mask));
441 page_mask &= iotlb.addr_mask;
442 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
443 *target_as = iotlb.target_as;
444
445 section = address_space_translate_internal(
446 address_space_to_dispatch(iotlb.target_as), addr, xlat,
447 plen_out, is_mmio);
448
449 iommu_mr = memory_region_get_iommu(section->mr);
450 } while (unlikely(iommu_mr));
451
452 if (page_mask_out) {
453 *page_mask_out = page_mask;
454 }
455 return *section;
456
457 unassigned:
458 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
459 }
460
461 /**
462 * flatview_do_translate - translate an address in FlatView
463 *
464 * @fv: the flat view that we want to translate on
465 * @addr: the address to be translated in above address space
466 * @xlat: the translated address offset within memory region. It
467 * cannot be @NULL.
468 * @plen_out: valid read/write length of the translated address. It
469 * can be @NULL when we don't care about it.
470 * @page_mask_out: page mask for the translated address. This
471 * should only be meaningful for IOMMU translated
472 * addresses, since there may be huge pages that this bit
473 * would tell. It can be @NULL if we don't care about it.
474 * @is_write: whether the translation operation is for write
475 * @is_mmio: whether this can be MMIO, set true if it can
476 * @target_as: the address space targeted by the IOMMU
477 * @attrs: memory transaction attributes
478 *
479 * This function is called from RCU critical section
480 */
481 static MemoryRegionSection flatview_do_translate(FlatView *fv,
482 hwaddr addr,
483 hwaddr *xlat,
484 hwaddr *plen_out,
485 hwaddr *page_mask_out,
486 bool is_write,
487 bool is_mmio,
488 AddressSpace **target_as,
489 MemTxAttrs attrs)
490 {
491 MemoryRegionSection *section;
492 IOMMUMemoryRegion *iommu_mr;
493 hwaddr plen = (hwaddr)(-1);
494
495 if (!plen_out) {
496 plen_out = &plen;
497 }
498
499 section = address_space_translate_internal(
500 flatview_to_dispatch(fv), addr, xlat,
501 plen_out, is_mmio);
502
503 iommu_mr = memory_region_get_iommu(section->mr);
504 if (unlikely(iommu_mr)) {
505 return address_space_translate_iommu(iommu_mr, xlat,
506 plen_out, page_mask_out,
507 is_write, is_mmio,
508 target_as, attrs);
509 }
510 if (page_mask_out) {
511 /* Not behind an IOMMU, use default page size. */
512 *page_mask_out = ~TARGET_PAGE_MASK;
513 }
514
515 return *section;
516 }
517
518 /* Called from RCU critical section */
519 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
520 bool is_write, MemTxAttrs attrs)
521 {
522 MemoryRegionSection section;
523 hwaddr xlat, page_mask;
524
525 /*
526 * This can never be MMIO, and we don't really care about plen,
527 * but page mask.
528 */
529 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
530 NULL, &page_mask, is_write, false, &as,
531 attrs);
532
533 /* Illegal translation */
534 if (section.mr == &io_mem_unassigned) {
535 goto iotlb_fail;
536 }
537
538 /* Convert memory region offset into address space offset */
539 xlat += section.offset_within_address_space -
540 section.offset_within_region;
541
542 return (IOMMUTLBEntry) {
543 .target_as = as,
544 .iova = addr & ~page_mask,
545 .translated_addr = xlat & ~page_mask,
546 .addr_mask = page_mask,
547 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
548 .perm = IOMMU_RW,
549 };
550
551 iotlb_fail:
552 return (IOMMUTLBEntry) {0};
553 }
554
555 /* Called from RCU critical section */
556 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
557 hwaddr *plen, bool is_write,
558 MemTxAttrs attrs)
559 {
560 MemoryRegion *mr;
561 MemoryRegionSection section;
562 AddressSpace *as = NULL;
563
564 /* This can be MMIO, so setup MMIO bit. */
565 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
566 is_write, true, &as, attrs);
567 mr = section.mr;
568
569 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
570 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
571 *plen = MIN(page, *plen);
572 }
573
574 return mr;
575 }
576
577 typedef struct TCGIOMMUNotifier {
578 IOMMUNotifier n;
579 MemoryRegion *mr;
580 CPUState *cpu;
581 int iommu_idx;
582 bool active;
583 } TCGIOMMUNotifier;
584
585 static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
586 {
587 TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
588
589 if (!notifier->active) {
590 return;
591 }
592 tlb_flush(notifier->cpu);
593 notifier->active = false;
594 /* We leave the notifier struct on the list to avoid reallocating it later.
595 * Generally the number of IOMMUs a CPU deals with will be small.
596 * In any case we can't unregister the iommu notifier from a notify
597 * callback.
598 */
599 }
600
601 static void tcg_register_iommu_notifier(CPUState *cpu,
602 IOMMUMemoryRegion *iommu_mr,
603 int iommu_idx)
604 {
605 /* Make sure this CPU has an IOMMU notifier registered for this
606 * IOMMU/IOMMU index combination, so that we can flush its TLB
607 * when the IOMMU tells us the mappings we've cached have changed.
608 */
609 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
610 TCGIOMMUNotifier *notifier = NULL;
611 int i;
612
613 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
614 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
615 if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
616 break;
617 }
618 }
619 if (i == cpu->iommu_notifiers->len) {
620 /* Not found, add a new entry at the end of the array */
621 cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
622 notifier = g_new0(TCGIOMMUNotifier, 1);
623 g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
624
625 notifier->mr = mr;
626 notifier->iommu_idx = iommu_idx;
627 notifier->cpu = cpu;
628 /* Rather than trying to register interest in the specific part
629 * of the iommu's address space that we've accessed and then
630 * expand it later as subsequent accesses touch more of it, we
631 * just register interest in the whole thing, on the assumption
632 * that iommu reconfiguration will be rare.
633 */
634 iommu_notifier_init(&notifier->n,
635 tcg_iommu_unmap_notify,
636 IOMMU_NOTIFIER_UNMAP,
637 0,
638 HWADDR_MAX,
639 iommu_idx);
640 memory_region_register_iommu_notifier(notifier->mr, &notifier->n,
641 &error_fatal);
642 }
643
644 if (!notifier->active) {
645 notifier->active = true;
646 }
647 }
648
649 void tcg_iommu_free_notifier_list(CPUState *cpu)
650 {
651 /* Destroy the CPU's notifier list */
652 int i;
653 TCGIOMMUNotifier *notifier;
654
655 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
656 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
657 memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
658 g_free(notifier);
659 }
660 g_array_free(cpu->iommu_notifiers, true);
661 }
662
663 void tcg_iommu_init_notifier_list(CPUState *cpu)
664 {
665 cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
666 }
667
668 /* Called from RCU critical section */
669 MemoryRegionSection *
670 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
671 hwaddr *xlat, hwaddr *plen,
672 MemTxAttrs attrs, int *prot)
673 {
674 MemoryRegionSection *section;
675 IOMMUMemoryRegion *iommu_mr;
676 IOMMUMemoryRegionClass *imrc;
677 IOMMUTLBEntry iotlb;
678 int iommu_idx;
679 AddressSpaceDispatch *d =
680 qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
681
682 for (;;) {
683 section = address_space_translate_internal(d, addr, &addr, plen, false);
684
685 iommu_mr = memory_region_get_iommu(section->mr);
686 if (!iommu_mr) {
687 break;
688 }
689
690 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
691
692 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
693 tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
694 /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
695 * doesn't short-cut its translation table walk.
696 */
697 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
698 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
699 | (addr & iotlb.addr_mask));
700 /* Update the caller's prot bits to remove permissions the IOMMU
701 * is giving us a failure response for. If we get down to no
702 * permissions left at all we can give up now.
703 */
704 if (!(iotlb.perm & IOMMU_RO)) {
705 *prot &= ~(PAGE_READ | PAGE_EXEC);
706 }
707 if (!(iotlb.perm & IOMMU_WO)) {
708 *prot &= ~PAGE_WRITE;
709 }
710
711 if (!*prot) {
712 goto translate_fail;
713 }
714
715 d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
716 }
717
718 assert(!memory_region_is_iommu(section->mr));
719 *xlat = addr;
720 return section;
721
722 translate_fail:
723 return &d->map.sections[PHYS_SECTION_UNASSIGNED];
724 }
725
726 void cpu_address_space_init(CPUState *cpu, int asidx,
727 const char *prefix, MemoryRegion *mr)
728 {
729 CPUAddressSpace *newas;
730 AddressSpace *as = g_new0(AddressSpace, 1);
731 char *as_name;
732
733 assert(mr);
734 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
735 address_space_init(as, mr, as_name);
736 g_free(as_name);
737
738 /* Target code should have set num_ases before calling us */
739 assert(asidx < cpu->num_ases);
740
741 if (asidx == 0) {
742 /* address space 0 gets the convenience alias */
743 cpu->as = as;
744 }
745
746 /* KVM cannot currently support multiple address spaces. */
747 assert(asidx == 0 || !kvm_enabled());
748
749 if (!cpu->cpu_ases) {
750 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
751 }
752
753 newas = &cpu->cpu_ases[asidx];
754 newas->cpu = cpu;
755 newas->as = as;
756 if (tcg_enabled()) {
757 newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
758 newas->tcg_as_listener.commit = tcg_commit;
759 memory_listener_register(&newas->tcg_as_listener, as);
760 }
761 }
762
763 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
764 {
765 /* Return the AddressSpace corresponding to the specified index */
766 return cpu->cpu_ases[asidx].as;
767 }
768
769 /* Add a watchpoint. */
770 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
771 int flags, CPUWatchpoint **watchpoint)
772 {
773 CPUWatchpoint *wp;
774 vaddr in_page;
775
776 /* forbid ranges which are empty or run off the end of the address space */
777 if (len == 0 || (addr + len - 1) < addr) {
778 error_report("tried to set invalid watchpoint at %"
779 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
780 return -EINVAL;
781 }
782 wp = g_malloc(sizeof(*wp));
783
784 wp->vaddr = addr;
785 wp->len = len;
786 wp->flags = flags;
787
788 /* keep all GDB-injected watchpoints in front */
789 if (flags & BP_GDB) {
790 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
791 } else {
792 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
793 }
794
795 in_page = -(addr | TARGET_PAGE_MASK);
796 if (len <= in_page) {
797 tlb_flush_page(cpu, addr);
798 } else {
799 tlb_flush(cpu);
800 }
801
802 if (watchpoint)
803 *watchpoint = wp;
804 return 0;
805 }
806
807 /* Remove a specific watchpoint. */
808 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
809 int flags)
810 {
811 CPUWatchpoint *wp;
812
813 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
814 if (addr == wp->vaddr && len == wp->len
815 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
816 cpu_watchpoint_remove_by_ref(cpu, wp);
817 return 0;
818 }
819 }
820 return -ENOENT;
821 }
822
823 /* Remove a specific watchpoint by reference. */
824 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
825 {
826 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
827
828 tlb_flush_page(cpu, watchpoint->vaddr);
829
830 g_free(watchpoint);
831 }
832
833 /* Remove all matching watchpoints. */
834 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
835 {
836 CPUWatchpoint *wp, *next;
837
838 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
839 if (wp->flags & mask) {
840 cpu_watchpoint_remove_by_ref(cpu, wp);
841 }
842 }
843 }
844
845 #ifdef CONFIG_TCG
846 /* Return true if this watchpoint address matches the specified
847 * access (ie the address range covered by the watchpoint overlaps
848 * partially or completely with the address range covered by the
849 * access).
850 */
851 static inline bool watchpoint_address_matches(CPUWatchpoint *wp,
852 vaddr addr, vaddr len)
853 {
854 /* We know the lengths are non-zero, but a little caution is
855 * required to avoid errors in the case where the range ends
856 * exactly at the top of the address space and so addr + len
857 * wraps round to zero.
858 */
859 vaddr wpend = wp->vaddr + wp->len - 1;
860 vaddr addrend = addr + len - 1;
861
862 return !(addr > wpend || wp->vaddr > addrend);
863 }
864
865 /* Return flags for watchpoints that match addr + prot. */
866 int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len)
867 {
868 CPUWatchpoint *wp;
869 int ret = 0;
870
871 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
872 if (watchpoint_address_matches(wp, addr, len)) {
873 ret |= wp->flags;
874 }
875 }
876 return ret;
877 }
878
879 /* Generate a debug exception if a watchpoint has been hit. */
880 void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
881 MemTxAttrs attrs, int flags, uintptr_t ra)
882 {
883 CPUClass *cc = CPU_GET_CLASS(cpu);
884 CPUWatchpoint *wp;
885
886 assert(tcg_enabled());
887 if (cpu->watchpoint_hit) {
888 /*
889 * We re-entered the check after replacing the TB.
890 * Now raise the debug interrupt so that it will
891 * trigger after the current instruction.
892 */
893 qemu_mutex_lock_iothread();
894 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
895 qemu_mutex_unlock_iothread();
896 return;
897 }
898
899 if (cc->tcg_ops->adjust_watchpoint_address) {
900 /* this is currently used only by ARM BE32 */
901 addr = cc->tcg_ops->adjust_watchpoint_address(cpu, addr, len);
902 }
903 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
904 if (watchpoint_address_matches(wp, addr, len)
905 && (wp->flags & flags)) {
906 if (replay_running_debug()) {
907 /*
908 * replay_breakpoint reads icount.
909 * Force recompile to succeed, because icount may
910 * be read only at the end of the block.
911 */
912 if (!cpu->can_do_io) {
913 /* Force execution of one insn next time. */
914 cpu->cflags_next_tb = 1 | CF_LAST_IO | curr_cflags(cpu);
915 cpu_loop_exit_restore(cpu, ra);
916 }
917 /*
918 * Don't process the watchpoints when we are
919 * in a reverse debugging operation.
920 */
921 replay_breakpoint();
922 return;
923 }
924 if (flags == BP_MEM_READ) {
925 wp->flags |= BP_WATCHPOINT_HIT_READ;
926 } else {
927 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
928 }
929 wp->hitaddr = MAX(addr, wp->vaddr);
930 wp->hitattrs = attrs;
931 if (!cpu->watchpoint_hit) {
932 if (wp->flags & BP_CPU && cc->tcg_ops->debug_check_watchpoint &&
933 !cc->tcg_ops->debug_check_watchpoint(cpu, wp)) {
934 wp->flags &= ~BP_WATCHPOINT_HIT;
935 continue;
936 }
937 cpu->watchpoint_hit = wp;
938
939 mmap_lock();
940 tb_check_watchpoint(cpu, ra);
941 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
942 cpu->exception_index = EXCP_DEBUG;
943 mmap_unlock();
944 cpu_loop_exit_restore(cpu, ra);
945 } else {
946 /* Force execution of one insn next time. */
947 cpu->cflags_next_tb = 1 | curr_cflags(cpu);
948 mmap_unlock();
949 if (ra) {
950 cpu_restore_state(cpu, ra, true);
951 }
952 cpu_loop_exit_noexc(cpu);
953 }
954 }
955 } else {
956 wp->flags &= ~BP_WATCHPOINT_HIT;
957 }
958 }
959 }
960
961 #endif /* CONFIG_TCG */
962
963 /* Called from RCU critical section */
964 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
965 {
966 RAMBlock *block;
967
968 block = qatomic_rcu_read(&ram_list.mru_block);
969 if (block && addr - block->offset < block->max_length) {
970 return block;
971 }
972 RAMBLOCK_FOREACH(block) {
973 if (addr - block->offset < block->max_length) {
974 goto found;
975 }
976 }
977
978 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
979 abort();
980
981 found:
982 /* It is safe to write mru_block outside the iothread lock. This
983 * is what happens:
984 *
985 * mru_block = xxx
986 * rcu_read_unlock()
987 * xxx removed from list
988 * rcu_read_lock()
989 * read mru_block
990 * mru_block = NULL;
991 * call_rcu(reclaim_ramblock, xxx);
992 * rcu_read_unlock()
993 *
994 * qatomic_rcu_set is not needed here. The block was already published
995 * when it was placed into the list. Here we're just making an extra
996 * copy of the pointer.
997 */
998 ram_list.mru_block = block;
999 return block;
1000 }
1001
1002 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1003 {
1004 CPUState *cpu;
1005 ram_addr_t start1;
1006 RAMBlock *block;
1007 ram_addr_t end;
1008
1009 assert(tcg_enabled());
1010 end = TARGET_PAGE_ALIGN(start + length);
1011 start &= TARGET_PAGE_MASK;
1012
1013 RCU_READ_LOCK_GUARD();
1014 block = qemu_get_ram_block(start);
1015 assert(block == qemu_get_ram_block(end - 1));
1016 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1017 CPU_FOREACH(cpu) {
1018 tlb_reset_dirty(cpu, start1, length);
1019 }
1020 }
1021
1022 /* Note: start and end must be within the same ram block. */
1023 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1024 ram_addr_t length,
1025 unsigned client)
1026 {
1027 DirtyMemoryBlocks *blocks;
1028 unsigned long end, page, start_page;
1029 bool dirty = false;
1030 RAMBlock *ramblock;
1031 uint64_t mr_offset, mr_size;
1032
1033 if (length == 0) {
1034 return false;
1035 }
1036
1037 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1038 start_page = start >> TARGET_PAGE_BITS;
1039 page = start_page;
1040
1041 WITH_RCU_READ_LOCK_GUARD() {
1042 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1043 ramblock = qemu_get_ram_block(start);
1044 /* Range sanity check on the ramblock */
1045 assert(start >= ramblock->offset &&
1046 start + length <= ramblock->offset + ramblock->used_length);
1047
1048 while (page < end) {
1049 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1050 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1051 unsigned long num = MIN(end - page,
1052 DIRTY_MEMORY_BLOCK_SIZE - offset);
1053
1054 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1055 offset, num);
1056 page += num;
1057 }
1058
1059 mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
1060 mr_size = (end - start_page) << TARGET_PAGE_BITS;
1061 memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
1062 }
1063
1064 if (dirty && tcg_enabled()) {
1065 tlb_reset_dirty_range_all(start, length);
1066 }
1067
1068 return dirty;
1069 }
1070
1071 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1072 (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
1073 {
1074 DirtyMemoryBlocks *blocks;
1075 ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
1076 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1077 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1078 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1079 DirtyBitmapSnapshot *snap;
1080 unsigned long page, end, dest;
1081
1082 snap = g_malloc0(sizeof(*snap) +
1083 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1084 snap->start = first;
1085 snap->end = last;
1086
1087 page = first >> TARGET_PAGE_BITS;
1088 end = last >> TARGET_PAGE_BITS;
1089 dest = 0;
1090
1091 WITH_RCU_READ_LOCK_GUARD() {
1092 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1093
1094 while (page < end) {
1095 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1096 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1097 unsigned long num = MIN(end - page,
1098 DIRTY_MEMORY_BLOCK_SIZE - offset);
1099
1100 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1101 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1102 offset >>= BITS_PER_LEVEL;
1103
1104 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1105 blocks->blocks[idx] + offset,
1106 num);
1107 page += num;
1108 dest += num >> BITS_PER_LEVEL;
1109 }
1110 }
1111
1112 if (tcg_enabled()) {
1113 tlb_reset_dirty_range_all(start, length);
1114 }
1115
1116 memory_region_clear_dirty_bitmap(mr, offset, length);
1117
1118 return snap;
1119 }
1120
1121 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1122 ram_addr_t start,
1123 ram_addr_t length)
1124 {
1125 unsigned long page, end;
1126
1127 assert(start >= snap->start);
1128 assert(start + length <= snap->end);
1129
1130 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1131 page = (start - snap->start) >> TARGET_PAGE_BITS;
1132
1133 while (page < end) {
1134 if (test_bit(page, snap->dirty)) {
1135 return true;
1136 }
1137 page++;
1138 }
1139 return false;
1140 }
1141
1142 /* Called from RCU critical section */
1143 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1144 MemoryRegionSection *section)
1145 {
1146 AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
1147 return section - d->map.sections;
1148 }
1149
1150 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
1151 uint16_t section);
1152 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1153
1154 static uint16_t phys_section_add(PhysPageMap *map,
1155 MemoryRegionSection *section)
1156 {
1157 /* The physical section number is ORed with a page-aligned
1158 * pointer to produce the iotlb entries. Thus it should
1159 * never overflow into the page-aligned value.
1160 */
1161 assert(map->sections_nb < TARGET_PAGE_SIZE);
1162
1163 if (map->sections_nb == map->sections_nb_alloc) {
1164 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1165 map->sections = g_renew(MemoryRegionSection, map->sections,
1166 map->sections_nb_alloc);
1167 }
1168 map->sections[map->sections_nb] = *section;
1169 memory_region_ref(section->mr);
1170 return map->sections_nb++;
1171 }
1172
1173 static void phys_section_destroy(MemoryRegion *mr)
1174 {
1175 bool have_sub_page = mr->subpage;
1176
1177 memory_region_unref(mr);
1178
1179 if (have_sub_page) {
1180 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1181 object_unref(OBJECT(&subpage->iomem));
1182 g_free(subpage);
1183 }
1184 }
1185
1186 static void phys_sections_free(PhysPageMap *map)
1187 {
1188 while (map->sections_nb > 0) {
1189 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1190 phys_section_destroy(section->mr);
1191 }
1192 g_free(map->sections);
1193 g_free(map->nodes);
1194 }
1195
1196 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1197 {
1198 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1199 subpage_t *subpage;
1200 hwaddr base = section->offset_within_address_space
1201 & TARGET_PAGE_MASK;
1202 MemoryRegionSection *existing = phys_page_find(d, base);
1203 MemoryRegionSection subsection = {
1204 .offset_within_address_space = base,
1205 .size = int128_make64(TARGET_PAGE_SIZE),
1206 };
1207 hwaddr start, end;
1208
1209 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1210
1211 if (!(existing->mr->subpage)) {
1212 subpage = subpage_init(fv, base);
1213 subsection.fv = fv;
1214 subsection.mr = &subpage->iomem;
1215 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1216 phys_section_add(&d->map, &subsection));
1217 } else {
1218 subpage = container_of(existing->mr, subpage_t, iomem);
1219 }
1220 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1221 end = start + int128_get64(section->size) - 1;
1222 subpage_register(subpage, start, end,
1223 phys_section_add(&d->map, section));
1224 }
1225
1226
1227 static void register_multipage(FlatView *fv,
1228 MemoryRegionSection *section)
1229 {
1230 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1231 hwaddr start_addr = section->offset_within_address_space;
1232 uint16_t section_index = phys_section_add(&d->map, section);
1233 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1234 TARGET_PAGE_BITS));
1235
1236 assert(num_pages);
1237 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1238 }
1239
1240 /*
1241 * The range in *section* may look like this:
1242 *
1243 * |s|PPPPPPP|s|
1244 *
1245 * where s stands for subpage and P for page.
1246 */
1247 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1248 {
1249 MemoryRegionSection remain = *section;
1250 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1251
1252 /* register first subpage */
1253 if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1254 uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1255 - remain.offset_within_address_space;
1256
1257 MemoryRegionSection now = remain;
1258 now.size = int128_min(int128_make64(left), now.size);
1259 register_subpage(fv, &now);
1260 if (int128_eq(remain.size, now.size)) {
1261 return;
1262 }
1263 remain.size = int128_sub(remain.size, now.size);
1264 remain.offset_within_address_space += int128_get64(now.size);
1265 remain.offset_within_region += int128_get64(now.size);
1266 }
1267
1268 /* register whole pages */
1269 if (int128_ge(remain.size, page_size)) {
1270 MemoryRegionSection now = remain;
1271 now.size = int128_and(now.size, int128_neg(page_size));
1272 register_multipage(fv, &now);
1273 if (int128_eq(remain.size, now.size)) {
1274 return;
1275 }
1276 remain.size = int128_sub(remain.size, now.size);
1277 remain.offset_within_address_space += int128_get64(now.size);
1278 remain.offset_within_region += int128_get64(now.size);
1279 }
1280
1281 /* register last subpage */
1282 register_subpage(fv, &remain);
1283 }
1284
1285 void qemu_flush_coalesced_mmio_buffer(void)
1286 {
1287 if (kvm_enabled())
1288 kvm_flush_coalesced_mmio_buffer();
1289 }
1290
1291 void qemu_mutex_lock_ramlist(void)
1292 {
1293 qemu_mutex_lock(&ram_list.mutex);
1294 }
1295
1296 void qemu_mutex_unlock_ramlist(void)
1297 {
1298 qemu_mutex_unlock(&ram_list.mutex);
1299 }
1300
1301 void ram_block_dump(Monitor *mon)
1302 {
1303 RAMBlock *block;
1304 char *psize;
1305
1306 RCU_READ_LOCK_GUARD();
1307 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1308 "Block Name", "PSize", "Offset", "Used", "Total");
1309 RAMBLOCK_FOREACH(block) {
1310 psize = size_to_str(block->page_size);
1311 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1312 " 0x%016" PRIx64 "\n", block->idstr, psize,
1313 (uint64_t)block->offset,
1314 (uint64_t)block->used_length,
1315 (uint64_t)block->max_length);
1316 g_free(psize);
1317 }
1318 }
1319
1320 #ifdef __linux__
1321 /*
1322 * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1323 * may or may not name the same files / on the same filesystem now as
1324 * when we actually open and map them. Iterate over the file
1325 * descriptors instead, and use qemu_fd_getpagesize().
1326 */
1327 static int find_min_backend_pagesize(Object *obj, void *opaque)
1328 {
1329 long *hpsize_min = opaque;
1330
1331 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1332 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1333 long hpsize = host_memory_backend_pagesize(backend);
1334
1335 if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
1336 *hpsize_min = hpsize;
1337 }
1338 }
1339
1340 return 0;
1341 }
1342
1343 static int find_max_backend_pagesize(Object *obj, void *opaque)
1344 {
1345 long *hpsize_max = opaque;
1346
1347 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1348 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1349 long hpsize = host_memory_backend_pagesize(backend);
1350
1351 if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1352 *hpsize_max = hpsize;
1353 }
1354 }
1355
1356 return 0;
1357 }
1358
1359 /*
1360 * TODO: We assume right now that all mapped host memory backends are
1361 * used as RAM, however some might be used for different purposes.
1362 */
1363 long qemu_minrampagesize(void)
1364 {
1365 long hpsize = LONG_MAX;
1366 Object *memdev_root = object_resolve_path("/objects", NULL);
1367
1368 object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
1369 return hpsize;
1370 }
1371
1372 long qemu_maxrampagesize(void)
1373 {
1374 long pagesize = 0;
1375 Object *memdev_root = object_resolve_path("/objects", NULL);
1376
1377 object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
1378 return pagesize;
1379 }
1380 #else
1381 long qemu_minrampagesize(void)
1382 {
1383 return qemu_real_host_page_size;
1384 }
1385 long qemu_maxrampagesize(void)
1386 {
1387 return qemu_real_host_page_size;
1388 }
1389 #endif
1390
1391 #ifdef CONFIG_POSIX
1392 static int64_t get_file_size(int fd)
1393 {
1394 int64_t size;
1395 #if defined(__linux__)
1396 struct stat st;
1397
1398 if (fstat(fd, &st) < 0) {
1399 return -errno;
1400 }
1401
1402 /* Special handling for devdax character devices */
1403 if (S_ISCHR(st.st_mode)) {
1404 g_autofree char *subsystem_path = NULL;
1405 g_autofree char *subsystem = NULL;
1406
1407 subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1408 major(st.st_rdev), minor(st.st_rdev));
1409 subsystem = g_file_read_link(subsystem_path, NULL);
1410
1411 if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
1412 g_autofree char *size_path = NULL;
1413 g_autofree char *size_str = NULL;
1414
1415 size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
1416 major(st.st_rdev), minor(st.st_rdev));
1417
1418 if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
1419 return g_ascii_strtoll(size_str, NULL, 0);
1420 }
1421 }
1422 }
1423 #endif /* defined(__linux__) */
1424
1425 /* st.st_size may be zero for special files yet lseek(2) works */
1426 size = lseek(fd, 0, SEEK_END);
1427 if (size < 0) {
1428 return -errno;
1429 }
1430 return size;
1431 }
1432
1433 static int64_t get_file_align(int fd)
1434 {
1435 int64_t align = -1;
1436 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1437 struct stat st;
1438
1439 if (fstat(fd, &st) < 0) {
1440 return -errno;
1441 }
1442
1443 /* Special handling for devdax character devices */
1444 if (S_ISCHR(st.st_mode)) {
1445 g_autofree char *path = NULL;
1446 g_autofree char *rpath = NULL;
1447 struct daxctl_ctx *ctx;
1448 struct daxctl_region *region;
1449 int rc = 0;
1450
1451 path = g_strdup_printf("/sys/dev/char/%d:%d",
1452 major(st.st_rdev), minor(st.st_rdev));
1453 rpath = realpath(path, NULL);
1454
1455 rc = daxctl_new(&ctx);
1456 if (rc) {
1457 return -1;
1458 }
1459
1460 daxctl_region_foreach(ctx, region) {
1461 if (strstr(rpath, daxctl_region_get_path(region))) {
1462 align = daxctl_region_get_align(region);
1463 break;
1464 }
1465 }
1466 daxctl_unref(ctx);
1467 }
1468 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1469
1470 return align;
1471 }
1472
1473 static int file_ram_open(const char *path,
1474 const char *region_name,
1475 bool readonly,
1476 bool *created,
1477 Error **errp)
1478 {
1479 char *filename;
1480 char *sanitized_name;
1481 char *c;
1482 int fd = -1;
1483
1484 *created = false;
1485 for (;;) {
1486 fd = open(path, readonly ? O_RDONLY : O_RDWR);
1487 if (fd >= 0) {
1488 /* @path names an existing file, use it */
1489 break;
1490 }
1491 if (errno == ENOENT) {
1492 /* @path names a file that doesn't exist, create it */
1493 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1494 if (fd >= 0) {
1495 *created = true;
1496 break;
1497 }
1498 } else if (errno == EISDIR) {
1499 /* @path names a directory, create a file there */
1500 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1501 sanitized_name = g_strdup(region_name);
1502 for (c = sanitized_name; *c != '\0'; c++) {
1503 if (*c == '/') {
1504 *c = '_';
1505 }
1506 }
1507
1508 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1509 sanitized_name);
1510 g_free(sanitized_name);
1511
1512 fd = mkstemp(filename);
1513 if (fd >= 0) {
1514 unlink(filename);
1515 g_free(filename);
1516 break;
1517 }
1518 g_free(filename);
1519 }
1520 if (errno != EEXIST && errno != EINTR) {
1521 error_setg_errno(errp, errno,
1522 "can't open backing store %s for guest RAM",
1523 path);
1524 return -1;
1525 }
1526 /*
1527 * Try again on EINTR and EEXIST. The latter happens when
1528 * something else creates the file between our two open().
1529 */
1530 }
1531
1532 return fd;
1533 }
1534
1535 static void *file_ram_alloc(RAMBlock *block,
1536 ram_addr_t memory,
1537 int fd,
1538 bool readonly,
1539 bool truncate,
1540 off_t offset,
1541 Error **errp)
1542 {
1543 void *area;
1544
1545 block->page_size = qemu_fd_getpagesize(fd);
1546 if (block->mr->align % block->page_size) {
1547 error_setg(errp, "alignment 0x%" PRIx64
1548 " must be multiples of page size 0x%zx",
1549 block->mr->align, block->page_size);
1550 return NULL;
1551 } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1552 error_setg(errp, "alignment 0x%" PRIx64
1553 " must be a power of two", block->mr->align);
1554 return NULL;
1555 }
1556 block->mr->align = MAX(block->page_size, block->mr->align);
1557 #if defined(__s390x__)
1558 if (kvm_enabled()) {
1559 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1560 }
1561 #endif
1562
1563 if (memory < block->page_size) {
1564 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1565 "or larger than page size 0x%zx",
1566 memory, block->page_size);
1567 return NULL;
1568 }
1569
1570 memory = ROUND_UP(memory, block->page_size);
1571
1572 /*
1573 * ftruncate is not supported by hugetlbfs in older
1574 * hosts, so don't bother bailing out on errors.
1575 * If anything goes wrong with it under other filesystems,
1576 * mmap will fail.
1577 *
1578 * Do not truncate the non-empty backend file to avoid corrupting
1579 * the existing data in the file. Disabling shrinking is not
1580 * enough. For example, the current vNVDIMM implementation stores
1581 * the guest NVDIMM labels at the end of the backend file. If the
1582 * backend file is later extended, QEMU will not be able to find
1583 * those labels. Therefore, extending the non-empty backend file
1584 * is disabled as well.
1585 */
1586 if (truncate && ftruncate(fd, memory)) {
1587 perror("ftruncate");
1588 }
1589
1590 area = qemu_ram_mmap(fd, memory, block->mr->align, readonly,
1591 block->flags & RAM_SHARED, block->flags & RAM_PMEM,
1592 offset);
1593 if (area == MAP_FAILED) {
1594 error_setg_errno(errp, errno,
1595 "unable to map backing store for guest RAM");
1596 return NULL;
1597 }
1598
1599 block->fd = fd;
1600 return area;
1601 }
1602 #endif
1603
1604 /* Allocate space within the ram_addr_t space that governs the
1605 * dirty bitmaps.
1606 * Called with the ramlist lock held.
1607 */
1608 static ram_addr_t find_ram_offset(ram_addr_t size)
1609 {
1610 RAMBlock *block, *next_block;
1611 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1612
1613 assert(size != 0); /* it would hand out same offset multiple times */
1614
1615 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1616 return 0;
1617 }
1618
1619 RAMBLOCK_FOREACH(block) {
1620 ram_addr_t candidate, next = RAM_ADDR_MAX;
1621
1622 /* Align blocks to start on a 'long' in the bitmap
1623 * which makes the bitmap sync'ing take the fast path.
1624 */
1625 candidate = block->offset + block->max_length;
1626 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1627
1628 /* Search for the closest following block
1629 * and find the gap.
1630 */
1631 RAMBLOCK_FOREACH(next_block) {
1632 if (next_block->offset >= candidate) {
1633 next = MIN(next, next_block->offset);
1634 }
1635 }
1636
1637 /* If it fits remember our place and remember the size
1638 * of gap, but keep going so that we might find a smaller
1639 * gap to fill so avoiding fragmentation.
1640 */
1641 if (next - candidate >= size && next - candidate < mingap) {
1642 offset = candidate;
1643 mingap = next - candidate;
1644 }
1645
1646 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1647 }
1648
1649 if (offset == RAM_ADDR_MAX) {
1650 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1651 (uint64_t)size);
1652 abort();
1653 }
1654
1655 trace_find_ram_offset(size, offset);
1656
1657 return offset;
1658 }
1659
1660 static unsigned long last_ram_page(void)
1661 {
1662 RAMBlock *block;
1663 ram_addr_t last = 0;
1664
1665 RCU_READ_LOCK_GUARD();
1666 RAMBLOCK_FOREACH(block) {
1667 last = MAX(last, block->offset + block->max_length);
1668 }
1669 return last >> TARGET_PAGE_BITS;
1670 }
1671
1672 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1673 {
1674 int ret;
1675
1676 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1677 if (!machine_dump_guest_core(current_machine)) {
1678 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1679 if (ret) {
1680 perror("qemu_madvise");
1681 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1682 "but dump_guest_core=off specified\n");
1683 }
1684 }
1685 }
1686
1687 const char *qemu_ram_get_idstr(RAMBlock *rb)
1688 {
1689 return rb->idstr;
1690 }
1691
1692 void *qemu_ram_get_host_addr(RAMBlock *rb)
1693 {
1694 return rb->host;
1695 }
1696
1697 ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
1698 {
1699 return rb->offset;
1700 }
1701
1702 ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
1703 {
1704 return rb->used_length;
1705 }
1706
1707 ram_addr_t qemu_ram_get_max_length(RAMBlock *rb)
1708 {
1709 return rb->max_length;
1710 }
1711
1712 bool qemu_ram_is_shared(RAMBlock *rb)
1713 {
1714 return rb->flags & RAM_SHARED;
1715 }
1716
1717 /* Note: Only set at the start of postcopy */
1718 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1719 {
1720 return rb->flags & RAM_UF_ZEROPAGE;
1721 }
1722
1723 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1724 {
1725 rb->flags |= RAM_UF_ZEROPAGE;
1726 }
1727
1728 bool qemu_ram_is_migratable(RAMBlock *rb)
1729 {
1730 return rb->flags & RAM_MIGRATABLE;
1731 }
1732
1733 void qemu_ram_set_migratable(RAMBlock *rb)
1734 {
1735 rb->flags |= RAM_MIGRATABLE;
1736 }
1737
1738 void qemu_ram_unset_migratable(RAMBlock *rb)
1739 {
1740 rb->flags &= ~RAM_MIGRATABLE;
1741 }
1742
1743 /* Called with iothread lock held. */
1744 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1745 {
1746 RAMBlock *block;
1747
1748 assert(new_block);
1749 assert(!new_block->idstr[0]);
1750
1751 if (dev) {
1752 char *id = qdev_get_dev_path(dev);
1753 if (id) {
1754 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1755 g_free(id);
1756 }
1757 }
1758 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1759
1760 RCU_READ_LOCK_GUARD();
1761 RAMBLOCK_FOREACH(block) {
1762 if (block != new_block &&
1763 !strcmp(block->idstr, new_block->idstr)) {
1764 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1765 new_block->idstr);
1766 abort();
1767 }
1768 }
1769 }
1770
1771 /* Called with iothread lock held. */
1772 void qemu_ram_unset_idstr(RAMBlock *block)
1773 {
1774 /* FIXME: arch_init.c assumes that this is not called throughout
1775 * migration. Ignore the problem since hot-unplug during migration
1776 * does not work anyway.
1777 */
1778 if (block) {
1779 memset(block->idstr, 0, sizeof(block->idstr));
1780 }
1781 }
1782
1783 size_t qemu_ram_pagesize(RAMBlock *rb)
1784 {
1785 return rb->page_size;
1786 }
1787
1788 /* Returns the largest size of page in use */
1789 size_t qemu_ram_pagesize_largest(void)
1790 {
1791 RAMBlock *block;
1792 size_t largest = 0;
1793
1794 RAMBLOCK_FOREACH(block) {
1795 largest = MAX(largest, qemu_ram_pagesize(block));
1796 }
1797
1798 return largest;
1799 }
1800
1801 static int memory_try_enable_merging(void *addr, size_t len)
1802 {
1803 if (!machine_mem_merge(current_machine)) {
1804 /* disabled by the user */
1805 return 0;
1806 }
1807
1808 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1809 }
1810
1811 /*
1812 * Resizing RAM while migrating can result in the migration being canceled.
1813 * Care has to be taken if the guest might have already detected the memory.
1814 *
1815 * As memory core doesn't know how is memory accessed, it is up to
1816 * resize callback to update device state and/or add assertions to detect
1817 * misuse, if necessary.
1818 */
1819 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1820 {
1821 const ram_addr_t oldsize = block->used_length;
1822 const ram_addr_t unaligned_size = newsize;
1823
1824 assert(block);
1825
1826 newsize = HOST_PAGE_ALIGN(newsize);
1827
1828 if (block->used_length == newsize) {
1829 /*
1830 * We don't have to resize the ram block (which only knows aligned
1831 * sizes), however, we have to notify if the unaligned size changed.
1832 */
1833 if (unaligned_size != memory_region_size(block->mr)) {
1834 memory_region_set_size(block->mr, unaligned_size);
1835 if (block->resized) {
1836 block->resized(block->idstr, unaligned_size, block->host);
1837 }
1838 }
1839 return 0;
1840 }
1841
1842 if (!(block->flags & RAM_RESIZEABLE)) {
1843 error_setg_errno(errp, EINVAL,
1844 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1845 " != 0x" RAM_ADDR_FMT, block->idstr,
1846 newsize, block->used_length);
1847 return -EINVAL;
1848 }
1849
1850 if (block->max_length < newsize) {
1851 error_setg_errno(errp, EINVAL,
1852 "Size too large: %s: 0x" RAM_ADDR_FMT
1853 " > 0x" RAM_ADDR_FMT, block->idstr,
1854 newsize, block->max_length);
1855 return -EINVAL;
1856 }
1857
1858 /* Notify before modifying the ram block and touching the bitmaps. */
1859 if (block->host) {
1860 ram_block_notify_resize(block->host, oldsize, newsize);
1861 }
1862
1863 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1864 block->used_length = newsize;
1865 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1866 DIRTY_CLIENTS_ALL);
1867 memory_region_set_size(block->mr, unaligned_size);
1868 if (block->resized) {
1869 block->resized(block->idstr, unaligned_size, block->host);
1870 }
1871 return 0;
1872 }
1873
1874 /*
1875 * Trigger sync on the given ram block for range [start, start + length]
1876 * with the backing store if one is available.
1877 * Otherwise no-op.
1878 * @Note: this is supposed to be a synchronous op.
1879 */
1880 void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
1881 {
1882 /* The requested range should fit in within the block range */
1883 g_assert((start + length) <= block->used_length);
1884
1885 #ifdef CONFIG_LIBPMEM
1886 /* The lack of support for pmem should not block the sync */
1887 if (ramblock_is_pmem(block)) {
1888 void *addr = ramblock_ptr(block, start);
1889 pmem_persist(addr, length);
1890 return;
1891 }
1892 #endif
1893 if (block->fd >= 0) {
1894 /**
1895 * Case there is no support for PMEM or the memory has not been
1896 * specified as persistent (or is not one) - use the msync.
1897 * Less optimal but still achieves the same goal
1898 */
1899 void *addr = ramblock_ptr(block, start);
1900 if (qemu_msync(addr, length, block->fd)) {
1901 warn_report("%s: failed to sync memory range: start: "
1902 RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
1903 __func__, start, length);
1904 }
1905 }
1906 }
1907
1908 /* Called with ram_list.mutex held */
1909 static void dirty_memory_extend(ram_addr_t old_ram_size,
1910 ram_addr_t new_ram_size)
1911 {
1912 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1913 DIRTY_MEMORY_BLOCK_SIZE);
1914 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1915 DIRTY_MEMORY_BLOCK_SIZE);
1916 int i;
1917
1918 /* Only need to extend if block count increased */
1919 if (new_num_blocks <= old_num_blocks) {
1920 return;
1921 }
1922
1923 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1924 DirtyMemoryBlocks *old_blocks;
1925 DirtyMemoryBlocks *new_blocks;
1926 int j;
1927
1928 old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
1929 new_blocks = g_malloc(sizeof(*new_blocks) +
1930 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1931
1932 if (old_num_blocks) {
1933 memcpy(new_blocks->blocks, old_blocks->blocks,
1934 old_num_blocks * sizeof(old_blocks->blocks[0]));
1935 }
1936
1937 for (j = old_num_blocks; j < new_num_blocks; j++) {
1938 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1939 }
1940
1941 qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1942
1943 if (old_blocks) {
1944 g_free_rcu(old_blocks, rcu);
1945 }
1946 }
1947 }
1948
1949 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
1950 {
1951 RAMBlock *block;
1952 RAMBlock *last_block = NULL;
1953 ram_addr_t old_ram_size, new_ram_size;
1954 Error *err = NULL;
1955
1956 old_ram_size = last_ram_page();
1957
1958 qemu_mutex_lock_ramlist();
1959 new_block->offset = find_ram_offset(new_block->max_length);
1960
1961 if (!new_block->host) {
1962 if (xen_enabled()) {
1963 xen_ram_alloc(new_block->offset, new_block->max_length,
1964 new_block->mr, &err);
1965 if (err) {
1966 error_propagate(errp, err);
1967 qemu_mutex_unlock_ramlist();
1968 return;
1969 }
1970 } else {
1971 new_block->host = qemu_anon_ram_alloc(new_block->max_length,
1972 &new_block->mr->align,
1973 shared);
1974 if (!new_block->host) {
1975 error_setg_errno(errp, errno,
1976 "cannot set up guest memory '%s'",
1977 memory_region_name(new_block->mr));
1978 qemu_mutex_unlock_ramlist();
1979 return;
1980 }
1981 memory_try_enable_merging(new_block->host, new_block->max_length);
1982 }
1983 }
1984
1985 new_ram_size = MAX(old_ram_size,
1986 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1987 if (new_ram_size > old_ram_size) {
1988 dirty_memory_extend(old_ram_size, new_ram_size);
1989 }
1990 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1991 * QLIST (which has an RCU-friendly variant) does not have insertion at
1992 * tail, so save the last element in last_block.
1993 */
1994 RAMBLOCK_FOREACH(block) {
1995 last_block = block;
1996 if (block->max_length < new_block->max_length) {
1997 break;
1998 }
1999 }
2000 if (block) {
2001 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
2002 } else if (last_block) {
2003 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
2004 } else { /* list is empty */
2005 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
2006 }
2007 ram_list.mru_block = NULL;
2008
2009 /* Write list before version */
2010 smp_wmb();
2011 ram_list.version++;
2012 qemu_mutex_unlock_ramlist();
2013
2014 cpu_physical_memory_set_dirty_range(new_block->offset,
2015 new_block->used_length,
2016 DIRTY_CLIENTS_ALL);
2017
2018 if (new_block->host) {
2019 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2020 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2021 /*
2022 * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
2023 * Configure it unless the machine is a qtest server, in which case
2024 * KVM is not used and it may be forked (eg for fuzzing purposes).
2025 */
2026 if (!qtest_enabled()) {
2027 qemu_madvise(new_block->host, new_block->max_length,
2028 QEMU_MADV_DONTFORK);
2029 }
2030 ram_block_notify_add(new_block->host, new_block->used_length,
2031 new_block->max_length);
2032 }
2033 }
2034
2035 #ifdef CONFIG_POSIX
2036 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2037 uint32_t ram_flags, int fd, off_t offset,
2038 bool readonly, Error **errp)
2039 {
2040 RAMBlock *new_block;
2041 Error *local_err = NULL;
2042 int64_t file_size, file_align;
2043
2044 /* Just support these ram flags by now. */
2045 assert((ram_flags & ~(RAM_SHARED | RAM_PMEM)) == 0);
2046
2047 if (xen_enabled()) {
2048 error_setg(errp, "-mem-path not supported with Xen");
2049 return NULL;
2050 }
2051
2052 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2053 error_setg(errp,
2054 "host lacks kvm mmu notifiers, -mem-path unsupported");
2055 return NULL;
2056 }
2057
2058 size = HOST_PAGE_ALIGN(size);
2059 file_size = get_file_size(fd);
2060 if (file_size > 0 && file_size < size) {
2061 error_setg(errp, "backing store size 0x%" PRIx64
2062 " does not match 'size' option 0x" RAM_ADDR_FMT,
2063 file_size, size);
2064 return NULL;
2065 }
2066
2067 file_align = get_file_align(fd);
2068 if (file_align > 0 && mr && file_align > mr->align) {
2069 error_setg(errp, "backing store align 0x%" PRIx64
2070 " is larger than 'align' option 0x%" PRIx64,
2071 file_align, mr->align);
2072 return NULL;
2073 }
2074
2075 new_block = g_malloc0(sizeof(*new_block));
2076 new_block->mr = mr;
2077 new_block->used_length = size;
2078 new_block->max_length = size;
2079 new_block->flags = ram_flags;
2080 new_block->host = file_ram_alloc(new_block, size, fd, readonly,
2081 !file_size, offset, errp);
2082 if (!new_block->host) {
2083 g_free(new_block);
2084 return NULL;
2085 }
2086
2087 ram_block_add(new_block, &local_err, ram_flags & RAM_SHARED);
2088 if (local_err) {
2089 g_free(new_block);
2090 error_propagate(errp, local_err);
2091 return NULL;
2092 }
2093 return new_block;
2094
2095 }
2096
2097
2098 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2099 uint32_t ram_flags, const char *mem_path,
2100 bool readonly, Error **errp)
2101 {
2102 int fd;
2103 bool created;
2104 RAMBlock *block;
2105
2106 fd = file_ram_open(mem_path, memory_region_name(mr), readonly, &created,
2107 errp);
2108 if (fd < 0) {
2109 return NULL;
2110 }
2111
2112 block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, 0, readonly, errp);
2113 if (!block) {
2114 if (created) {
2115 unlink(mem_path);
2116 }
2117 close(fd);
2118 return NULL;
2119 }
2120
2121 return block;
2122 }
2123 #endif
2124
2125 static
2126 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2127 void (*resized)(const char*,
2128 uint64_t length,
2129 void *host),
2130 void *host, bool resizeable, bool share,
2131 MemoryRegion *mr, Error **errp)
2132 {
2133 RAMBlock *new_block;
2134 Error *local_err = NULL;
2135
2136 size = HOST_PAGE_ALIGN(size);
2137 max_size = HOST_PAGE_ALIGN(max_size);
2138 new_block = g_malloc0(sizeof(*new_block));
2139 new_block->mr = mr;
2140 new_block->resized = resized;
2141 new_block->used_length = size;
2142 new_block->max_length = max_size;
2143 assert(max_size >= size);
2144 new_block->fd = -1;
2145 new_block->page_size = qemu_real_host_page_size;
2146 new_block->host = host;
2147 if (host) {
2148 new_block->flags |= RAM_PREALLOC;
2149 }
2150 if (resizeable) {
2151 new_block->flags |= RAM_RESIZEABLE;
2152 }
2153 ram_block_add(new_block, &local_err, share);
2154 if (local_err) {
2155 g_free(new_block);
2156 error_propagate(errp, local_err);
2157 return NULL;
2158 }
2159 return new_block;
2160 }
2161
2162 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2163 MemoryRegion *mr, Error **errp)
2164 {
2165 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2166 false, mr, errp);
2167 }
2168
2169 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2170 MemoryRegion *mr, Error **errp)
2171 {
2172 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2173 share, mr, errp);
2174 }
2175
2176 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2177 void (*resized)(const char*,
2178 uint64_t length,
2179 void *host),
2180 MemoryRegion *mr, Error **errp)
2181 {
2182 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2183 false, mr, errp);
2184 }
2185
2186 static void reclaim_ramblock(RAMBlock *block)
2187 {
2188 if (block->flags & RAM_PREALLOC) {
2189 ;
2190 } else if (xen_enabled()) {
2191 xen_invalidate_map_cache_entry(block->host);
2192 #ifndef _WIN32
2193 } else if (block->fd >= 0) {
2194 qemu_ram_munmap(block->fd, block->host, block->max_length);
2195 close(block->fd);
2196 #endif
2197 } else {
2198 qemu_anon_ram_free(block->host, block->max_length);
2199 }
2200 g_free(block);
2201 }
2202
2203 void qemu_ram_free(RAMBlock *block)
2204 {
2205 if (!block) {
2206 return;
2207 }
2208
2209 if (block->host) {
2210 ram_block_notify_remove(block->host, block->used_length,
2211 block->max_length);
2212 }
2213
2214 qemu_mutex_lock_ramlist();
2215 QLIST_REMOVE_RCU(block, next);
2216 ram_list.mru_block = NULL;
2217 /* Write list before version */
2218 smp_wmb();
2219 ram_list.version++;
2220 call_rcu(block, reclaim_ramblock, rcu);
2221 qemu_mutex_unlock_ramlist();
2222 }
2223
2224 #ifndef _WIN32
2225 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2226 {
2227 RAMBlock *block;
2228 ram_addr_t offset;
2229 int flags;
2230 void *area, *vaddr;
2231
2232 RAMBLOCK_FOREACH(block) {
2233 offset = addr - block->offset;
2234 if (offset < block->max_length) {
2235 vaddr = ramblock_ptr(block, offset);
2236 if (block->flags & RAM_PREALLOC) {
2237 ;
2238 } else if (xen_enabled()) {
2239 abort();
2240 } else {
2241 flags = MAP_FIXED;
2242 if (block->fd >= 0) {
2243 flags |= (block->flags & RAM_SHARED ?
2244 MAP_SHARED : MAP_PRIVATE);
2245 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2246 flags, block->fd, offset);
2247 } else {
2248 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2249 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2250 flags, -1, 0);
2251 }
2252 if (area != vaddr) {
2253 error_report("Could not remap addr: "
2254 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2255 length, addr);
2256 exit(1);
2257 }
2258 memory_try_enable_merging(vaddr, length);
2259 qemu_ram_setup_dump(vaddr, length);
2260 }
2261 }
2262 }
2263 }
2264 #endif /* !_WIN32 */
2265
2266 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2267 * This should not be used for general purpose DMA. Use address_space_map
2268 * or address_space_rw instead. For local memory (e.g. video ram) that the
2269 * device owns, use memory_region_get_ram_ptr.
2270 *
2271 * Called within RCU critical section.
2272 */
2273 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2274 {
2275 RAMBlock *block = ram_block;
2276
2277 if (block == NULL) {
2278 block = qemu_get_ram_block(addr);
2279 addr -= block->offset;
2280 }
2281
2282 if (xen_enabled() && block->host == NULL) {
2283 /* We need to check if the requested address is in the RAM
2284 * because we don't want to map the entire memory in QEMU.
2285 * In that case just map until the end of the page.
2286 */
2287 if (block->offset == 0) {
2288 return xen_map_cache(addr, 0, 0, false);
2289 }
2290
2291 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2292 }
2293 return ramblock_ptr(block, addr);
2294 }
2295
2296 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2297 * but takes a size argument.
2298 *
2299 * Called within RCU critical section.
2300 */
2301 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2302 hwaddr *size, bool lock)
2303 {
2304 RAMBlock *block = ram_block;
2305 if (*size == 0) {
2306 return NULL;
2307 }
2308
2309 if (block == NULL) {
2310 block = qemu_get_ram_block(addr);
2311 addr -= block->offset;
2312 }
2313 *size = MIN(*size, block->max_length - addr);
2314
2315 if (xen_enabled() && block->host == NULL) {
2316 /* We need to check if the requested address is in the RAM
2317 * because we don't want to map the entire memory in QEMU.
2318 * In that case just map the requested area.
2319 */
2320 if (block->offset == 0) {
2321 return xen_map_cache(addr, *size, lock, lock);
2322 }
2323
2324 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2325 }
2326
2327 return ramblock_ptr(block, addr);
2328 }
2329
2330 /* Return the offset of a hostpointer within a ramblock */
2331 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2332 {
2333 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2334 assert((uintptr_t)host >= (uintptr_t)rb->host);
2335 assert(res < rb->max_length);
2336
2337 return res;
2338 }
2339
2340 /*
2341 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2342 * in that RAMBlock.
2343 *
2344 * ptr: Host pointer to look up
2345 * round_offset: If true round the result offset down to a page boundary
2346 * *ram_addr: set to result ram_addr
2347 * *offset: set to result offset within the RAMBlock
2348 *
2349 * Returns: RAMBlock (or NULL if not found)
2350 *
2351 * By the time this function returns, the returned pointer is not protected
2352 * by RCU anymore. If the caller is not within an RCU critical section and
2353 * does not hold the iothread lock, it must have other means of protecting the
2354 * pointer, such as a reference to the region that includes the incoming
2355 * ram_addr_t.
2356 */
2357 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2358 ram_addr_t *offset)
2359 {
2360 RAMBlock *block;
2361 uint8_t *host = ptr;
2362
2363 if (xen_enabled()) {
2364 ram_addr_t ram_addr;
2365 RCU_READ_LOCK_GUARD();
2366 ram_addr = xen_ram_addr_from_mapcache(ptr);
2367 block = qemu_get_ram_block(ram_addr);
2368 if (block) {
2369 *offset = ram_addr - block->offset;
2370 }
2371 return block;
2372 }
2373
2374 RCU_READ_LOCK_GUARD();
2375 block = qatomic_rcu_read(&ram_list.mru_block);
2376 if (block && block->host && host - block->host < block->max_length) {
2377 goto found;
2378 }
2379
2380 RAMBLOCK_FOREACH(block) {
2381 /* This case append when the block is not mapped. */
2382 if (block->host == NULL) {
2383 continue;
2384 }
2385 if (host - block->host < block->max_length) {
2386 goto found;
2387 }
2388 }
2389
2390 return NULL;
2391
2392 found:
2393 *offset = (host - block->host);
2394 if (round_offset) {
2395 *offset &= TARGET_PAGE_MASK;
2396 }
2397 return block;
2398 }
2399
2400 /*
2401 * Finds the named RAMBlock
2402 *
2403 * name: The name of RAMBlock to find
2404 *
2405 * Returns: RAMBlock (or NULL if not found)
2406 */
2407 RAMBlock *qemu_ram_block_by_name(const char *name)
2408 {
2409 RAMBlock *block;
2410
2411 RAMBLOCK_FOREACH(block) {
2412 if (!strcmp(name, block->idstr)) {
2413 return block;
2414 }
2415 }
2416
2417 return NULL;
2418 }
2419
2420 /* Some of the softmmu routines need to translate from a host pointer
2421 (typically a TLB entry) back to a ram offset. */
2422 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2423 {
2424 RAMBlock *block;
2425 ram_addr_t offset;
2426
2427 block = qemu_ram_block_from_host(ptr, false, &offset);
2428 if (!block) {
2429 return RAM_ADDR_INVALID;
2430 }
2431
2432 return block->offset + offset;
2433 }
2434
2435 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2436 MemTxAttrs attrs, void *buf, hwaddr len);
2437 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2438 const void *buf, hwaddr len);
2439 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2440 bool is_write, MemTxAttrs attrs);
2441
2442 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2443 unsigned len, MemTxAttrs attrs)
2444 {
2445 subpage_t *subpage = opaque;
2446 uint8_t buf[8];
2447 MemTxResult res;
2448
2449 #if defined(DEBUG_SUBPAGE)
2450 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2451 subpage, len, addr);
2452 #endif
2453 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2454 if (res) {
2455 return res;
2456 }
2457 *data = ldn_p(buf, len);
2458 return MEMTX_OK;
2459 }
2460
2461 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2462 uint64_t value, unsigned len, MemTxAttrs attrs)
2463 {
2464 subpage_t *subpage = opaque;
2465 uint8_t buf[8];
2466
2467 #if defined(DEBUG_SUBPAGE)
2468 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2469 " value %"PRIx64"\n",
2470 __func__, subpage, len, addr, value);
2471 #endif
2472 stn_p(buf, len, value);
2473 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2474 }
2475
2476 static bool subpage_accepts(void *opaque, hwaddr addr,
2477 unsigned len, bool is_write,
2478 MemTxAttrs attrs)
2479 {
2480 subpage_t *subpage = opaque;
2481 #if defined(DEBUG_SUBPAGE)
2482 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2483 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2484 #endif
2485
2486 return flatview_access_valid(subpage->fv, addr + subpage->base,
2487 len, is_write, attrs);
2488 }
2489
2490 static const MemoryRegionOps subpage_ops = {
2491 .read_with_attrs = subpage_read,
2492 .write_with_attrs = subpage_write,
2493 .impl.min_access_size = 1,
2494 .impl.max_access_size = 8,
2495 .valid.min_access_size = 1,
2496 .valid.max_access_size = 8,
2497 .valid.accepts = subpage_accepts,
2498 .endianness = DEVICE_NATIVE_ENDIAN,
2499 };
2500
2501 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2502 uint16_t section)
2503 {
2504 int idx, eidx;
2505
2506 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2507 return -1;
2508 idx = SUBPAGE_IDX(start);
2509 eidx = SUBPAGE_IDX(end);
2510 #if defined(DEBUG_SUBPAGE)
2511 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2512 __func__, mmio, start, end, idx, eidx, section);
2513 #endif
2514 for (; idx <= eidx; idx++) {
2515 mmio->sub_section[idx] = section;
2516 }
2517
2518 return 0;
2519 }
2520
2521 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2522 {
2523 subpage_t *mmio;
2524
2525 /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2526 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2527 mmio->fv = fv;
2528 mmio->base = base;
2529 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2530 NULL, TARGET_PAGE_SIZE);
2531 mmio->iomem.subpage = true;
2532 #if defined(DEBUG_SUBPAGE)
2533 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2534 mmio, base, TARGET_PAGE_SIZE);
2535 #endif
2536
2537 return mmio;
2538 }
2539
2540 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2541 {
2542 assert(fv);
2543 MemoryRegionSection section = {
2544 .fv = fv,
2545 .mr = mr,
2546 .offset_within_address_space = 0,
2547 .offset_within_region = 0,
2548 .size = int128_2_64(),
2549 };
2550
2551 return phys_section_add(map, &section);
2552 }
2553
2554 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2555 hwaddr index, MemTxAttrs attrs)
2556 {
2557 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2558 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2559 AddressSpaceDispatch *d = qatomic_rcu_read(&cpuas->memory_dispatch);
2560 MemoryRegionSection *sections = d->map.sections;
2561
2562 return &sections[index & ~TARGET_PAGE_MASK];
2563 }
2564
2565 static void io_mem_init(void)
2566 {
2567 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2568 NULL, UINT64_MAX);
2569 }
2570
2571 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2572 {
2573 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2574 uint16_t n;
2575
2576 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2577 assert(n == PHYS_SECTION_UNASSIGNED);
2578
2579 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2580
2581 return d;
2582 }
2583
2584 void address_space_dispatch_free(AddressSpaceDispatch *d)
2585 {
2586 phys_sections_free(&d->map);
2587 g_free(d);
2588 }
2589
2590 static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2591 {
2592 }
2593
2594 static void tcg_log_global_after_sync(MemoryListener *listener)
2595 {
2596 CPUAddressSpace *cpuas;
2597
2598 /* Wait for the CPU to end the current TB. This avoids the following
2599 * incorrect race:
2600 *
2601 * vCPU migration
2602 * ---------------------- -------------------------
2603 * TLB check -> slow path
2604 * notdirty_mem_write
2605 * write to RAM
2606 * mark dirty
2607 * clear dirty flag
2608 * TLB check -> fast path
2609 * read memory
2610 * write to RAM
2611 *
2612 * by pushing the migration thread's memory read after the vCPU thread has
2613 * written the memory.
2614 */
2615 if (replay_mode == REPLAY_MODE_NONE) {
2616 /*
2617 * VGA can make calls to this function while updating the screen.
2618 * In record/replay mode this causes a deadlock, because
2619 * run_on_cpu waits for rr mutex. Therefore no races are possible
2620 * in this case and no need for making run_on_cpu when
2621 * record/replay is not enabled.
2622 */
2623 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2624 run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2625 }
2626 }
2627
2628 static void tcg_commit(MemoryListener *listener)
2629 {
2630 CPUAddressSpace *cpuas;
2631 AddressSpaceDispatch *d;
2632
2633 assert(tcg_enabled());
2634 /* since each CPU stores ram addresses in its TLB cache, we must
2635 reset the modified entries */
2636 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2637 cpu_reloading_memory_map();
2638 /* The CPU and TLB are protected by the iothread lock.
2639 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2640 * may have split the RCU critical section.
2641 */
2642 d = address_space_to_dispatch(cpuas->as);
2643 qatomic_rcu_set(&cpuas->memory_dispatch, d);
2644 tlb_flush(cpuas->cpu);
2645 }
2646
2647 static void memory_map_init(void)
2648 {
2649 system_memory = g_malloc(sizeof(*system_memory));
2650
2651 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2652 address_space_init(&address_space_memory, system_memory, "memory");
2653
2654 system_io = g_malloc(sizeof(*system_io));
2655 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2656 65536);
2657 address_space_init(&address_space_io, system_io, "I/O");
2658 }
2659
2660 MemoryRegion *get_system_memory(void)
2661 {
2662 return system_memory;
2663 }
2664
2665 MemoryRegion *get_system_io(void)
2666 {
2667 return system_io;
2668 }
2669
2670 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2671 hwaddr length)
2672 {
2673 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2674 addr += memory_region_get_ram_addr(mr);
2675
2676 /* No early return if dirty_log_mask is or becomes 0, because
2677 * cpu_physical_memory_set_dirty_range will still call
2678 * xen_modified_memory.
2679 */
2680 if (dirty_log_mask) {
2681 dirty_log_mask =
2682 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2683 }
2684 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2685 assert(tcg_enabled());
2686 tb_invalidate_phys_range(addr, addr + length);
2687 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2688 }
2689 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2690 }
2691
2692 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
2693 {
2694 /*
2695 * In principle this function would work on other memory region types too,
2696 * but the ROM device use case is the only one where this operation is
2697 * necessary. Other memory regions should use the
2698 * address_space_read/write() APIs.
2699 */
2700 assert(memory_region_is_romd(mr));
2701
2702 invalidate_and_set_dirty(mr, addr, size);
2703 }
2704
2705 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2706 {
2707 unsigned access_size_max = mr->ops->valid.max_access_size;
2708
2709 /* Regions are assumed to support 1-4 byte accesses unless
2710 otherwise specified. */
2711 if (access_size_max == 0) {
2712 access_size_max = 4;
2713 }
2714
2715 /* Bound the maximum access by the alignment of the address. */
2716 if (!mr->ops->impl.unaligned) {
2717 unsigned align_size_max = addr & -addr;
2718 if (align_size_max != 0 && align_size_max < access_size_max) {
2719 access_size_max = align_size_max;
2720 }
2721 }
2722
2723 /* Don't attempt accesses larger than the maximum. */
2724 if (l > access_size_max) {
2725 l = access_size_max;
2726 }
2727 l = pow2floor(l);
2728
2729 return l;
2730 }
2731
2732 static bool prepare_mmio_access(MemoryRegion *mr)
2733 {
2734 bool release_lock = false;
2735
2736 if (!qemu_mutex_iothread_locked()) {
2737 qemu_mutex_lock_iothread();
2738 release_lock = true;
2739 }
2740 if (mr->flush_coalesced_mmio) {
2741 qemu_flush_coalesced_mmio_buffer();
2742 }
2743
2744 return release_lock;
2745 }
2746
2747 /* Called within RCU critical section. */
2748 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
2749 MemTxAttrs attrs,
2750 const void *ptr,
2751 hwaddr len, hwaddr addr1,
2752 hwaddr l, MemoryRegion *mr)
2753 {
2754 uint8_t *ram_ptr;
2755 uint64_t val;
2756 MemTxResult result = MEMTX_OK;
2757 bool release_lock = false;
2758 const uint8_t *buf = ptr;
2759
2760 for (;;) {
2761 if (!memory_access_is_direct(mr, true)) {
2762 release_lock |= prepare_mmio_access(mr);
2763 l = memory_access_size(mr, l, addr1);
2764 /* XXX: could force current_cpu to NULL to avoid
2765 potential bugs */
2766 val = ldn_he_p(buf, l);
2767 result |= memory_region_dispatch_write(mr, addr1, val,
2768 size_memop(l), attrs);
2769 } else {
2770 /* RAM case */
2771 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2772 memcpy(ram_ptr, buf, l);
2773 invalidate_and_set_dirty(mr, addr1, l);
2774 }
2775
2776 if (release_lock) {
2777 qemu_mutex_unlock_iothread();
2778 release_lock = false;
2779 }
2780
2781 len -= l;
2782 buf += l;
2783 addr += l;
2784
2785 if (!len) {
2786 break;
2787 }
2788
2789 l = len;
2790 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2791 }
2792
2793 return result;
2794 }
2795
2796 /* Called from RCU critical section. */
2797 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2798 const void *buf, hwaddr len)
2799 {
2800 hwaddr l;
2801 hwaddr addr1;
2802 MemoryRegion *mr;
2803 MemTxResult result = MEMTX_OK;
2804
2805 l = len;
2806 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2807 result = flatview_write_continue(fv, addr, attrs, buf, len,
2808 addr1, l, mr);
2809
2810 return result;
2811 }
2812
2813 /* Called within RCU critical section. */
2814 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
2815 MemTxAttrs attrs, void *ptr,
2816 hwaddr len, hwaddr addr1, hwaddr l,
2817 MemoryRegion *mr)
2818 {
2819 uint8_t *ram_ptr;
2820 uint64_t val;
2821 MemTxResult result = MEMTX_OK;
2822 bool release_lock = false;
2823 uint8_t *buf = ptr;
2824
2825 fuzz_dma_read_cb(addr, len, mr);
2826 for (;;) {
2827 if (!memory_access_is_direct(mr, false)) {
2828 /* I/O case */
2829 release_lock |= prepare_mmio_access(mr);
2830 l = memory_access_size(mr, l, addr1);
2831 result |= memory_region_dispatch_read(mr, addr1, &val,
2832 size_memop(l), attrs);
2833 stn_he_p(buf, l, val);
2834 } else {
2835 /* RAM case */
2836 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2837 memcpy(buf, ram_ptr, l);
2838 }
2839
2840 if (release_lock) {
2841 qemu_mutex_unlock_iothread();
2842 release_lock = false;
2843 }
2844
2845 len -= l;
2846 buf += l;
2847 addr += l;
2848
2849 if (!len) {
2850 break;
2851 }
2852
2853 l = len;
2854 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2855 }
2856
2857 return result;
2858 }
2859
2860 /* Called from RCU critical section. */
2861 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2862 MemTxAttrs attrs, void *buf, hwaddr len)
2863 {
2864 hwaddr l;
2865 hwaddr addr1;
2866 MemoryRegion *mr;
2867
2868 l = len;
2869 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2870 return flatview_read_continue(fv, addr, attrs, buf, len,
2871 addr1, l, mr);
2872 }
2873
2874 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2875 MemTxAttrs attrs, void *buf, hwaddr len)
2876 {
2877 MemTxResult result = MEMTX_OK;
2878 FlatView *fv;
2879
2880 if (len > 0) {
2881 RCU_READ_LOCK_GUARD();
2882 fv = address_space_to_flatview(as);
2883 result = flatview_read(fv, addr, attrs, buf, len);
2884 }
2885
2886 return result;
2887 }
2888
2889 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2890 MemTxAttrs attrs,
2891 const void *buf, hwaddr len)
2892 {
2893 MemTxResult result = MEMTX_OK;
2894 FlatView *fv;
2895
2896 if (len > 0) {
2897 RCU_READ_LOCK_GUARD();
2898 fv = address_space_to_flatview(as);
2899 result = flatview_write(fv, addr, attrs, buf, len);
2900 }
2901
2902 return result;
2903 }
2904
2905 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2906 void *buf, hwaddr len, bool is_write)
2907 {
2908 if (is_write) {
2909 return address_space_write(as, addr, attrs, buf, len);
2910 } else {
2911 return address_space_read_full(as, addr, attrs, buf, len);
2912 }
2913 }
2914
2915 void cpu_physical_memory_rw(hwaddr addr, void *buf,
2916 hwaddr len, bool is_write)
2917 {
2918 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
2919 buf, len, is_write);
2920 }
2921
2922 enum write_rom_type {
2923 WRITE_DATA,
2924 FLUSH_CACHE,
2925 };
2926
2927 static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
2928 hwaddr addr,
2929 MemTxAttrs attrs,
2930 const void *ptr,
2931 hwaddr len,
2932 enum write_rom_type type)
2933 {
2934 hwaddr l;
2935 uint8_t *ram_ptr;
2936 hwaddr addr1;
2937 MemoryRegion *mr;
2938 const uint8_t *buf = ptr;
2939
2940 RCU_READ_LOCK_GUARD();
2941 while (len > 0) {
2942 l = len;
2943 mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
2944
2945 if (!(memory_region_is_ram(mr) ||
2946 memory_region_is_romd(mr))) {
2947 l = memory_access_size(mr, l, addr1);
2948 } else {
2949 /* ROM/RAM case */
2950 ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2951 switch (type) {
2952 case WRITE_DATA:
2953 memcpy(ram_ptr, buf, l);
2954 invalidate_and_set_dirty(mr, addr1, l);
2955 break;
2956 case FLUSH_CACHE:
2957 flush_idcache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr, l);
2958 break;
2959 }
2960 }
2961 len -= l;
2962 buf += l;
2963 addr += l;
2964 }
2965 return MEMTX_OK;
2966 }
2967
2968 /* used for ROM loading : can write in RAM and ROM */
2969 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
2970 MemTxAttrs attrs,
2971 const void *buf, hwaddr len)
2972 {
2973 return address_space_write_rom_internal(as, addr, attrs,
2974 buf, len, WRITE_DATA);
2975 }
2976
2977 void cpu_flush_icache_range(hwaddr start, hwaddr len)
2978 {
2979 /*
2980 * This function should do the same thing as an icache flush that was
2981 * triggered from within the guest. For TCG we are always cache coherent,
2982 * so there is no need to flush anything. For KVM / Xen we need to flush
2983 * the host's instruction cache at least.
2984 */
2985 if (tcg_enabled()) {
2986 return;
2987 }
2988
2989 address_space_write_rom_internal(&address_space_memory,
2990 start, MEMTXATTRS_UNSPECIFIED,
2991 NULL, len, FLUSH_CACHE);
2992 }
2993
2994 typedef struct {
2995 MemoryRegion *mr;
2996 void *buffer;
2997 hwaddr addr;
2998 hwaddr len;
2999 bool in_use;
3000 } BounceBuffer;
3001
3002 static BounceBuffer bounce;
3003
3004 typedef struct MapClient {
3005 QEMUBH *bh;
3006 QLIST_ENTRY(MapClient) link;
3007 } MapClient;
3008
3009 QemuMutex map_client_list_lock;
3010 static QLIST_HEAD(, MapClient) map_client_list
3011 = QLIST_HEAD_INITIALIZER(map_client_list);
3012
3013 static void cpu_unregister_map_client_do(MapClient *client)
3014 {
3015 QLIST_REMOVE(client, link);
3016 g_free(client);
3017 }
3018
3019 static void cpu_notify_map_clients_locked(void)
3020 {
3021 MapClient *client;
3022
3023 while (!QLIST_EMPTY(&map_client_list)) {
3024 client = QLIST_FIRST(&map_client_list);
3025 qemu_bh_schedule(client->bh);
3026 cpu_unregister_map_client_do(client);
3027 }
3028 }
3029
3030 void cpu_register_map_client(QEMUBH *bh)
3031 {
3032 MapClient *client = g_malloc(sizeof(*client));
3033
3034 qemu_mutex_lock(&map_client_list_lock);
3035 client->bh = bh;
3036 QLIST_INSERT_HEAD(&map_client_list, client, link);
3037 if (!qatomic_read(&bounce.in_use)) {
3038 cpu_notify_map_clients_locked();
3039 }
3040 qemu_mutex_unlock(&map_client_list_lock);
3041 }
3042
3043 void cpu_exec_init_all(void)
3044 {
3045 qemu_mutex_init(&ram_list.mutex);
3046 /* The data structures we set up here depend on knowing the page size,
3047 * so no more changes can be made after this point.
3048 * In an ideal world, nothing we did before we had finished the
3049 * machine setup would care about the target page size, and we could
3050 * do this much later, rather than requiring board models to state
3051 * up front what their requirements are.
3052 */
3053 finalize_target_page_bits();
3054 io_mem_init();
3055 memory_map_init();
3056 qemu_mutex_init(&map_client_list_lock);
3057 }
3058
3059 void cpu_unregister_map_client(QEMUBH *bh)
3060 {
3061 MapClient *client;
3062
3063 qemu_mutex_lock(&map_client_list_lock);
3064 QLIST_FOREACH(client, &map_client_list, link) {
3065 if (client->bh == bh) {
3066 cpu_unregister_map_client_do(client);
3067 break;
3068 }
3069 }
3070 qemu_mutex_unlock(&map_client_list_lock);
3071 }
3072
3073 static void cpu_notify_map_clients(void)
3074 {
3075 qemu_mutex_lock(&map_client_list_lock);
3076 cpu_notify_map_clients_locked();
3077 qemu_mutex_unlock(&map_client_list_lock);
3078 }
3079
3080 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
3081 bool is_write, MemTxAttrs attrs)
3082 {
3083 MemoryRegion *mr;
3084 hwaddr l, xlat;
3085
3086 while (len > 0) {
3087 l = len;
3088 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3089 if (!memory_access_is_direct(mr, is_write)) {
3090 l = memory_access_size(mr, l, addr);
3091 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3092 return false;
3093 }
3094 }
3095
3096 len -= l;
3097 addr += l;
3098 }
3099 return true;
3100 }
3101
3102 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3103 hwaddr len, bool is_write,
3104 MemTxAttrs attrs)
3105 {
3106 FlatView *fv;
3107 bool result;
3108
3109 RCU_READ_LOCK_GUARD();
3110 fv = address_space_to_flatview(as);
3111 result = flatview_access_valid(fv, addr, len, is_write, attrs);
3112 return result;
3113 }
3114
3115 static hwaddr
3116 flatview_extend_translation(FlatView *fv, hwaddr addr,
3117 hwaddr target_len,
3118 MemoryRegion *mr, hwaddr base, hwaddr len,
3119 bool is_write, MemTxAttrs attrs)
3120 {
3121 hwaddr done = 0;
3122 hwaddr xlat;
3123 MemoryRegion *this_mr;
3124
3125 for (;;) {
3126 target_len -= len;
3127 addr += len;
3128 done += len;
3129 if (target_len == 0) {
3130 return done;
3131 }
3132
3133 len = target_len;
3134 this_mr = flatview_translate(fv, addr, &xlat,
3135 &len, is_write, attrs);
3136 if (this_mr != mr || xlat != base + done) {
3137 return done;
3138 }
3139 }
3140 }
3141
3142 /* Map a physical memory region into a host virtual address.
3143 * May map a subset of the requested range, given by and returned in *plen.
3144 * May return NULL if resources needed to perform the mapping are exhausted.
3145 * Use only for reads OR writes - not for read-modify-write operations.
3146 * Use cpu_register_map_client() to know when retrying the map operation is
3147 * likely to succeed.
3148 */
3149 void *address_space_map(AddressSpace *as,
3150 hwaddr addr,
3151 hwaddr *plen,
3152 bool is_write,
3153 MemTxAttrs attrs)
3154 {
3155 hwaddr len = *plen;
3156 hwaddr l, xlat;
3157 MemoryRegion *mr;
3158 void *ptr;
3159 FlatView *fv;
3160
3161 if (len == 0) {
3162 return NULL;
3163 }
3164
3165 l = len;
3166 RCU_READ_LOCK_GUARD();
3167 fv = address_space_to_flatview(as);
3168 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3169
3170 if (!memory_access_is_direct(mr, is_write)) {
3171 if (qatomic_xchg(&bounce.in_use, true)) {
3172 *plen = 0;
3173 return NULL;
3174 }
3175 /* Avoid unbounded allocations */
3176 l = MIN(l, TARGET_PAGE_SIZE);
3177 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3178 bounce.addr = addr;
3179 bounce.len = l;
3180
3181 memory_region_ref(mr);
3182 bounce.mr = mr;
3183 if (!is_write) {
3184 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3185 bounce.buffer, l);
3186 }
3187
3188 *plen = l;
3189 return bounce.buffer;
3190 }
3191
3192
3193 memory_region_ref(mr);
3194 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3195 l, is_write, attrs);
3196 fuzz_dma_read_cb(addr, *plen, mr);
3197 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3198
3199 return ptr;
3200 }
3201
3202 /* Unmaps a memory region previously mapped by address_space_map().
3203 * Will also mark the memory as dirty if is_write is true. access_len gives
3204 * the amount of memory that was actually read or written by the caller.
3205 */
3206 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3207 bool is_write, hwaddr access_len)
3208 {
3209 if (buffer != bounce.buffer) {
3210 MemoryRegion *mr;
3211 ram_addr_t addr1;
3212
3213 mr = memory_region_from_host(buffer, &addr1);
3214 assert(mr != NULL);
3215 if (is_write) {
3216 invalidate_and_set_dirty(mr, addr1, access_len);
3217 }
3218 if (xen_enabled()) {
3219 xen_invalidate_map_cache_entry(buffer);
3220 }
3221 memory_region_unref(mr);
3222 return;
3223 }
3224 if (is_write) {
3225 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3226 bounce.buffer, access_len);
3227 }
3228 qemu_vfree(bounce.buffer);
3229 bounce.buffer = NULL;
3230 memory_region_unref(bounce.mr);
3231 qatomic_mb_set(&bounce.in_use, false);
3232 cpu_notify_map_clients();
3233 }
3234
3235 void *cpu_physical_memory_map(hwaddr addr,
3236 hwaddr *plen,
3237 bool is_write)
3238 {
3239 return address_space_map(&address_space_memory, addr, plen, is_write,
3240 MEMTXATTRS_UNSPECIFIED);
3241 }
3242
3243 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3244 bool is_write, hwaddr access_len)
3245 {
3246 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3247 }
3248
3249 #define ARG1_DECL AddressSpace *as
3250 #define ARG1 as
3251 #define SUFFIX
3252 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3253 #define RCU_READ_LOCK(...) rcu_read_lock()
3254 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3255 #include "memory_ldst.c.inc"
3256
3257 int64_t address_space_cache_init(MemoryRegionCache *cache,
3258 AddressSpace *as,
3259 hwaddr addr,
3260 hwaddr len,
3261 bool is_write)
3262 {
3263 AddressSpaceDispatch *d;
3264 hwaddr l;
3265 MemoryRegion *mr;
3266 Int128 diff;
3267
3268 assert(len > 0);
3269
3270 l = len;
3271 cache->fv = address_space_get_flatview(as);
3272 d = flatview_to_dispatch(cache->fv);
3273 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3274
3275 /*
3276 * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3277 * Take that into account to compute how many bytes are there between
3278 * cache->xlat and the end of the section.
3279 */
3280 diff = int128_sub(cache->mrs.size,
3281 int128_make64(cache->xlat - cache->mrs.offset_within_region));
3282 l = int128_get64(int128_min(diff, int128_make64(l)));
3283
3284 mr = cache->mrs.mr;
3285 memory_region_ref(mr);
3286 if (memory_access_is_direct(mr, is_write)) {
3287 /* We don't care about the memory attributes here as we're only
3288 * doing this if we found actual RAM, which behaves the same
3289 * regardless of attributes; so UNSPECIFIED is fine.
3290 */
3291 l = flatview_extend_translation(cache->fv, addr, len, mr,
3292 cache->xlat, l, is_write,
3293 MEMTXATTRS_UNSPECIFIED);
3294 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3295 } else {
3296 cache->ptr = NULL;
3297 }
3298
3299 cache->len = l;
3300 cache->is_write = is_write;
3301 return l;
3302 }
3303
3304 void address_space_cache_invalidate(MemoryRegionCache *cache,
3305 hwaddr addr,
3306 hwaddr access_len)
3307 {
3308 assert(cache->is_write);
3309 if (likely(cache->ptr)) {
3310 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3311 }
3312 }
3313
3314 void address_space_cache_destroy(MemoryRegionCache *cache)
3315 {
3316 if (!cache->mrs.mr) {
3317 return;
3318 }
3319
3320 if (xen_enabled()) {
3321 xen_invalidate_map_cache_entry(cache->ptr);
3322 }
3323 memory_region_unref(cache->mrs.mr);
3324 flatview_unref(cache->fv);
3325 cache->mrs.mr = NULL;
3326 cache->fv = NULL;
3327 }
3328
3329 /* Called from RCU critical section. This function has the same
3330 * semantics as address_space_translate, but it only works on a
3331 * predefined range of a MemoryRegion that was mapped with
3332 * address_space_cache_init.
3333 */
3334 static inline MemoryRegion *address_space_translate_cached(
3335 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3336 hwaddr *plen, bool is_write, MemTxAttrs attrs)
3337 {
3338 MemoryRegionSection section;
3339 MemoryRegion *mr;
3340 IOMMUMemoryRegion *iommu_mr;
3341 AddressSpace *target_as;
3342
3343 assert(!cache->ptr);
3344 *xlat = addr + cache->xlat;
3345
3346 mr = cache->mrs.mr;
3347 iommu_mr = memory_region_get_iommu(mr);
3348 if (!iommu_mr) {
3349 /* MMIO region. */
3350 return mr;
3351 }
3352
3353 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3354 NULL, is_write, true,
3355 &target_as, attrs);
3356 return section.mr;
3357 }
3358
3359 /* Called from RCU critical section. address_space_read_cached uses this
3360 * out of line function when the target is an MMIO or IOMMU region.
3361 */
3362 MemTxResult
3363 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3364 void *buf, hwaddr len)
3365 {
3366 hwaddr addr1, l;
3367 MemoryRegion *mr;
3368
3369 l = len;
3370 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3371 MEMTXATTRS_UNSPECIFIED);
3372 return flatview_read_continue(cache->fv,
3373 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3374 addr1, l, mr);
3375 }
3376
3377 /* Called from RCU critical section. address_space_write_cached uses this
3378 * out of line function when the target is an MMIO or IOMMU region.
3379 */
3380 MemTxResult
3381 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3382 const void *buf, hwaddr len)
3383 {
3384 hwaddr addr1, l;
3385 MemoryRegion *mr;
3386
3387 l = len;
3388 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3389 MEMTXATTRS_UNSPECIFIED);
3390 return flatview_write_continue(cache->fv,
3391 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3392 addr1, l, mr);
3393 }
3394
3395 #define ARG1_DECL MemoryRegionCache *cache
3396 #define ARG1 cache
3397 #define SUFFIX _cached_slow
3398 #define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3399 #define RCU_READ_LOCK() ((void)0)
3400 #define RCU_READ_UNLOCK() ((void)0)
3401 #include "memory_ldst.c.inc"
3402
3403 /* virtual memory access for debug (includes writing to ROM) */
3404 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3405 void *ptr, target_ulong len, bool is_write)
3406 {
3407 hwaddr phys_addr;
3408 target_ulong l, page;
3409 uint8_t *buf = ptr;
3410
3411 cpu_synchronize_state(cpu);
3412 while (len > 0) {
3413 int asidx;
3414 MemTxAttrs attrs;
3415 MemTxResult res;
3416
3417 page = addr & TARGET_PAGE_MASK;
3418 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3419 asidx = cpu_asidx_from_attrs(cpu, attrs);
3420 /* if no physical page mapped, return an error */
3421 if (phys_addr == -1)
3422 return -1;
3423 l = (page + TARGET_PAGE_SIZE) - addr;
3424 if (l > len)
3425 l = len;
3426 phys_addr += (addr & ~TARGET_PAGE_MASK);
3427 if (is_write) {
3428 res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3429 attrs, buf, l);
3430 } else {
3431 res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3432 attrs, buf, l);
3433 }
3434 if (res != MEMTX_OK) {
3435 return -1;
3436 }
3437 len -= l;
3438 buf += l;
3439 addr += l;
3440 }
3441 return 0;
3442 }
3443
3444 /*
3445 * Allows code that needs to deal with migration bitmaps etc to still be built
3446 * target independent.
3447 */
3448 size_t qemu_target_page_size(void)
3449 {
3450 return TARGET_PAGE_SIZE;
3451 }
3452
3453 int qemu_target_page_bits(void)
3454 {
3455 return TARGET_PAGE_BITS;
3456 }
3457
3458 int qemu_target_page_bits_min(void)
3459 {
3460 return TARGET_PAGE_BITS_MIN;
3461 }
3462
3463 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3464 {
3465 MemoryRegion*mr;
3466 hwaddr l = 1;
3467 bool res;
3468
3469 RCU_READ_LOCK_GUARD();
3470 mr = address_space_translate(&address_space_memory,
3471 phys_addr, &phys_addr, &l, false,
3472 MEMTXATTRS_UNSPECIFIED);
3473
3474 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3475 return res;
3476 }
3477
3478 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3479 {
3480 RAMBlock *block;
3481 int ret = 0;
3482
3483 RCU_READ_LOCK_GUARD();
3484 RAMBLOCK_FOREACH(block) {
3485 ret = func(block, opaque);
3486 if (ret) {
3487 break;
3488 }
3489 }
3490 return ret;
3491 }
3492
3493 /*
3494 * Unmap pages of memory from start to start+length such that
3495 * they a) read as 0, b) Trigger whatever fault mechanism
3496 * the OS provides for postcopy.
3497 * The pages must be unmapped by the end of the function.
3498 * Returns: 0 on success, none-0 on failure
3499 *
3500 */
3501 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3502 {
3503 int ret = -1;
3504
3505 uint8_t *host_startaddr = rb->host + start;
3506
3507 if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
3508 error_report("ram_block_discard_range: Unaligned start address: %p",
3509 host_startaddr);
3510 goto err;
3511 }
3512
3513 if ((start + length) <= rb->max_length) {
3514 bool need_madvise, need_fallocate;
3515 if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
3516 error_report("ram_block_discard_range: Unaligned length: %zx",
3517 length);
3518 goto err;
3519 }
3520
3521 errno = ENOTSUP; /* If we are missing MADVISE etc */
3522
3523 /* The logic here is messy;
3524 * madvise DONTNEED fails for hugepages
3525 * fallocate works on hugepages and shmem
3526 */
3527 need_madvise = (rb->page_size == qemu_host_page_size);
3528 need_fallocate = rb->fd != -1;
3529 if (need_fallocate) {
3530 /* For a file, this causes the area of the file to be zero'd
3531 * if read, and for hugetlbfs also causes it to be unmapped
3532 * so a userfault will trigger.
3533 */
3534 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3535 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3536 start, length);
3537 if (ret) {
3538 ret = -errno;
3539 error_report("ram_block_discard_range: Failed to fallocate "
3540 "%s:%" PRIx64 " +%zx (%d)",
3541 rb->idstr, start, length, ret);
3542 goto err;
3543 }
3544 #else
3545 ret = -ENOSYS;
3546 error_report("ram_block_discard_range: fallocate not available/file"
3547 "%s:%" PRIx64 " +%zx (%d)",
3548 rb->idstr, start, length, ret);
3549 goto err;
3550 #endif
3551 }
3552 if (need_madvise) {
3553 /* For normal RAM this causes it to be unmapped,
3554 * for shared memory it causes the local mapping to disappear
3555 * and to fall back on the file contents (which we just
3556 * fallocate'd away).
3557 */
3558 #if defined(CONFIG_MADVISE)
3559 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3560 if (ret) {
3561 ret = -errno;
3562 error_report("ram_block_discard_range: Failed to discard range "
3563 "%s:%" PRIx64 " +%zx (%d)",
3564 rb->idstr, start, length, ret);
3565 goto err;
3566 }
3567 #else
3568 ret = -ENOSYS;
3569 error_report("ram_block_discard_range: MADVISE not available"
3570 "%s:%" PRIx64 " +%zx (%d)",
3571 rb->idstr, start, length, ret);
3572 goto err;
3573 #endif
3574 }
3575 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3576 need_madvise, need_fallocate, ret);
3577 } else {
3578 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3579 "/%zx/" RAM_ADDR_FMT")",
3580 rb->idstr, start, length, rb->max_length);
3581 }
3582
3583 err:
3584 return ret;
3585 }
3586
3587 bool ramblock_is_pmem(RAMBlock *rb)
3588 {
3589 return rb->flags & RAM_PMEM;
3590 }
3591
3592 static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
3593 {
3594 if (start == end - 1) {
3595 qemu_printf("\t%3d ", start);
3596 } else {
3597 qemu_printf("\t%3d..%-3d ", start, end - 1);
3598 }
3599 qemu_printf(" skip=%d ", skip);
3600 if (ptr == PHYS_MAP_NODE_NIL) {
3601 qemu_printf(" ptr=NIL");
3602 } else if (!skip) {
3603 qemu_printf(" ptr=#%d", ptr);
3604 } else {
3605 qemu_printf(" ptr=[%d]", ptr);
3606 }
3607 qemu_printf("\n");
3608 }
3609
3610 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3611 int128_sub((size), int128_one())) : 0)
3612
3613 void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
3614 {
3615 int i;
3616
3617 qemu_printf(" Dispatch\n");
3618 qemu_printf(" Physical sections\n");
3619
3620 for (i = 0; i < d->map.sections_nb; ++i) {
3621 MemoryRegionSection *s = d->map.sections + i;
3622 const char *names[] = { " [unassigned]", " [not dirty]",
3623 " [ROM]", " [watch]" };
3624
3625 qemu_printf(" #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx
3626 " %s%s%s%s%s",
3627 i,
3628 s->offset_within_address_space,
3629 s->offset_within_address_space + MR_SIZE(s->mr->size),
3630 s->mr->name ? s->mr->name : "(noname)",
3631 i < ARRAY_SIZE(names) ? names[i] : "",
3632 s->mr == root ? " [ROOT]" : "",
3633 s == d->mru_section ? " [MRU]" : "",
3634 s->mr->is_iommu ? " [iommu]" : "");
3635
3636 if (s->mr->alias) {
3637 qemu_printf(" alias=%s", s->mr->alias->name ?
3638 s->mr->alias->name : "noname");
3639 }
3640 qemu_printf("\n");
3641 }
3642
3643 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3644 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3645 for (i = 0; i < d->map.nodes_nb; ++i) {
3646 int j, jprev;
3647 PhysPageEntry prev;
3648 Node *n = d->map.nodes + i;
3649
3650 qemu_printf(" [%d]\n", i);
3651
3652 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3653 PhysPageEntry *pe = *n + j;
3654
3655 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3656 continue;
3657 }
3658
3659 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3660
3661 jprev = j;
3662 prev = *pe;
3663 }
3664
3665 if (jprev != ARRAY_SIZE(*n)) {
3666 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3667 }
3668 }
3669 }
3670
3671 /*
3672 * If positive, discarding RAM is disabled. If negative, discarding RAM is
3673 * required to work and cannot be disabled.
3674 */
3675 static int ram_block_discard_disabled;
3676
3677 int ram_block_discard_disable(bool state)
3678 {
3679 int old;
3680
3681 if (!state) {
3682 qatomic_dec(&ram_block_discard_disabled);
3683 return 0;
3684 }
3685
3686 do {
3687 old = qatomic_read(&ram_block_discard_disabled);
3688 if (old < 0) {
3689 return -EBUSY;
3690 }
3691 } while (qatomic_cmpxchg(&ram_block_discard_disabled,
3692 old, old + 1) != old);
3693 return 0;
3694 }
3695
3696 int ram_block_discard_require(bool state)
3697 {
3698 int old;
3699
3700 if (!state) {
3701 qatomic_inc(&ram_block_discard_disabled);
3702 return 0;
3703 }
3704
3705 do {
3706 old = qatomic_read(&ram_block_discard_disabled);
3707 if (old > 0) {
3708 return -EBUSY;
3709 }
3710 } while (qatomic_cmpxchg(&ram_block_discard_disabled,
3711 old, old - 1) != old);
3712 return 0;
3713 }
3714
3715 bool ram_block_discard_is_disabled(void)
3716 {
3717 return qatomic_read(&ram_block_discard_disabled) > 0;
3718 }
3719
3720 bool ram_block_discard_is_required(void)
3721 {
3722 return qatomic_read(&ram_block_discard_disabled) < 0;
3723 }