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