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