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