xref: /qemu/include/system/memory.h (revision 24c00b754121f3569ea9e68f5f188747cf5b8439)
1 /*
2  * Physical memory management API
3  *
4  * Copyright 2011 Red Hat, Inc. and/or its affiliates
5  *
6  * Authors:
7  *  Avi Kivity <avi@redhat.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
12  */
13 
14 #ifndef SYSTEM_MEMORY_H
15 #define SYSTEM_MEMORY_H
16 
17 #include "exec/cpu-common.h"
18 #include "exec/hwaddr.h"
19 #include "exec/memattrs.h"
20 #include "exec/memop.h"
21 #include "exec/ramlist.h"
22 #include "exec/tswap.h"
23 #include "qemu/bswap.h"
24 #include "qemu/queue.h"
25 #include "qemu/int128.h"
26 #include "qemu/range.h"
27 #include "qemu/notify.h"
28 #include "qom/object.h"
29 #include "qemu/rcu.h"
30 
31 #define RAM_ADDR_INVALID (~(ram_addr_t)0)
32 
33 #define MAX_PHYS_ADDR_SPACE_BITS 62
34 #define MAX_PHYS_ADDR            (((hwaddr)1 << MAX_PHYS_ADDR_SPACE_BITS) - 1)
35 
36 #define TYPE_MEMORY_REGION "memory-region"
37 DECLARE_INSTANCE_CHECKER(MemoryRegion, MEMORY_REGION,
38                          TYPE_MEMORY_REGION)
39 
40 #define TYPE_IOMMU_MEMORY_REGION "iommu-memory-region"
41 typedef struct IOMMUMemoryRegionClass IOMMUMemoryRegionClass;
42 DECLARE_OBJ_CHECKERS(IOMMUMemoryRegion, IOMMUMemoryRegionClass,
43                      IOMMU_MEMORY_REGION, TYPE_IOMMU_MEMORY_REGION)
44 
45 #define TYPE_RAM_DISCARD_MANAGER "ram-discard-manager"
46 typedef struct RamDiscardManagerClass RamDiscardManagerClass;
47 typedef struct RamDiscardManager RamDiscardManager;
48 DECLARE_OBJ_CHECKERS(RamDiscardManager, RamDiscardManagerClass,
49                      RAM_DISCARD_MANAGER, TYPE_RAM_DISCARD_MANAGER);
50 
51 #ifdef CONFIG_FUZZ
52 void fuzz_dma_read_cb(size_t addr,
53                       size_t len,
54                       MemoryRegion *mr);
55 #else
fuzz_dma_read_cb(size_t addr,size_t len,MemoryRegion * mr)56 static inline void fuzz_dma_read_cb(size_t addr,
57                                     size_t len,
58                                     MemoryRegion *mr)
59 {
60     /* Do Nothing */
61 }
62 #endif
63 
64 /* Possible bits for global_dirty_log_{start|stop} */
65 
66 /* Dirty tracking enabled because migration is running */
67 #define GLOBAL_DIRTY_MIGRATION  (1U << 0)
68 
69 /* Dirty tracking enabled because measuring dirty rate */
70 #define GLOBAL_DIRTY_DIRTY_RATE (1U << 1)
71 
72 /* Dirty tracking enabled because dirty limit */
73 #define GLOBAL_DIRTY_LIMIT      (1U << 2)
74 
75 #define GLOBAL_DIRTY_MASK  (0x7)
76 
77 extern unsigned int global_dirty_tracking;
78 
79 typedef struct MemoryRegionOps MemoryRegionOps;
80 
81 struct ReservedRegion {
82     Range range;
83     unsigned type;
84 };
85 
86 /**
87  * struct MemoryRegionSection: describes a fragment of a #MemoryRegion
88  *
89  * @mr: the region, or %NULL if empty
90  * @fv: the flat view of the address space the region is mapped in
91  * @offset_within_region: the beginning of the section, relative to @mr's start
92  * @size: the size of the section; will not exceed @mr's boundaries
93  * @offset_within_address_space: the address of the first byte of the section
94  *     relative to the region's address space
95  * @readonly: writes to this section are ignored
96  * @nonvolatile: this section is non-volatile
97  * @unmergeable: this section should not get merged with adjacent sections
98  */
99 struct MemoryRegionSection {
100     Int128 size;
101     MemoryRegion *mr;
102     FlatView *fv;
103     hwaddr offset_within_region;
104     hwaddr offset_within_address_space;
105     bool readonly;
106     bool nonvolatile;
107     bool unmergeable;
108 };
109 
110 typedef struct IOMMUTLBEntry IOMMUTLBEntry;
111 
112 /* See address_space_translate: bit 0 is read, bit 1 is write.  */
113 typedef enum {
114     IOMMU_NONE = 0,
115     IOMMU_RO   = 1,
116     IOMMU_WO   = 2,
117     IOMMU_RW   = 3,
118 } IOMMUAccessFlags;
119 
120 #define IOMMU_ACCESS_FLAG(r, w) (((r) ? IOMMU_RO : 0) | ((w) ? IOMMU_WO : 0))
121 
122 struct IOMMUTLBEntry {
123     AddressSpace    *target_as;
124     hwaddr           iova;
125     hwaddr           translated_addr;
126     hwaddr           addr_mask;  /* 0xfff = 4k translation */
127     IOMMUAccessFlags perm;
128 };
129 
130 /*
131  * Bitmap for different IOMMUNotifier capabilities. Each notifier can
132  * register with one or multiple IOMMU Notifier capability bit(s).
133  *
134  * Normally there're two use cases for the notifiers:
135  *
136  *   (1) When the device needs accurate synchronizations of the vIOMMU page
137  *       tables, it needs to register with both MAP|UNMAP notifies (which
138  *       is defined as IOMMU_NOTIFIER_IOTLB_EVENTS below).
139  *
140  *       Regarding to accurate synchronization, it's when the notified
141  *       device maintains a shadow page table and must be notified on each
142  *       guest MAP (page table entry creation) and UNMAP (invalidation)
143  *       events (e.g. VFIO). Both notifications must be accurate so that
144  *       the shadow page table is fully in sync with the guest view.
145  *
146  *   (2) When the device doesn't need accurate synchronizations of the
147  *       vIOMMU page tables, it needs to register only with UNMAP or
148  *       DEVIOTLB_UNMAP notifies.
149  *
150  *       It's when the device maintains a cache of IOMMU translations
151  *       (IOTLB) and is able to fill that cache by requesting translations
152  *       from the vIOMMU through a protocol similar to ATS (Address
153  *       Translation Service).
154  *
155  *       Note that in this mode the vIOMMU will not maintain a shadowed
156  *       page table for the address space, and the UNMAP messages can cover
157  *       more than the pages that used to get mapped.  The IOMMU notifiee
158  *       should be able to take care of over-sized invalidations.
159  */
160 typedef enum {
161     IOMMU_NOTIFIER_NONE = 0,
162     /* Notify cache invalidations */
163     IOMMU_NOTIFIER_UNMAP = 0x1,
164     /* Notify entry changes (newly created entries) */
165     IOMMU_NOTIFIER_MAP = 0x2,
166     /* Notify changes on device IOTLB entries */
167     IOMMU_NOTIFIER_DEVIOTLB_UNMAP = 0x04,
168 } IOMMUNotifierFlag;
169 
170 #define IOMMU_NOTIFIER_IOTLB_EVENTS (IOMMU_NOTIFIER_MAP | IOMMU_NOTIFIER_UNMAP)
171 #define IOMMU_NOTIFIER_DEVIOTLB_EVENTS IOMMU_NOTIFIER_DEVIOTLB_UNMAP
172 #define IOMMU_NOTIFIER_ALL (IOMMU_NOTIFIER_IOTLB_EVENTS | \
173                             IOMMU_NOTIFIER_DEVIOTLB_EVENTS)
174 
175 struct IOMMUNotifier;
176 typedef void (*IOMMUNotify)(struct IOMMUNotifier *notifier,
177                             IOMMUTLBEntry *data);
178 
179 struct IOMMUNotifier {
180     IOMMUNotify notify;
181     IOMMUNotifierFlag notifier_flags;
182     /* Notify for address space range start <= addr <= end */
183     hwaddr start;
184     hwaddr end;
185     int iommu_idx;
186     void *opaque;
187     QLIST_ENTRY(IOMMUNotifier) node;
188 };
189 typedef struct IOMMUNotifier IOMMUNotifier;
190 
191 typedef struct IOMMUTLBEvent {
192     IOMMUNotifierFlag type;
193     IOMMUTLBEntry entry;
194 } IOMMUTLBEvent;
195 
196 /* RAM is pre-allocated and passed into qemu_ram_alloc_from_ptr */
197 #define RAM_PREALLOC   (1 << 0)
198 
199 /* RAM is mmap-ed with MAP_SHARED */
200 #define RAM_SHARED     (1 << 1)
201 
202 /* Only a portion of RAM (used_length) is actually used, and migrated.
203  * Resizing RAM while migrating can result in the migration being canceled.
204  */
205 #define RAM_RESIZEABLE (1 << 2)
206 
207 /* UFFDIO_ZEROPAGE is available on this RAMBlock to atomically
208  * zero the page and wake waiting processes.
209  * (Set during postcopy)
210  */
211 #define RAM_UF_ZEROPAGE (1 << 3)
212 
213 /* RAM can be migrated */
214 #define RAM_MIGRATABLE (1 << 4)
215 
216 /* RAM is a persistent kind memory */
217 #define RAM_PMEM (1 << 5)
218 
219 
220 /*
221  * UFFDIO_WRITEPROTECT is used on this RAMBlock to
222  * support 'write-tracking' migration type.
223  * Implies ram_state->ram_wt_enabled.
224  */
225 #define RAM_UF_WRITEPROTECT (1 << 6)
226 
227 /*
228  * RAM is mmap-ed with MAP_NORESERVE. When set, reserving swap space (or huge
229  * pages if applicable) is skipped: will bail out if not supported. When not
230  * set, the OS will do the reservation, if supported for the memory type.
231  */
232 #define RAM_NORESERVE (1 << 7)
233 
234 /* RAM that isn't accessible through normal means. */
235 #define RAM_PROTECTED (1 << 8)
236 
237 /* RAM is an mmap-ed named file */
238 #define RAM_NAMED_FILE (1 << 9)
239 
240 /* RAM is mmap-ed read-only */
241 #define RAM_READONLY (1 << 10)
242 
243 /* RAM FD is opened read-only */
244 #define RAM_READONLY_FD (1 << 11)
245 
246 /* RAM can be private that has kvm guest memfd backend */
247 #define RAM_GUEST_MEMFD   (1 << 12)
248 
249 /*
250  * In RAMBlock creation functions, if MAP_SHARED is 0 in the flags parameter,
251  * the implementation may still create a shared mapping if other conditions
252  * require it.  Callers who specifically want a private mapping, eg objects
253  * specified by the user, must pass RAM_PRIVATE.
254  * After RAMBlock creation, MAP_SHARED in the block's flags indicates whether
255  * the block is shared or private, and MAP_PRIVATE is omitted.
256  */
257 #define RAM_PRIVATE (1 << 13)
258 
iommu_notifier_init(IOMMUNotifier * n,IOMMUNotify fn,IOMMUNotifierFlag flags,hwaddr start,hwaddr end,int iommu_idx)259 static inline void iommu_notifier_init(IOMMUNotifier *n, IOMMUNotify fn,
260                                        IOMMUNotifierFlag flags,
261                                        hwaddr start, hwaddr end,
262                                        int iommu_idx)
263 {
264     n->notify = fn;
265     n->notifier_flags = flags;
266     n->start = start;
267     n->end = end;
268     n->iommu_idx = iommu_idx;
269 }
270 
271 /*
272  * Memory region callbacks
273  */
274 struct MemoryRegionOps {
275     /* Read from the memory region. @addr is relative to @mr; @size is
276      * in bytes. */
277     uint64_t (*read)(void *opaque,
278                      hwaddr addr,
279                      unsigned size);
280     /* Write to the memory region. @addr is relative to @mr; @size is
281      * in bytes. */
282     void (*write)(void *opaque,
283                   hwaddr addr,
284                   uint64_t data,
285                   unsigned size);
286 
287     MemTxResult (*read_with_attrs)(void *opaque,
288                                    hwaddr addr,
289                                    uint64_t *data,
290                                    unsigned size,
291                                    MemTxAttrs attrs);
292     MemTxResult (*write_with_attrs)(void *opaque,
293                                     hwaddr addr,
294                                     uint64_t data,
295                                     unsigned size,
296                                     MemTxAttrs attrs);
297 
298     enum device_endian endianness;
299     /* Guest-visible constraints: */
300     struct {
301         /* If nonzero, specify bounds on access sizes beyond which a machine
302          * check is thrown.
303          */
304         unsigned min_access_size;
305         unsigned max_access_size;
306         /* If true, unaligned accesses are supported.  Otherwise unaligned
307          * accesses throw machine checks.
308          */
309          bool unaligned;
310         /*
311          * If present, and returns #false, the transaction is not accepted
312          * by the device (and results in machine dependent behaviour such
313          * as a machine check exception).
314          */
315         bool (*accepts)(void *opaque, hwaddr addr,
316                         unsigned size, bool is_write,
317                         MemTxAttrs attrs);
318     } valid;
319     /* Internal implementation constraints: */
320     struct {
321         /* If nonzero, specifies the minimum size implemented.  Smaller sizes
322          * will be rounded upwards and a partial result will be returned.
323          */
324         unsigned min_access_size;
325         /* If nonzero, specifies the maximum size implemented.  Larger sizes
326          * will be done as a series of accesses with smaller sizes.
327          */
328         unsigned max_access_size;
329         /* If true, unaligned accesses are supported.  Otherwise all accesses
330          * are converted to (possibly multiple) naturally aligned accesses.
331          */
332         bool unaligned;
333     } impl;
334 };
335 
336 typedef struct MemoryRegionClass {
337     /* private */
338     ObjectClass parent_class;
339 } MemoryRegionClass;
340 
341 
342 enum IOMMUMemoryRegionAttr {
343     IOMMU_ATTR_SPAPR_TCE_FD
344 };
345 
346 /*
347  * IOMMUMemoryRegionClass:
348  *
349  * All IOMMU implementations need to subclass TYPE_IOMMU_MEMORY_REGION
350  * and provide an implementation of at least the @translate method here
351  * to handle requests to the memory region. Other methods are optional.
352  *
353  * The IOMMU implementation must use the IOMMU notifier infrastructure
354  * to report whenever mappings are changed, by calling
355  * memory_region_notify_iommu() (or, if necessary, by calling
356  * memory_region_notify_iommu_one() for each registered notifier).
357  *
358  * Conceptually an IOMMU provides a mapping from input address
359  * to an output TLB entry. If the IOMMU is aware of memory transaction
360  * attributes and the output TLB entry depends on the transaction
361  * attributes, we represent this using IOMMU indexes. Each index
362  * selects a particular translation table that the IOMMU has:
363  *
364  *   @attrs_to_index returns the IOMMU index for a set of transaction attributes
365  *
366  *   @translate takes an input address and an IOMMU index
367  *
368  * and the mapping returned can only depend on the input address and the
369  * IOMMU index.
370  *
371  * Most IOMMUs don't care about the transaction attributes and support
372  * only a single IOMMU index. A more complex IOMMU might have one index
373  * for secure transactions and one for non-secure transactions.
374  */
375 struct IOMMUMemoryRegionClass {
376     /* private: */
377     MemoryRegionClass parent_class;
378 
379     /* public: */
380     /**
381      * @translate:
382      *
383      * Return a TLB entry that contains a given address.
384      *
385      * The IOMMUAccessFlags indicated via @flag are optional and may
386      * be specified as IOMMU_NONE to indicate that the caller needs
387      * the full translation information for both reads and writes. If
388      * the access flags are specified then the IOMMU implementation
389      * may use this as an optimization, to stop doing a page table
390      * walk as soon as it knows that the requested permissions are not
391      * allowed. If IOMMU_NONE is passed then the IOMMU must do the
392      * full page table walk and report the permissions in the returned
393      * IOMMUTLBEntry. (Note that this implies that an IOMMU may not
394      * return different mappings for reads and writes.)
395      *
396      * The returned information remains valid while the caller is
397      * holding the big QEMU lock or is inside an RCU critical section;
398      * if the caller wishes to cache the mapping beyond that it must
399      * register an IOMMU notifier so it can invalidate its cached
400      * information when the IOMMU mapping changes.
401      *
402      * @iommu: the IOMMUMemoryRegion
403      *
404      * @hwaddr: address to be translated within the memory region
405      *
406      * @flag: requested access permission
407      *
408      * @iommu_idx: IOMMU index for the translation
409      */
410     IOMMUTLBEntry (*translate)(IOMMUMemoryRegion *iommu, hwaddr addr,
411                                IOMMUAccessFlags flag, int iommu_idx);
412     /**
413      * @get_min_page_size:
414      *
415      * Returns minimum supported page size in bytes.
416      *
417      * If this method is not provided then the minimum is assumed to
418      * be TARGET_PAGE_SIZE.
419      *
420      * @iommu: the IOMMUMemoryRegion
421      */
422     uint64_t (*get_min_page_size)(IOMMUMemoryRegion *iommu);
423     /**
424      * @notify_flag_changed:
425      *
426      * Called when IOMMU Notifier flag changes (ie when the set of
427      * events which IOMMU users are requesting notification for changes).
428      * Optional method -- need not be provided if the IOMMU does not
429      * need to know exactly which events must be notified.
430      *
431      * @iommu: the IOMMUMemoryRegion
432      *
433      * @old_flags: events which previously needed to be notified
434      *
435      * @new_flags: events which now need to be notified
436      *
437      * Returns 0 on success, or a negative errno; in particular
438      * returns -EINVAL if the new flag bitmap is not supported by the
439      * IOMMU memory region. In case of failure, the error object
440      * must be created
441      */
442     int (*notify_flag_changed)(IOMMUMemoryRegion *iommu,
443                                IOMMUNotifierFlag old_flags,
444                                IOMMUNotifierFlag new_flags,
445                                Error **errp);
446     /**
447      * @replay:
448      *
449      * Called to handle memory_region_iommu_replay().
450      *
451      * The default implementation of memory_region_iommu_replay() is to
452      * call the IOMMU translate method for every page in the address space
453      * with flag == IOMMU_NONE and then call the notifier if translate
454      * returns a valid mapping. If this method is implemented then it
455      * overrides the default behaviour, and must provide the full semantics
456      * of memory_region_iommu_replay(), by calling @notifier for every
457      * translation present in the IOMMU.
458      *
459      * Optional method -- an IOMMU only needs to provide this method
460      * if the default is inefficient or produces undesirable side effects.
461      *
462      * Note: this is not related to record-and-replay functionality.
463      */
464     void (*replay)(IOMMUMemoryRegion *iommu, IOMMUNotifier *notifier);
465 
466     /**
467      * @get_attr:
468      *
469      * Get IOMMU misc attributes. This is an optional method that
470      * can be used to allow users of the IOMMU to get implementation-specific
471      * information. The IOMMU implements this method to handle calls
472      * by IOMMU users to memory_region_iommu_get_attr() by filling in
473      * the arbitrary data pointer for any IOMMUMemoryRegionAttr values that
474      * the IOMMU supports. If the method is unimplemented then
475      * memory_region_iommu_get_attr() will always return -EINVAL.
476      *
477      * @iommu: the IOMMUMemoryRegion
478      *
479      * @attr: attribute being queried
480      *
481      * @data: memory to fill in with the attribute data
482      *
483      * Returns 0 on success, or a negative errno; in particular
484      * returns -EINVAL for unrecognized or unimplemented attribute types.
485      */
486     int (*get_attr)(IOMMUMemoryRegion *iommu, enum IOMMUMemoryRegionAttr attr,
487                     void *data);
488 
489     /**
490      * @attrs_to_index:
491      *
492      * Return the IOMMU index to use for a given set of transaction attributes.
493      *
494      * Optional method: if an IOMMU only supports a single IOMMU index then
495      * the default implementation of memory_region_iommu_attrs_to_index()
496      * will return 0.
497      *
498      * The indexes supported by an IOMMU must be contiguous, starting at 0.
499      *
500      * @iommu: the IOMMUMemoryRegion
501      * @attrs: memory transaction attributes
502      */
503     int (*attrs_to_index)(IOMMUMemoryRegion *iommu, MemTxAttrs attrs);
504 
505     /**
506      * @num_indexes:
507      *
508      * Return the number of IOMMU indexes this IOMMU supports.
509      *
510      * Optional method: if this method is not provided, then
511      * memory_region_iommu_num_indexes() will return 1, indicating that
512      * only a single IOMMU index is supported.
513      *
514      * @iommu: the IOMMUMemoryRegion
515      */
516     int (*num_indexes)(IOMMUMemoryRegion *iommu);
517 };
518 
519 typedef struct RamDiscardListener RamDiscardListener;
520 typedef int (*NotifyRamPopulate)(RamDiscardListener *rdl,
521                                  MemoryRegionSection *section);
522 typedef void (*NotifyRamDiscard)(RamDiscardListener *rdl,
523                                  MemoryRegionSection *section);
524 
525 struct RamDiscardListener {
526     /*
527      * @notify_populate:
528      *
529      * Notification that previously discarded memory is about to get populated.
530      * Listeners are able to object. If any listener objects, already
531      * successfully notified listeners are notified about a discard again.
532      *
533      * @rdl: the #RamDiscardListener getting notified
534      * @section: the #MemoryRegionSection to get populated. The section
535      *           is aligned within the memory region to the minimum granularity
536      *           unless it would exceed the registered section.
537      *
538      * Returns 0 on success. If the notification is rejected by the listener,
539      * an error is returned.
540      */
541     NotifyRamPopulate notify_populate;
542 
543     /*
544      * @notify_discard:
545      *
546      * Notification that previously populated memory was discarded successfully
547      * and listeners should drop all references to such memory and prevent
548      * new population (e.g., unmap).
549      *
550      * @rdl: the #RamDiscardListener getting notified
551      * @section: the #MemoryRegionSection to get populated. The section
552      *           is aligned within the memory region to the minimum granularity
553      *           unless it would exceed the registered section.
554      */
555     NotifyRamDiscard notify_discard;
556 
557     /*
558      * @double_discard_supported:
559      *
560      * The listener suppors getting @notify_discard notifications that span
561      * already discarded parts.
562      */
563     bool double_discard_supported;
564 
565     MemoryRegionSection *section;
566     QLIST_ENTRY(RamDiscardListener) next;
567 };
568 
ram_discard_listener_init(RamDiscardListener * rdl,NotifyRamPopulate populate_fn,NotifyRamDiscard discard_fn,bool double_discard_supported)569 static inline void ram_discard_listener_init(RamDiscardListener *rdl,
570                                              NotifyRamPopulate populate_fn,
571                                              NotifyRamDiscard discard_fn,
572                                              bool double_discard_supported)
573 {
574     rdl->notify_populate = populate_fn;
575     rdl->notify_discard = discard_fn;
576     rdl->double_discard_supported = double_discard_supported;
577 }
578 
579 /**
580  * typedef ReplayRamDiscardState:
581  *
582  * The callback handler for #RamDiscardManagerClass.replay_populated/
583  * #RamDiscardManagerClass.replay_discarded to invoke on populated/discarded
584  * parts.
585  *
586  * @section: the #MemoryRegionSection of populated/discarded part
587  * @opaque: pointer to forward to the callback
588  *
589  * Returns 0 on success, or a negative error if failed.
590  */
591 typedef int (*ReplayRamDiscardState)(MemoryRegionSection *section,
592                                      void *opaque);
593 
594 /*
595  * RamDiscardManagerClass:
596  *
597  * A #RamDiscardManager coordinates which parts of specific RAM #MemoryRegion
598  * regions are currently populated to be used/accessed by the VM, notifying
599  * after parts were discarded (freeing up memory) and before parts will be
600  * populated (consuming memory), to be used/accessed by the VM.
601  *
602  * A #RamDiscardManager can only be set for a RAM #MemoryRegion while the
603  * #MemoryRegion isn't mapped into an address space yet (either directly
604  * or via an alias); it cannot change while the #MemoryRegion is
605  * mapped into an address space.
606  *
607  * The #RamDiscardManager is intended to be used by technologies that are
608  * incompatible with discarding of RAM (e.g., VFIO, which may pin all
609  * memory inside a #MemoryRegion), and require proper coordination to only
610  * map the currently populated parts, to hinder parts that are expected to
611  * remain discarded from silently getting populated and consuming memory.
612  * Technologies that support discarding of RAM don't have to bother and can
613  * simply map the whole #MemoryRegion.
614  *
615  * An example #RamDiscardManager is virtio-mem, which logically (un)plugs
616  * memory within an assigned RAM #MemoryRegion, coordinated with the VM.
617  * Logically unplugging memory consists of discarding RAM. The VM agreed to not
618  * access unplugged (discarded) memory - especially via DMA. virtio-mem will
619  * properly coordinate with listeners before memory is plugged (populated),
620  * and after memory is unplugged (discarded).
621  *
622  * Listeners are called in multiples of the minimum granularity (unless it
623  * would exceed the registered range) and changes are aligned to the minimum
624  * granularity within the #MemoryRegion. Listeners have to prepare for memory
625  * becoming discarded in a different granularity than it was populated and the
626  * other way around.
627  */
628 struct RamDiscardManagerClass {
629     /* private */
630     InterfaceClass parent_class;
631 
632     /* public */
633 
634     /**
635      * @get_min_granularity:
636      *
637      * Get the minimum granularity in which listeners will get notified
638      * about changes within the #MemoryRegion via the #RamDiscardManager.
639      *
640      * @rdm: the #RamDiscardManager
641      * @mr: the #MemoryRegion
642      *
643      * Returns the minimum granularity.
644      */
645     uint64_t (*get_min_granularity)(const RamDiscardManager *rdm,
646                                     const MemoryRegion *mr);
647 
648     /**
649      * @is_populated:
650      *
651      * Check whether the given #MemoryRegionSection is completely populated
652      * (i.e., no parts are currently discarded) via the #RamDiscardManager.
653      * There are no alignment requirements.
654      *
655      * @rdm: the #RamDiscardManager
656      * @section: the #MemoryRegionSection
657      *
658      * Returns whether the given range is completely populated.
659      */
660     bool (*is_populated)(const RamDiscardManager *rdm,
661                          const MemoryRegionSection *section);
662 
663     /**
664      * @replay_populated:
665      *
666      * Call the #ReplayRamDiscardState callback for all populated parts within
667      * the #MemoryRegionSection via the #RamDiscardManager.
668      *
669      * In case any call fails, no further calls are made.
670      *
671      * @rdm: the #RamDiscardManager
672      * @section: the #MemoryRegionSection
673      * @replay_fn: the #ReplayRamDiscardState callback
674      * @opaque: pointer to forward to the callback
675      *
676      * Returns 0 on success, or a negative error if any notification failed.
677      */
678     int (*replay_populated)(const RamDiscardManager *rdm,
679                             MemoryRegionSection *section,
680                             ReplayRamDiscardState replay_fn, void *opaque);
681 
682     /**
683      * @replay_discarded:
684      *
685      * Call the #ReplayRamDiscardState callback for all discarded parts within
686      * the #MemoryRegionSection via the #RamDiscardManager.
687      *
688      * @rdm: the #RamDiscardManager
689      * @section: the #MemoryRegionSection
690      * @replay_fn: the #ReplayRamDiscardState callback
691      * @opaque: pointer to forward to the callback
692      *
693      * Returns 0 on success, or a negative error if any notification failed.
694      */
695     int (*replay_discarded)(const RamDiscardManager *rdm,
696                             MemoryRegionSection *section,
697                             ReplayRamDiscardState replay_fn, void *opaque);
698 
699     /**
700      * @register_listener:
701      *
702      * Register a #RamDiscardListener for the given #MemoryRegionSection and
703      * immediately notify the #RamDiscardListener about all populated parts
704      * within the #MemoryRegionSection via the #RamDiscardManager.
705      *
706      * In case any notification fails, no further notifications are triggered
707      * and an error is logged.
708      *
709      * @rdm: the #RamDiscardManager
710      * @rdl: the #RamDiscardListener
711      * @section: the #MemoryRegionSection
712      */
713     void (*register_listener)(RamDiscardManager *rdm,
714                               RamDiscardListener *rdl,
715                               MemoryRegionSection *section);
716 
717     /**
718      * @unregister_listener:
719      *
720      * Unregister a previously registered #RamDiscardListener via the
721      * #RamDiscardManager after notifying the #RamDiscardListener about all
722      * populated parts becoming unpopulated within the registered
723      * #MemoryRegionSection.
724      *
725      * @rdm: the #RamDiscardManager
726      * @rdl: the #RamDiscardListener
727      */
728     void (*unregister_listener)(RamDiscardManager *rdm,
729                                 RamDiscardListener *rdl);
730 };
731 
732 uint64_t ram_discard_manager_get_min_granularity(const RamDiscardManager *rdm,
733                                                  const MemoryRegion *mr);
734 
735 bool ram_discard_manager_is_populated(const RamDiscardManager *rdm,
736                                       const MemoryRegionSection *section);
737 
738 /**
739  * ram_discard_manager_replay_populated:
740  *
741  * A wrapper to call the #RamDiscardManagerClass.replay_populated callback
742  * of the #RamDiscardManager.
743  *
744  * @rdm: the #RamDiscardManager
745  * @section: the #MemoryRegionSection
746  * @replay_fn: the #ReplayRamDiscardState callback
747  * @opaque: pointer to forward to the callback
748  *
749  * Returns 0 on success, or a negative error if any notification failed.
750  */
751 int ram_discard_manager_replay_populated(const RamDiscardManager *rdm,
752                                          MemoryRegionSection *section,
753                                          ReplayRamDiscardState replay_fn,
754                                          void *opaque);
755 
756 /**
757  * ram_discard_manager_replay_discarded:
758  *
759  * A wrapper to call the #RamDiscardManagerClass.replay_discarded callback
760  * of the #RamDiscardManager.
761  *
762  * @rdm: the #RamDiscardManager
763  * @section: the #MemoryRegionSection
764  * @replay_fn: the #ReplayRamDiscardState callback
765  * @opaque: pointer to forward to the callback
766  *
767  * Returns 0 on success, or a negative error if any notification failed.
768  */
769 int ram_discard_manager_replay_discarded(const RamDiscardManager *rdm,
770                                          MemoryRegionSection *section,
771                                          ReplayRamDiscardState replay_fn,
772                                          void *opaque);
773 
774 void ram_discard_manager_register_listener(RamDiscardManager *rdm,
775                                            RamDiscardListener *rdl,
776                                            MemoryRegionSection *section);
777 
778 void ram_discard_manager_unregister_listener(RamDiscardManager *rdm,
779                                              RamDiscardListener *rdl);
780 
781 /**
782  * memory_translate_iotlb: Extract addresses from a TLB entry.
783  *                         Called with rcu_read_lock held.
784  *
785  * @iotlb: pointer to an #IOMMUTLBEntry
786  * @xlat_p: return the offset of the entry from the start of the returned
787  *          MemoryRegion.
788  * @errp: pointer to Error*, to store an error if it happens.
789  *
790  * Return: On success, return the MemoryRegion containing the @iotlb translated
791  *         addr.  The MemoryRegion must not be accessed after rcu_read_unlock.
792  *         On failure, return NULL, setting @errp with error.
793  */
794 MemoryRegion *memory_translate_iotlb(IOMMUTLBEntry *iotlb, hwaddr *xlat_p,
795                                      Error **errp);
796 
797 typedef struct CoalescedMemoryRange CoalescedMemoryRange;
798 typedef struct MemoryRegionIoeventfd MemoryRegionIoeventfd;
799 
800 /** MemoryRegion:
801  *
802  * A struct representing a memory region.
803  */
804 struct MemoryRegion {
805     Object parent_obj;
806 
807     /* private: */
808 
809     /* The following fields should fit in a cache line */
810     bool romd_mode;
811     bool ram;
812     bool subpage;
813     bool readonly; /* For RAM regions */
814     bool nonvolatile;
815     bool rom_device;
816     bool flush_coalesced_mmio;
817     bool unmergeable;
818     uint8_t dirty_log_mask;
819     bool is_iommu;
820     RAMBlock *ram_block;
821     Object *owner;
822     /* owner as TYPE_DEVICE. Used for re-entrancy checks in MR access hotpath */
823     DeviceState *dev;
824 
825     const MemoryRegionOps *ops;
826     void *opaque;
827     MemoryRegion *container;
828     int mapped_via_alias; /* Mapped via an alias, container might be NULL */
829     Int128 size;
830     hwaddr addr;
831     void (*destructor)(MemoryRegion *mr);
832     uint64_t align;
833     bool terminates;
834     bool ram_device;
835     bool enabled;
836     uint8_t vga_logging_count;
837     MemoryRegion *alias;
838     hwaddr alias_offset;
839     int32_t priority;
840     QTAILQ_HEAD(, MemoryRegion) subregions;
841     QTAILQ_ENTRY(MemoryRegion) subregions_link;
842     QTAILQ_HEAD(, CoalescedMemoryRange) coalesced;
843     const char *name;
844     unsigned ioeventfd_nb;
845     MemoryRegionIoeventfd *ioeventfds;
846     RamDiscardManager *rdm; /* Only for RAM */
847 
848     /* For devices designed to perform re-entrant IO into their own IO MRs */
849     bool disable_reentrancy_guard;
850 };
851 
852 struct IOMMUMemoryRegion {
853     MemoryRegion parent_obj;
854 
855     QLIST_HEAD(, IOMMUNotifier) iommu_notify;
856     IOMMUNotifierFlag iommu_notify_flags;
857 };
858 
859 #define IOMMU_NOTIFIER_FOREACH(n, mr) \
860     QLIST_FOREACH((n), &(mr)->iommu_notify, node)
861 
862 #define MEMORY_LISTENER_PRIORITY_MIN            0
863 #define MEMORY_LISTENER_PRIORITY_ACCEL          10
864 #define MEMORY_LISTENER_PRIORITY_DEV_BACKEND    10
865 
866 /**
867  * struct MemoryListener: callbacks structure for updates to the physical memory map
868  *
869  * Allows a component to adjust to changes in the guest-visible memory map.
870  * Use with memory_listener_register() and memory_listener_unregister().
871  */
872 struct MemoryListener {
873     /**
874      * @begin:
875      *
876      * Called at the beginning of an address space update transaction.
877      * Followed by calls to #MemoryListener.region_add(),
878      * #MemoryListener.region_del(), #MemoryListener.region_nop(),
879      * #MemoryListener.log_start() and #MemoryListener.log_stop() in
880      * increasing address order.
881      *
882      * @listener: The #MemoryListener.
883      */
884     void (*begin)(MemoryListener *listener);
885 
886     /**
887      * @commit:
888      *
889      * Called at the end of an address space update transaction,
890      * after the last call to #MemoryListener.region_add(),
891      * #MemoryListener.region_del() or #MemoryListener.region_nop(),
892      * #MemoryListener.log_start() and #MemoryListener.log_stop().
893      *
894      * @listener: The #MemoryListener.
895      */
896     void (*commit)(MemoryListener *listener);
897 
898     /**
899      * @region_add:
900      *
901      * Called during an address space update transaction,
902      * for a section of the address space that is new in this address space
903      * space since the last transaction.
904      *
905      * @listener: The #MemoryListener.
906      * @section: The new #MemoryRegionSection.
907      */
908     void (*region_add)(MemoryListener *listener, MemoryRegionSection *section);
909 
910     /**
911      * @region_del:
912      *
913      * Called during an address space update transaction,
914      * for a section of the address space that has disappeared in the address
915      * space since the last transaction.
916      *
917      * @listener: The #MemoryListener.
918      * @section: The old #MemoryRegionSection.
919      */
920     void (*region_del)(MemoryListener *listener, MemoryRegionSection *section);
921 
922     /**
923      * @region_nop:
924      *
925      * Called during an address space update transaction,
926      * for a section of the address space that is in the same place in the address
927      * space as in the last transaction.
928      *
929      * @listener: The #MemoryListener.
930      * @section: The #MemoryRegionSection.
931      */
932     void (*region_nop)(MemoryListener *listener, MemoryRegionSection *section);
933 
934     /**
935      * @log_start:
936      *
937      * Called during an address space update transaction, after
938      * one of #MemoryListener.region_add(), #MemoryListener.region_del() or
939      * #MemoryListener.region_nop(), if dirty memory logging clients have
940      * become active since the last transaction.
941      *
942      * @listener: The #MemoryListener.
943      * @section: The #MemoryRegionSection.
944      * @old: A bitmap of dirty memory logging clients that were active in
945      * the previous transaction.
946      * @new: A bitmap of dirty memory logging clients that are active in
947      * the current transaction.
948      */
949     void (*log_start)(MemoryListener *listener, MemoryRegionSection *section,
950                       int old_val, int new_val);
951 
952     /**
953      * @log_stop:
954      *
955      * Called during an address space update transaction, after
956      * one of #MemoryListener.region_add(), #MemoryListener.region_del() or
957      * #MemoryListener.region_nop() and possibly after
958      * #MemoryListener.log_start(), if dirty memory logging clients have
959      * become inactive since the last transaction.
960      *
961      * @listener: The #MemoryListener.
962      * @section: The #MemoryRegionSection.
963      * @old: A bitmap of dirty memory logging clients that were active in
964      * the previous transaction.
965      * @new: A bitmap of dirty memory logging clients that are active in
966      * the current transaction.
967      */
968     void (*log_stop)(MemoryListener *listener, MemoryRegionSection *section,
969                      int old_val, int new_val);
970 
971     /**
972      * @log_sync:
973      *
974      * Called by memory_region_snapshot_and_clear_dirty() and
975      * memory_global_dirty_log_sync(), before accessing QEMU's "official"
976      * copy of the dirty memory bitmap for a #MemoryRegionSection.
977      *
978      * @listener: The #MemoryListener.
979      * @section: The #MemoryRegionSection.
980      */
981     void (*log_sync)(MemoryListener *listener, MemoryRegionSection *section);
982 
983     /**
984      * @log_sync_global:
985      *
986      * This is the global version of @log_sync when the listener does
987      * not have a way to synchronize the log with finer granularity.
988      * When the listener registers with @log_sync_global defined, then
989      * its @log_sync must be NULL.  Vice versa.
990      *
991      * @listener: The #MemoryListener.
992      * @last_stage: The last stage to synchronize the log during migration.
993      * The caller should guarantee that the synchronization with true for
994      * @last_stage is triggered for once after all VCPUs have been stopped.
995      */
996     void (*log_sync_global)(MemoryListener *listener, bool last_stage);
997 
998     /**
999      * @log_clear:
1000      *
1001      * Called before reading the dirty memory bitmap for a
1002      * #MemoryRegionSection.
1003      *
1004      * @listener: The #MemoryListener.
1005      * @section: The #MemoryRegionSection.
1006      */
1007     void (*log_clear)(MemoryListener *listener, MemoryRegionSection *section);
1008 
1009     /**
1010      * @log_global_start:
1011      *
1012      * Called by memory_global_dirty_log_start(), which
1013      * enables the %DIRTY_LOG_MIGRATION client on all memory regions in
1014      * the address space.  #MemoryListener.log_global_start() is also
1015      * called when a #MemoryListener is added, if global dirty logging is
1016      * active at that time.
1017      *
1018      * @listener: The #MemoryListener.
1019      * @errp: pointer to Error*, to store an error if it happens.
1020      *
1021      * Return: true on success, else false setting @errp with error.
1022      */
1023     bool (*log_global_start)(MemoryListener *listener, Error **errp);
1024 
1025     /**
1026      * @log_global_stop:
1027      *
1028      * Called by memory_global_dirty_log_stop(), which
1029      * disables the %DIRTY_LOG_MIGRATION client on all memory regions in
1030      * the address space.
1031      *
1032      * @listener: The #MemoryListener.
1033      */
1034     void (*log_global_stop)(MemoryListener *listener);
1035 
1036     /**
1037      * @log_global_after_sync:
1038      *
1039      * Called after reading the dirty memory bitmap
1040      * for any #MemoryRegionSection.
1041      *
1042      * @listener: The #MemoryListener.
1043      */
1044     void (*log_global_after_sync)(MemoryListener *listener);
1045 
1046     /**
1047      * @eventfd_add:
1048      *
1049      * Called during an address space update transaction,
1050      * for a section of the address space that has had a new ioeventfd
1051      * registration since the last transaction.
1052      *
1053      * @listener: The #MemoryListener.
1054      * @section: The new #MemoryRegionSection.
1055      * @match_data: The @match_data parameter for the new ioeventfd.
1056      * @data: The @data parameter for the new ioeventfd.
1057      * @e: The #EventNotifier parameter for the new ioeventfd.
1058      */
1059     void (*eventfd_add)(MemoryListener *listener, MemoryRegionSection *section,
1060                         bool match_data, uint64_t data, EventNotifier *e);
1061 
1062     /**
1063      * @eventfd_del:
1064      *
1065      * Called during an address space update transaction,
1066      * for a section of the address space that has dropped an ioeventfd
1067      * registration since the last transaction.
1068      *
1069      * @listener: The #MemoryListener.
1070      * @section: The new #MemoryRegionSection.
1071      * @match_data: The @match_data parameter for the dropped ioeventfd.
1072      * @data: The @data parameter for the dropped ioeventfd.
1073      * @e: The #EventNotifier parameter for the dropped ioeventfd.
1074      */
1075     void (*eventfd_del)(MemoryListener *listener, MemoryRegionSection *section,
1076                         bool match_data, uint64_t data, EventNotifier *e);
1077 
1078     /**
1079      * @coalesced_io_add:
1080      *
1081      * Called during an address space update transaction,
1082      * for a section of the address space that has had a new coalesced
1083      * MMIO range registration since the last transaction.
1084      *
1085      * @listener: The #MemoryListener.
1086      * @section: The new #MemoryRegionSection.
1087      * @addr: The starting address for the coalesced MMIO range.
1088      * @len: The length of the coalesced MMIO range.
1089      */
1090     void (*coalesced_io_add)(MemoryListener *listener, MemoryRegionSection *section,
1091                                hwaddr addr, hwaddr len);
1092 
1093     /**
1094      * @coalesced_io_del:
1095      *
1096      * Called during an address space update transaction,
1097      * for a section of the address space that has dropped a coalesced
1098      * MMIO range since the last transaction.
1099      *
1100      * @listener: The #MemoryListener.
1101      * @section: The new #MemoryRegionSection.
1102      * @addr: The starting address for the coalesced MMIO range.
1103      * @len: The length of the coalesced MMIO range.
1104      */
1105     void (*coalesced_io_del)(MemoryListener *listener, MemoryRegionSection *section,
1106                                hwaddr addr, hwaddr len);
1107     /**
1108      * @priority:
1109      *
1110      * Govern the order in which memory listeners are invoked. Lower priorities
1111      * are invoked earlier for "add" or "start" callbacks, and later for "delete"
1112      * or "stop" callbacks.
1113      */
1114     unsigned priority;
1115 
1116     /**
1117      * @name:
1118      *
1119      * Name of the listener.  It can be used in contexts where we'd like to
1120      * identify one memory listener with the rest.
1121      */
1122     const char *name;
1123 
1124     /* private: */
1125     AddressSpace *address_space;
1126     QTAILQ_ENTRY(MemoryListener) link;
1127     QTAILQ_ENTRY(MemoryListener) link_as;
1128 };
1129 
1130 typedef struct AddressSpaceMapClient {
1131     QEMUBH *bh;
1132     QLIST_ENTRY(AddressSpaceMapClient) link;
1133 } AddressSpaceMapClient;
1134 
1135 #define DEFAULT_MAX_BOUNCE_BUFFER_SIZE (4096)
1136 
1137 /**
1138  * struct AddressSpace: describes a mapping of addresses to #MemoryRegion objects
1139  */
1140 struct AddressSpace {
1141     /* private: */
1142     struct rcu_head rcu;
1143     char *name;
1144     MemoryRegion *root;
1145 
1146     /* Accessed via RCU.  */
1147     struct FlatView *current_map;
1148 
1149     int ioeventfd_nb;
1150     int ioeventfd_notifiers;
1151     struct MemoryRegionIoeventfd *ioeventfds;
1152     QTAILQ_HEAD(, MemoryListener) listeners;
1153     QTAILQ_ENTRY(AddressSpace) address_spaces_link;
1154 
1155     /*
1156      * Maximum DMA bounce buffer size used for indirect memory map requests.
1157      * This limits the total size of bounce buffer allocations made for
1158      * DMA requests to indirect memory regions within this AddressSpace. DMA
1159      * requests that exceed the limit (e.g. due to overly large requested size
1160      * or concurrent DMA requests having claimed too much buffer space) will be
1161      * rejected and left to the caller to handle.
1162      */
1163     size_t max_bounce_buffer_size;
1164     /* Total size of bounce buffers currently allocated, atomically accessed */
1165     size_t bounce_buffer_size;
1166     /* List of callbacks to invoke when buffers free up */
1167     QemuMutex map_client_list_lock;
1168     QLIST_HEAD(, AddressSpaceMapClient) map_client_list;
1169 };
1170 
1171 typedef struct AddressSpaceDispatch AddressSpaceDispatch;
1172 typedef struct FlatRange FlatRange;
1173 
1174 /* Flattened global view of current active memory hierarchy.  Kept in sorted
1175  * order.
1176  */
1177 struct FlatView {
1178     struct rcu_head rcu;
1179     unsigned ref;
1180     FlatRange *ranges;
1181     unsigned nr;
1182     unsigned nr_allocated;
1183     struct AddressSpaceDispatch *dispatch;
1184     MemoryRegion *root;
1185 };
1186 
address_space_to_flatview(AddressSpace * as)1187 static inline FlatView *address_space_to_flatview(AddressSpace *as)
1188 {
1189     return qatomic_rcu_read(&as->current_map);
1190 }
1191 
1192 /**
1193  * typedef flatview_cb: callback for flatview_for_each_range()
1194  *
1195  * @start: start address of the range within the FlatView
1196  * @len: length of the range in bytes
1197  * @mr: MemoryRegion covering this range
1198  * @offset_in_region: offset of the first byte of the range within @mr
1199  * @opaque: data pointer passed to flatview_for_each_range()
1200  *
1201  * Returns: true to stop the iteration, false to keep going.
1202  */
1203 typedef bool (*flatview_cb)(Int128 start,
1204                             Int128 len,
1205                             const MemoryRegion *mr,
1206                             hwaddr offset_in_region,
1207                             void *opaque);
1208 
1209 /**
1210  * flatview_for_each_range: Iterate through a FlatView
1211  * @fv: the FlatView to iterate through
1212  * @cb: function to call for each range
1213  * @opaque: opaque data pointer to pass to @cb
1214  *
1215  * A FlatView is made up of a list of non-overlapping ranges, each of
1216  * which is a slice of a MemoryRegion. This function iterates through
1217  * each range in @fv, calling @cb. The callback function can terminate
1218  * iteration early by returning 'true'.
1219  */
1220 void flatview_for_each_range(FlatView *fv, flatview_cb cb, void *opaque);
1221 
MemoryRegionSection_eq(MemoryRegionSection * a,MemoryRegionSection * b)1222 static inline bool MemoryRegionSection_eq(MemoryRegionSection *a,
1223                                           MemoryRegionSection *b)
1224 {
1225     return a->mr == b->mr &&
1226            a->fv == b->fv &&
1227            a->offset_within_region == b->offset_within_region &&
1228            a->offset_within_address_space == b->offset_within_address_space &&
1229            int128_eq(a->size, b->size) &&
1230            a->readonly == b->readonly &&
1231            a->nonvolatile == b->nonvolatile;
1232 }
1233 
1234 /**
1235  * memory_region_section_new_copy: Copy a memory region section
1236  *
1237  * Allocate memory for a new copy, copy the memory region section, and
1238  * properly take a reference on all relevant members.
1239  *
1240  * @s: the #MemoryRegionSection to copy
1241  */
1242 MemoryRegionSection *memory_region_section_new_copy(MemoryRegionSection *s);
1243 
1244 /**
1245  * memory_region_section_free_copy: Free a copied memory region section
1246  *
1247  * Free a copy of a memory section created via memory_region_section_new_copy().
1248  * properly dropping references on all relevant members.
1249  *
1250  * @s: the #MemoryRegionSection to copy
1251  */
1252 void memory_region_section_free_copy(MemoryRegionSection *s);
1253 
1254 /**
1255  * memory_region_section_intersect_range: Adjust the memory section to cover
1256  * the intersection with the given range.
1257  *
1258  * @s: the #MemoryRegionSection to be adjusted
1259  * @offset: the offset of the given range in the memory region
1260  * @size: the size of the given range
1261  *
1262  * Returns false if the intersection is empty, otherwise returns true.
1263  */
memory_region_section_intersect_range(MemoryRegionSection * s,uint64_t offset,uint64_t size)1264 static inline bool memory_region_section_intersect_range(MemoryRegionSection *s,
1265                                                          uint64_t offset,
1266                                                          uint64_t size)
1267 {
1268     uint64_t start = MAX(s->offset_within_region, offset);
1269     Int128 end = int128_min(int128_add(int128_make64(s->offset_within_region),
1270                                        s->size),
1271                             int128_add(int128_make64(offset),
1272                                        int128_make64(size)));
1273 
1274     if (int128_le(end, int128_make64(start))) {
1275         return false;
1276     }
1277 
1278     s->offset_within_address_space += start - s->offset_within_region;
1279     s->offset_within_region = start;
1280     s->size = int128_sub(end, int128_make64(start));
1281     return true;
1282 }
1283 
1284 /**
1285  * memory_region_init: Initialize a memory region
1286  *
1287  * The region typically acts as a container for other memory regions.  Use
1288  * memory_region_add_subregion() to add subregions.
1289  *
1290  * @mr: the #MemoryRegion to be initialized
1291  * @owner: the object that tracks the region's reference count
1292  * @name: used for debugging; not visible to the user or ABI
1293  * @size: size of the region; any subregions beyond this size will be clipped
1294  */
1295 void memory_region_init(MemoryRegion *mr,
1296                         Object *owner,
1297                         const char *name,
1298                         uint64_t size);
1299 
1300 /**
1301  * memory_region_ref: Add 1 to a memory region's reference count
1302  *
1303  * Whenever memory regions are accessed outside the BQL, they need to be
1304  * preserved against hot-unplug.  MemoryRegions actually do not have their
1305  * own reference count; they piggyback on a QOM object, their "owner".
1306  * This function adds a reference to the owner.
1307  *
1308  * All MemoryRegions must have an owner if they can disappear, even if the
1309  * device they belong to operates exclusively under the BQL.  This is because
1310  * the region could be returned at any time by memory_region_find, and this
1311  * is usually under guest control.
1312  *
1313  * @mr: the #MemoryRegion
1314  */
1315 void memory_region_ref(MemoryRegion *mr);
1316 
1317 /**
1318  * memory_region_unref: Remove 1 to a memory region's reference count
1319  *
1320  * Whenever memory regions are accessed outside the BQL, they need to be
1321  * preserved against hot-unplug.  MemoryRegions actually do not have their
1322  * own reference count; they piggyback on a QOM object, their "owner".
1323  * This function removes a reference to the owner and possibly destroys it.
1324  *
1325  * @mr: the #MemoryRegion
1326  */
1327 void memory_region_unref(MemoryRegion *mr);
1328 
1329 /**
1330  * memory_region_init_io: Initialize an I/O memory region.
1331  *
1332  * Accesses into the region will cause the callbacks in @ops to be called.
1333  * if @size is nonzero, subregions will be clipped to @size.
1334  *
1335  * @mr: the #MemoryRegion to be initialized.
1336  * @owner: the object that tracks the region's reference count
1337  * @ops: a structure containing read and write callbacks to be used when
1338  *       I/O is performed on the region.
1339  * @opaque: passed to the read and write callbacks of the @ops structure.
1340  * @name: used for debugging; not visible to the user or ABI
1341  * @size: size of the region.
1342  */
1343 void memory_region_init_io(MemoryRegion *mr,
1344                            Object *owner,
1345                            const MemoryRegionOps *ops,
1346                            void *opaque,
1347                            const char *name,
1348                            uint64_t size);
1349 
1350 /**
1351  * memory_region_init_ram_nomigrate:  Initialize RAM memory region.  Accesses
1352  *                                    into the region will modify memory
1353  *                                    directly.
1354  *
1355  * @mr: the #MemoryRegion to be initialized.
1356  * @owner: the object that tracks the region's reference count
1357  * @name: Region name, becomes part of RAMBlock name used in migration stream
1358  *        must be unique within any device
1359  * @size: size of the region.
1360  * @errp: pointer to Error*, to store an error if it happens.
1361  *
1362  * Note that this function does not do anything to cause the data in the
1363  * RAM memory region to be migrated; that is the responsibility of the caller.
1364  *
1365  * Return: true on success, else false setting @errp with error.
1366  */
1367 bool memory_region_init_ram_nomigrate(MemoryRegion *mr,
1368                                       Object *owner,
1369                                       const char *name,
1370                                       uint64_t size,
1371                                       Error **errp);
1372 
1373 /**
1374  * memory_region_init_ram_flags_nomigrate:  Initialize RAM memory region.
1375  *                                          Accesses into the region will
1376  *                                          modify memory directly.
1377  *
1378  * @mr: the #MemoryRegion to be initialized.
1379  * @owner: the object that tracks the region's reference count
1380  * @name: Region name, becomes part of RAMBlock name used in migration stream
1381  *        must be unique within any device
1382  * @size: size of the region.
1383  * @ram_flags: RamBlock flags. Supported flags: RAM_SHARED, RAM_NORESERVE,
1384  *             RAM_GUEST_MEMFD.
1385  * @errp: pointer to Error*, to store an error if it happens.
1386  *
1387  * Note that this function does not do anything to cause the data in the
1388  * RAM memory region to be migrated; that is the responsibility of the caller.
1389  *
1390  * Return: true on success, else false setting @errp with error.
1391  */
1392 bool memory_region_init_ram_flags_nomigrate(MemoryRegion *mr,
1393                                             Object *owner,
1394                                             const char *name,
1395                                             uint64_t size,
1396                                             uint32_t ram_flags,
1397                                             Error **errp);
1398 
1399 /**
1400  * memory_region_init_resizeable_ram:  Initialize memory region with resizable
1401  *                                     RAM.  Accesses into the region will
1402  *                                     modify memory directly.  Only an initial
1403  *                                     portion of this RAM is actually used.
1404  *                                     Changing the size while migrating
1405  *                                     can result in the migration being
1406  *                                     canceled.
1407  *
1408  * @mr: the #MemoryRegion to be initialized.
1409  * @owner: the object that tracks the region's reference count
1410  * @name: Region name, becomes part of RAMBlock name used in migration stream
1411  *        must be unique within any device
1412  * @size: used size of the region.
1413  * @max_size: max size of the region.
1414  * @resized: callback to notify owner about used size change.
1415  * @errp: pointer to Error*, to store an error if it happens.
1416  *
1417  * Note that this function does not do anything to cause the data in the
1418  * RAM memory region to be migrated; that is the responsibility of the caller.
1419  *
1420  * Return: true on success, else false setting @errp with error.
1421  */
1422 bool memory_region_init_resizeable_ram(MemoryRegion *mr,
1423                                        Object *owner,
1424                                        const char *name,
1425                                        uint64_t size,
1426                                        uint64_t max_size,
1427                                        void (*resized)(const char*,
1428                                                        uint64_t length,
1429                                                        void *host),
1430                                        Error **errp);
1431 #ifdef CONFIG_POSIX
1432 
1433 /**
1434  * memory_region_init_ram_from_file:  Initialize RAM memory region with a
1435  *                                    mmap-ed backend.
1436  *
1437  * @mr: the #MemoryRegion to be initialized.
1438  * @owner: the object that tracks the region's reference count
1439  * @name: Region name, becomes part of RAMBlock name used in migration stream
1440  *        must be unique within any device
1441  * @size: size of the region.
1442  * @align: alignment of the region base address; if 0, the default alignment
1443  *         (getpagesize()) will be used.
1444  * @ram_flags: RamBlock flags. Supported flags: RAM_SHARED, RAM_PMEM,
1445  *             RAM_NORESERVE, RAM_PROTECTED, RAM_NAMED_FILE, RAM_READONLY,
1446  *             RAM_READONLY_FD, RAM_GUEST_MEMFD
1447  * @path: the path in which to allocate the RAM.
1448  * @offset: offset within the file referenced by path
1449  * @errp: pointer to Error*, to store an error if it happens.
1450  *
1451  * Note that this function does not do anything to cause the data in the
1452  * RAM memory region to be migrated; that is the responsibility of the caller.
1453  *
1454  * Return: true on success, else false setting @errp with error.
1455  */
1456 bool memory_region_init_ram_from_file(MemoryRegion *mr,
1457                                       Object *owner,
1458                                       const char *name,
1459                                       uint64_t size,
1460                                       uint64_t align,
1461                                       uint32_t ram_flags,
1462                                       const char *path,
1463                                       ram_addr_t offset,
1464                                       Error **errp);
1465 
1466 /**
1467  * memory_region_init_ram_from_fd:  Initialize RAM memory region with a
1468  *                                  mmap-ed backend.
1469  *
1470  * @mr: the #MemoryRegion to be initialized.
1471  * @owner: the object that tracks the region's reference count
1472  * @name: the name of the region.
1473  * @size: size of the region.
1474  * @ram_flags: RamBlock flags. Supported flags: RAM_SHARED, RAM_PMEM,
1475  *             RAM_NORESERVE, RAM_PROTECTED, RAM_NAMED_FILE, RAM_READONLY,
1476  *             RAM_READONLY_FD, RAM_GUEST_MEMFD
1477  * @fd: the fd to mmap.
1478  * @offset: offset within the file referenced by fd
1479  * @errp: pointer to Error*, to store an error if it happens.
1480  *
1481  * Note that this function does not do anything to cause the data in the
1482  * RAM memory region to be migrated; that is the responsibility of the caller.
1483  *
1484  * Return: true on success, else false setting @errp with error.
1485  */
1486 bool memory_region_init_ram_from_fd(MemoryRegion *mr,
1487                                     Object *owner,
1488                                     const char *name,
1489                                     uint64_t size,
1490                                     uint32_t ram_flags,
1491                                     int fd,
1492                                     ram_addr_t offset,
1493                                     Error **errp);
1494 #endif
1495 
1496 /**
1497  * memory_region_init_ram_ptr:  Initialize RAM memory region from a
1498  *                              user-provided pointer.  Accesses into the
1499  *                              region will modify memory directly.
1500  *
1501  * @mr: the #MemoryRegion to be initialized.
1502  * @owner: the object that tracks the region's reference count
1503  * @name: Region name, becomes part of RAMBlock name used in migration stream
1504  *        must be unique within any device
1505  * @size: size of the region.
1506  * @ptr: memory to be mapped; must contain at least @size bytes.
1507  *
1508  * Note that this function does not do anything to cause the data in the
1509  * RAM memory region to be migrated; that is the responsibility of the caller.
1510  */
1511 void memory_region_init_ram_ptr(MemoryRegion *mr,
1512                                 Object *owner,
1513                                 const char *name,
1514                                 uint64_t size,
1515                                 void *ptr);
1516 
1517 /**
1518  * memory_region_init_ram_device_ptr:  Initialize RAM device memory region from
1519  *                                     a user-provided pointer.
1520  *
1521  * A RAM device represents a mapping to a physical device, such as to a PCI
1522  * MMIO BAR of an vfio-pci assigned device.  The memory region may be mapped
1523  * into the VM address space and access to the region will modify memory
1524  * directly.  However, the memory region should not be included in a memory
1525  * dump (device may not be enabled/mapped at the time of the dump), and
1526  * operations incompatible with manipulating MMIO should be avoided.  Replaces
1527  * skip_dump flag.
1528  *
1529  * @mr: the #MemoryRegion to be initialized.
1530  * @owner: the object that tracks the region's reference count
1531  * @name: the name of the region.
1532  * @size: size of the region.
1533  * @ptr: memory to be mapped; must contain at least @size bytes.
1534  *
1535  * Note that this function does not do anything to cause the data in the
1536  * RAM memory region to be migrated; that is the responsibility of the caller.
1537  * (For RAM device memory regions, migrating the contents rarely makes sense.)
1538  */
1539 void memory_region_init_ram_device_ptr(MemoryRegion *mr,
1540                                        Object *owner,
1541                                        const char *name,
1542                                        uint64_t size,
1543                                        void *ptr);
1544 
1545 /**
1546  * memory_region_init_alias: Initialize a memory region that aliases all or a
1547  *                           part of another memory region.
1548  *
1549  * @mr: the #MemoryRegion to be initialized.
1550  * @owner: the object that tracks the region's reference count
1551  * @name: used for debugging; not visible to the user or ABI
1552  * @orig: the region to be referenced; @mr will be equivalent to
1553  *        @orig between @offset and @offset + @size - 1.
1554  * @offset: start of the section in @orig to be referenced.
1555  * @size: size of the region.
1556  */
1557 void memory_region_init_alias(MemoryRegion *mr,
1558                               Object *owner,
1559                               const char *name,
1560                               MemoryRegion *orig,
1561                               hwaddr offset,
1562                               uint64_t size);
1563 
1564 /**
1565  * memory_region_init_rom_nomigrate: Initialize a ROM memory region.
1566  *
1567  * This has the same effect as calling memory_region_init_ram_nomigrate()
1568  * and then marking the resulting region read-only with
1569  * memory_region_set_readonly().
1570  *
1571  * Note that this function does not do anything to cause the data in the
1572  * RAM side of the memory region to be migrated; that is the responsibility
1573  * of the caller.
1574  *
1575  * @mr: the #MemoryRegion to be initialized.
1576  * @owner: the object that tracks the region's reference count
1577  * @name: Region name, becomes part of RAMBlock name used in migration stream
1578  *        must be unique within any device
1579  * @size: size of the region.
1580  * @errp: pointer to Error*, to store an error if it happens.
1581  *
1582  * Return: true on success, else false setting @errp with error.
1583  */
1584 bool memory_region_init_rom_nomigrate(MemoryRegion *mr,
1585                                       Object *owner,
1586                                       const char *name,
1587                                       uint64_t size,
1588                                       Error **errp);
1589 
1590 /**
1591  * memory_region_init_rom_device_nomigrate:  Initialize a ROM memory region.
1592  *                                 Writes are handled via callbacks.
1593  *
1594  * Note that this function does not do anything to cause the data in the
1595  * RAM side of the memory region to be migrated; that is the responsibility
1596  * of the caller.
1597  *
1598  * @mr: the #MemoryRegion to be initialized.
1599  * @owner: the object that tracks the region's reference count
1600  * @ops: callbacks for write access handling (must not be NULL).
1601  * @opaque: passed to the read and write callbacks of the @ops structure.
1602  * @name: Region name, becomes part of RAMBlock name used in migration stream
1603  *        must be unique within any device
1604  * @size: size of the region.
1605  * @errp: pointer to Error*, to store an error if it happens.
1606  *
1607  * Return: true on success, else false setting @errp with error.
1608  */
1609 bool memory_region_init_rom_device_nomigrate(MemoryRegion *mr,
1610                                              Object *owner,
1611                                              const MemoryRegionOps *ops,
1612                                              void *opaque,
1613                                              const char *name,
1614                                              uint64_t size,
1615                                              Error **errp);
1616 
1617 /**
1618  * memory_region_init_iommu: Initialize a memory region of a custom type
1619  * that translates addresses
1620  *
1621  * An IOMMU region translates addresses and forwards accesses to a target
1622  * memory region.
1623  *
1624  * The IOMMU implementation must define a subclass of TYPE_IOMMU_MEMORY_REGION.
1625  * @_iommu_mr should be a pointer to enough memory for an instance of
1626  * that subclass, @instance_size is the size of that subclass, and
1627  * @mrtypename is its name. This function will initialize @_iommu_mr as an
1628  * instance of the subclass, and its methods will then be called to handle
1629  * accesses to the memory region. See the documentation of
1630  * #IOMMUMemoryRegionClass for further details.
1631  *
1632  * @_iommu_mr: the #IOMMUMemoryRegion to be initialized
1633  * @instance_size: the IOMMUMemoryRegion subclass instance size
1634  * @mrtypename: the type name of the #IOMMUMemoryRegion
1635  * @owner: the object that tracks the region's reference count
1636  * @name: used for debugging; not visible to the user or ABI
1637  * @size: size of the region.
1638  */
1639 void memory_region_init_iommu(void *_iommu_mr,
1640                               size_t instance_size,
1641                               const char *mrtypename,
1642                               Object *owner,
1643                               const char *name,
1644                               uint64_t size);
1645 
1646 /**
1647  * memory_region_init_ram - Initialize RAM memory region.  Accesses into the
1648  *                          region will modify memory directly.
1649  *
1650  * @mr: the #MemoryRegion to be initialized
1651  * @owner: the object that tracks the region's reference count (must be
1652  *         TYPE_DEVICE or a subclass of TYPE_DEVICE, or NULL)
1653  * @name: name of the memory region
1654  * @size: size of the region in bytes
1655  * @errp: pointer to Error*, to store an error if it happens.
1656  *
1657  * This function allocates RAM for a board model or device, and
1658  * arranges for it to be migrated (by calling vmstate_register_ram()
1659  * if @owner is a DeviceState, or vmstate_register_ram_global() if
1660  * @owner is NULL).
1661  *
1662  * TODO: Currently we restrict @owner to being either NULL (for
1663  * global RAM regions with no owner) or devices, so that we can
1664  * give the RAM block a unique name for migration purposes.
1665  * We should lift this restriction and allow arbitrary Objects.
1666  * If you pass a non-NULL non-device @owner then we will assert.
1667  *
1668  * Return: true on success, else false setting @errp with error.
1669  */
1670 bool memory_region_init_ram(MemoryRegion *mr,
1671                             Object *owner,
1672                             const char *name,
1673                             uint64_t size,
1674                             Error **errp);
1675 
1676 bool memory_region_init_ram_guest_memfd(MemoryRegion *mr,
1677                                         Object *owner,
1678                                         const char *name,
1679                                         uint64_t size,
1680                                         Error **errp);
1681 
1682 /**
1683  * memory_region_init_rom: Initialize a ROM memory region.
1684  *
1685  * This has the same effect as calling memory_region_init_ram()
1686  * and then marking the resulting region read-only with
1687  * memory_region_set_readonly(). This includes arranging for the
1688  * contents to be migrated.
1689  *
1690  * TODO: Currently we restrict @owner to being either NULL (for
1691  * global RAM regions with no owner) or devices, so that we can
1692  * give the RAM block a unique name for migration purposes.
1693  * We should lift this restriction and allow arbitrary Objects.
1694  * If you pass a non-NULL non-device @owner then we will assert.
1695  *
1696  * @mr: the #MemoryRegion to be initialized.
1697  * @owner: the object that tracks the region's reference count
1698  * @name: Region name, becomes part of RAMBlock name used in migration stream
1699  *        must be unique within any device
1700  * @size: size of the region.
1701  * @errp: pointer to Error*, to store an error if it happens.
1702  *
1703  * Return: true on success, else false setting @errp with error.
1704  */
1705 bool memory_region_init_rom(MemoryRegion *mr,
1706                             Object *owner,
1707                             const char *name,
1708                             uint64_t size,
1709                             Error **errp);
1710 
1711 /**
1712  * memory_region_init_rom_device:  Initialize a ROM memory region.
1713  *                                 Writes are handled via callbacks.
1714  *
1715  * This function initializes a memory region backed by RAM for reads
1716  * and callbacks for writes, and arranges for the RAM backing to
1717  * be migrated (by calling vmstate_register_ram()
1718  * if @owner is a DeviceState, or vmstate_register_ram_global() if
1719  * @owner is NULL).
1720  *
1721  * TODO: Currently we restrict @owner to being either NULL (for
1722  * global RAM regions with no owner) or devices, so that we can
1723  * give the RAM block a unique name for migration purposes.
1724  * We should lift this restriction and allow arbitrary Objects.
1725  * If you pass a non-NULL non-device @owner then we will assert.
1726  *
1727  * @mr: the #MemoryRegion to be initialized.
1728  * @owner: the object that tracks the region's reference count
1729  * @ops: callbacks for write access handling (must not be NULL).
1730  * @opaque: passed to the read and write callbacks of the @ops structure.
1731  * @name: Region name, becomes part of RAMBlock name used in migration stream
1732  *        must be unique within any device
1733  * @size: size of the region.
1734  * @errp: pointer to Error*, to store an error if it happens.
1735  *
1736  * Return: true on success, else false setting @errp with error.
1737  */
1738 bool memory_region_init_rom_device(MemoryRegion *mr,
1739                                    Object *owner,
1740                                    const MemoryRegionOps *ops,
1741                                    void *opaque,
1742                                    const char *name,
1743                                    uint64_t size,
1744                                    Error **errp);
1745 
1746 
1747 /**
1748  * memory_region_owner: get a memory region's owner.
1749  *
1750  * @mr: the memory region being queried.
1751  */
1752 Object *memory_region_owner(MemoryRegion *mr);
1753 
1754 /**
1755  * memory_region_size: get a memory region's size.
1756  *
1757  * @mr: the memory region being queried.
1758  */
1759 uint64_t memory_region_size(MemoryRegion *mr);
1760 
1761 /**
1762  * memory_region_is_ram: check whether a memory region is random access
1763  *
1764  * Returns %true if a memory region is random access.
1765  *
1766  * @mr: the memory region being queried
1767  */
memory_region_is_ram(MemoryRegion * mr)1768 static inline bool memory_region_is_ram(MemoryRegion *mr)
1769 {
1770     return mr->ram;
1771 }
1772 
1773 /**
1774  * memory_region_is_ram_device: check whether a memory region is a ram device
1775  *
1776  * Returns %true if a memory region is a device backed ram region
1777  *
1778  * @mr: the memory region being queried
1779  */
1780 bool memory_region_is_ram_device(MemoryRegion *mr);
1781 
1782 /**
1783  * memory_region_is_romd: check whether a memory region is in ROMD mode
1784  *
1785  * Returns %true if a memory region is a ROM device and currently set to allow
1786  * direct reads.
1787  *
1788  * @mr: the memory region being queried
1789  */
memory_region_is_romd(MemoryRegion * mr)1790 static inline bool memory_region_is_romd(MemoryRegion *mr)
1791 {
1792     return mr->rom_device && mr->romd_mode;
1793 }
1794 
1795 /**
1796  * memory_region_is_protected: check whether a memory region is protected
1797  *
1798  * Returns %true if a memory region is protected RAM and cannot be accessed
1799  * via standard mechanisms, e.g. DMA.
1800  *
1801  * @mr: the memory region being queried
1802  */
1803 bool memory_region_is_protected(MemoryRegion *mr);
1804 
1805 /**
1806  * memory_region_has_guest_memfd: check whether a memory region has guest_memfd
1807  *     associated
1808  *
1809  * Returns %true if a memory region's ram_block has valid guest_memfd assigned.
1810  *
1811  * @mr: the memory region being queried
1812  */
1813 bool memory_region_has_guest_memfd(MemoryRegion *mr);
1814 
1815 /**
1816  * memory_region_get_iommu: check whether a memory region is an iommu
1817  *
1818  * Returns pointer to IOMMUMemoryRegion if a memory region is an iommu,
1819  * otherwise NULL.
1820  *
1821  * @mr: the memory region being queried
1822  */
memory_region_get_iommu(MemoryRegion * mr)1823 static inline IOMMUMemoryRegion *memory_region_get_iommu(MemoryRegion *mr)
1824 {
1825     if (mr->alias) {
1826         return memory_region_get_iommu(mr->alias);
1827     }
1828     if (mr->is_iommu) {
1829         return (IOMMUMemoryRegion *) mr;
1830     }
1831     return NULL;
1832 }
1833 
1834 /**
1835  * memory_region_get_iommu_class_nocheck: returns iommu memory region class
1836  *   if an iommu or NULL if not
1837  *
1838  * Returns pointer to IOMMUMemoryRegionClass if a memory region is an iommu,
1839  * otherwise NULL. This is fast path avoiding QOM checking, use with caution.
1840  *
1841  * @iommu_mr: the memory region being queried
1842  */
memory_region_get_iommu_class_nocheck(IOMMUMemoryRegion * iommu_mr)1843 static inline IOMMUMemoryRegionClass *memory_region_get_iommu_class_nocheck(
1844         IOMMUMemoryRegion *iommu_mr)
1845 {
1846     return (IOMMUMemoryRegionClass *) (((Object *)iommu_mr)->class);
1847 }
1848 
1849 #define memory_region_is_iommu(mr) (memory_region_get_iommu(mr) != NULL)
1850 
1851 /**
1852  * memory_region_iommu_get_min_page_size: get minimum supported page size
1853  * for an iommu
1854  *
1855  * Returns minimum supported page size for an iommu.
1856  *
1857  * @iommu_mr: the memory region being queried
1858  */
1859 uint64_t memory_region_iommu_get_min_page_size(IOMMUMemoryRegion *iommu_mr);
1860 
1861 /**
1862  * memory_region_notify_iommu: notify a change in an IOMMU translation entry.
1863  *
1864  * Note: for any IOMMU implementation, an in-place mapping change
1865  * should be notified with an UNMAP followed by a MAP.
1866  *
1867  * @iommu_mr: the memory region that was changed
1868  * @iommu_idx: the IOMMU index for the translation table which has changed
1869  * @event: TLB event with the new entry in the IOMMU translation table.
1870  *         The entry replaces all old entries for the same virtual I/O address
1871  *         range.
1872  */
1873 void memory_region_notify_iommu(IOMMUMemoryRegion *iommu_mr,
1874                                 int iommu_idx,
1875                                 const IOMMUTLBEvent event);
1876 
1877 /**
1878  * memory_region_notify_iommu_one: notify a change in an IOMMU translation
1879  *                           entry to a single notifier
1880  *
1881  * This works just like memory_region_notify_iommu(), but it only
1882  * notifies a specific notifier, not all of them.
1883  *
1884  * @notifier: the notifier to be notified
1885  * @event: TLB event with the new entry in the IOMMU translation table.
1886  *         The entry replaces all old entries for the same virtual I/O address
1887  *         range.
1888  */
1889 void memory_region_notify_iommu_one(IOMMUNotifier *notifier,
1890                                     const IOMMUTLBEvent *event);
1891 
1892 /**
1893  * memory_region_unmap_iommu_notifier_range: notify a unmap for an IOMMU
1894  *                                           translation that covers the
1895  *                                           range of a notifier
1896  *
1897  * @notifier: the notifier to be notified
1898  */
1899 void memory_region_unmap_iommu_notifier_range(IOMMUNotifier *notifier);
1900 
1901 
1902 /**
1903  * memory_region_register_iommu_notifier: register a notifier for changes to
1904  * IOMMU translation entries.
1905  *
1906  * Returns 0 on success, or a negative errno otherwise. In particular,
1907  * -EINVAL indicates that at least one of the attributes of the notifier
1908  * is not supported (flag/range) by the IOMMU memory region. In case of error
1909  * the error object must be created.
1910  *
1911  * @mr: the memory region to observe
1912  * @n: the IOMMUNotifier to be added; the notify callback receives a
1913  *     pointer to an #IOMMUTLBEntry as the opaque value; the pointer
1914  *     ceases to be valid on exit from the notifier.
1915  * @errp: pointer to Error*, to store an error if it happens.
1916  */
1917 int memory_region_register_iommu_notifier(MemoryRegion *mr,
1918                                           IOMMUNotifier *n, Error **errp);
1919 
1920 /**
1921  * memory_region_iommu_replay: replay existing IOMMU translations to
1922  * a notifier with the minimum page granularity returned by
1923  * mr->iommu_ops->get_page_size().
1924  *
1925  * Note: this is not related to record-and-replay functionality.
1926  *
1927  * @iommu_mr: the memory region to observe
1928  * @n: the notifier to which to replay iommu mappings
1929  */
1930 void memory_region_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n);
1931 
1932 /**
1933  * memory_region_unregister_iommu_notifier: unregister a notifier for
1934  * changes to IOMMU translation entries.
1935  *
1936  * @mr: the memory region which was observed and for which notify_stopped()
1937  *      needs to be called
1938  * @n: the notifier to be removed.
1939  */
1940 void memory_region_unregister_iommu_notifier(MemoryRegion *mr,
1941                                              IOMMUNotifier *n);
1942 
1943 /**
1944  * memory_region_iommu_get_attr: return an IOMMU attr if get_attr() is
1945  * defined on the IOMMU.
1946  *
1947  * Returns 0 on success, or a negative errno otherwise. In particular,
1948  * -EINVAL indicates that the IOMMU does not support the requested
1949  * attribute.
1950  *
1951  * @iommu_mr: the memory region
1952  * @attr: the requested attribute
1953  * @data: a pointer to the requested attribute data
1954  */
1955 int memory_region_iommu_get_attr(IOMMUMemoryRegion *iommu_mr,
1956                                  enum IOMMUMemoryRegionAttr attr,
1957                                  void *data);
1958 
1959 /**
1960  * memory_region_iommu_attrs_to_index: return the IOMMU index to
1961  * use for translations with the given memory transaction attributes.
1962  *
1963  * @iommu_mr: the memory region
1964  * @attrs: the memory transaction attributes
1965  */
1966 int memory_region_iommu_attrs_to_index(IOMMUMemoryRegion *iommu_mr,
1967                                        MemTxAttrs attrs);
1968 
1969 /**
1970  * memory_region_iommu_num_indexes: return the total number of IOMMU
1971  * indexes that this IOMMU supports.
1972  *
1973  * @iommu_mr: the memory region
1974  */
1975 int memory_region_iommu_num_indexes(IOMMUMemoryRegion *iommu_mr);
1976 
1977 /**
1978  * memory_region_name: get a memory region's name
1979  *
1980  * Returns the string that was used to initialize the memory region.
1981  *
1982  * @mr: the memory region being queried
1983  */
1984 const char *memory_region_name(const MemoryRegion *mr);
1985 
1986 /**
1987  * memory_region_is_logging: return whether a memory region is logging writes
1988  *
1989  * Returns %true if the memory region is logging writes for the given client
1990  *
1991  * @mr: the memory region being queried
1992  * @client: the client being queried
1993  */
1994 bool memory_region_is_logging(MemoryRegion *mr, uint8_t client);
1995 
1996 /**
1997  * memory_region_get_dirty_log_mask: return the clients for which a
1998  * memory region is logging writes.
1999  *
2000  * Returns a bitmap of clients, in which the DIRTY_MEMORY_* constants
2001  * are the bit indices.
2002  *
2003  * @mr: the memory region being queried
2004  */
2005 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr);
2006 
2007 /**
2008  * memory_region_is_rom: check whether a memory region is ROM
2009  *
2010  * Returns %true if a memory region is read-only memory.
2011  *
2012  * @mr: the memory region being queried
2013  */
memory_region_is_rom(MemoryRegion * mr)2014 static inline bool memory_region_is_rom(MemoryRegion *mr)
2015 {
2016     return mr->ram && mr->readonly;
2017 }
2018 
2019 /**
2020  * memory_region_is_nonvolatile: check whether a memory region is non-volatile
2021  *
2022  * Returns %true is a memory region is non-volatile memory.
2023  *
2024  * @mr: the memory region being queried
2025  */
memory_region_is_nonvolatile(MemoryRegion * mr)2026 static inline bool memory_region_is_nonvolatile(MemoryRegion *mr)
2027 {
2028     return mr->nonvolatile;
2029 }
2030 
2031 /**
2032  * memory_region_get_fd: Get a file descriptor backing a RAM memory region.
2033  *
2034  * Returns a file descriptor backing a file-based RAM memory region,
2035  * or -1 if the region is not a file-based RAM memory region.
2036  *
2037  * @mr: the RAM or alias memory region being queried.
2038  */
2039 int memory_region_get_fd(MemoryRegion *mr);
2040 
2041 /**
2042  * memory_region_from_host: Convert a pointer into a RAM memory region
2043  * and an offset within it.
2044  *
2045  * Given a host pointer inside a RAM memory region (created with
2046  * memory_region_init_ram() or memory_region_init_ram_ptr()), return
2047  * the MemoryRegion and the offset within it.
2048  *
2049  * Use with care; by the time this function returns, the returned pointer is
2050  * not protected by RCU anymore.  If the caller is not within an RCU critical
2051  * section and does not hold the BQL, it must have other means of
2052  * protecting the pointer, such as a reference to the region that includes
2053  * the incoming ram_addr_t.
2054  *
2055  * @ptr: the host pointer to be converted
2056  * @offset: the offset within memory region
2057  */
2058 MemoryRegion *memory_region_from_host(void *ptr, ram_addr_t *offset);
2059 
2060 /**
2061  * memory_region_get_ram_ptr: Get a pointer into a RAM memory region.
2062  *
2063  * Returns a host pointer to a RAM memory region (created with
2064  * memory_region_init_ram() or memory_region_init_ram_ptr()).
2065  *
2066  * Use with care; by the time this function returns, the returned pointer is
2067  * not protected by RCU anymore.  If the caller is not within an RCU critical
2068  * section and does not hold the BQL, it must have other means of
2069  * protecting the pointer, such as a reference to the region that includes
2070  * the incoming ram_addr_t.
2071  *
2072  * @mr: the memory region being queried.
2073  */
2074 void *memory_region_get_ram_ptr(MemoryRegion *mr);
2075 
2076 /* memory_region_ram_resize: Resize a RAM region.
2077  *
2078  * Resizing RAM while migrating can result in the migration being canceled.
2079  * Care has to be taken if the guest might have already detected the memory.
2080  *
2081  * @mr: a memory region created with @memory_region_init_resizeable_ram.
2082  * @newsize: the new size the region
2083  * @errp: pointer to Error*, to store an error if it happens.
2084  */
2085 void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize,
2086                               Error **errp);
2087 
2088 /**
2089  * memory_region_msync: Synchronize selected address range of
2090  * a memory mapped region
2091  *
2092  * @mr: the memory region to be msync
2093  * @addr: the initial address of the range to be sync
2094  * @size: the size of the range to be sync
2095  */
2096 void memory_region_msync(MemoryRegion *mr, hwaddr addr, hwaddr size);
2097 
2098 /**
2099  * memory_region_writeback: Trigger cache writeback for
2100  * selected address range
2101  *
2102  * @mr: the memory region to be updated
2103  * @addr: the initial address of the range to be written back
2104  * @size: the size of the range to be written back
2105  */
2106 void memory_region_writeback(MemoryRegion *mr, hwaddr addr, hwaddr size);
2107 
2108 /**
2109  * memory_region_set_log: Turn dirty logging on or off for a region.
2110  *
2111  * Turns dirty logging on or off for a specified client (display, migration).
2112  * Only meaningful for RAM regions.
2113  *
2114  * @mr: the memory region being updated.
2115  * @log: whether dirty logging is to be enabled or disabled.
2116  * @client: the user of the logging information; %DIRTY_MEMORY_VGA only.
2117  */
2118 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client);
2119 
2120 /**
2121  * memory_region_set_dirty: Mark a range of bytes as dirty in a memory region.
2122  *
2123  * Marks a range of bytes as dirty, after it has been dirtied outside
2124  * guest code.
2125  *
2126  * @mr: the memory region being dirtied.
2127  * @addr: the address (relative to the start of the region) being dirtied.
2128  * @size: size of the range being dirtied.
2129  */
2130 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
2131                              hwaddr size);
2132 
2133 /**
2134  * memory_region_clear_dirty_bitmap - clear dirty bitmap for memory range
2135  *
2136  * This function is called when the caller wants to clear the remote
2137  * dirty bitmap of a memory range within the memory region.  This can
2138  * be used by e.g. KVM to manually clear dirty log when
2139  * KVM_CAP_MANUAL_DIRTY_LOG_PROTECT is declared support by the host
2140  * kernel.
2141  *
2142  * @mr:     the memory region to clear the dirty log upon
2143  * @start:  start address offset within the memory region
2144  * @len:    length of the memory region to clear dirty bitmap
2145  */
2146 void memory_region_clear_dirty_bitmap(MemoryRegion *mr, hwaddr start,
2147                                       hwaddr len);
2148 
2149 /**
2150  * memory_region_snapshot_and_clear_dirty: Get a snapshot of the dirty
2151  *                                         bitmap and clear it.
2152  *
2153  * Creates a snapshot of the dirty bitmap, clears the dirty bitmap and
2154  * returns the snapshot.  The snapshot can then be used to query dirty
2155  * status, using memory_region_snapshot_get_dirty.  Snapshotting allows
2156  * querying the same page multiple times, which is especially useful for
2157  * display updates where the scanlines often are not page aligned.
2158  *
2159  * The dirty bitmap region which gets copied into the snapshot (and
2160  * cleared afterwards) can be larger than requested.  The boundaries
2161  * are rounded up/down so complete bitmap longs (covering 64 pages on
2162  * 64bit hosts) can be copied over into the bitmap snapshot.  Which
2163  * isn't a problem for display updates as the extra pages are outside
2164  * the visible area, and in case the visible area changes a full
2165  * display redraw is due anyway.  Should other use cases for this
2166  * function emerge we might have to revisit this implementation
2167  * detail.
2168  *
2169  * Use g_free to release DirtyBitmapSnapshot.
2170  *
2171  * @mr: the memory region being queried.
2172  * @addr: the address (relative to the start of the region) being queried.
2173  * @size: the size of the range being queried.
2174  * @client: the user of the logging information; typically %DIRTY_MEMORY_VGA.
2175  */
2176 DirtyBitmapSnapshot *memory_region_snapshot_and_clear_dirty(MemoryRegion *mr,
2177                                                             hwaddr addr,
2178                                                             hwaddr size,
2179                                                             unsigned client);
2180 
2181 /**
2182  * memory_region_snapshot_get_dirty: Check whether a range of bytes is dirty
2183  *                                   in the specified dirty bitmap snapshot.
2184  *
2185  * @mr: the memory region being queried.
2186  * @snap: the dirty bitmap snapshot
2187  * @addr: the address (relative to the start of the region) being queried.
2188  * @size: the size of the range being queried.
2189  */
2190 bool memory_region_snapshot_get_dirty(MemoryRegion *mr,
2191                                       DirtyBitmapSnapshot *snap,
2192                                       hwaddr addr, hwaddr size);
2193 
2194 /**
2195  * memory_region_reset_dirty: Mark a range of pages as clean, for a specified
2196  *                            client.
2197  *
2198  * Marks a range of pages as no longer dirty.
2199  *
2200  * @mr: the region being updated.
2201  * @addr: the start of the subrange being cleaned.
2202  * @size: the size of the subrange being cleaned.
2203  * @client: the user of the logging information; %DIRTY_MEMORY_MIGRATION or
2204  *          %DIRTY_MEMORY_VGA.
2205  */
2206 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
2207                                hwaddr size, unsigned client);
2208 
2209 /**
2210  * memory_region_flush_rom_device: Mark a range of pages dirty and invalidate
2211  *                                 TBs (for self-modifying code).
2212  *
2213  * The MemoryRegionOps->write() callback of a ROM device must use this function
2214  * to mark byte ranges that have been modified internally, such as by directly
2215  * accessing the memory returned by memory_region_get_ram_ptr().
2216  *
2217  * This function marks the range dirty and invalidates TBs so that TCG can
2218  * detect self-modifying code.
2219  *
2220  * @mr: the region being flushed.
2221  * @addr: the start, relative to the start of the region, of the range being
2222  *        flushed.
2223  * @size: the size, in bytes, of the range being flushed.
2224  */
2225 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size);
2226 
2227 /**
2228  * memory_region_set_readonly: Turn a memory region read-only (or read-write)
2229  *
2230  * Allows a memory region to be marked as read-only (turning it into a ROM).
2231  * only useful on RAM regions.
2232  *
2233  * @mr: the region being updated.
2234  * @readonly: whether the region is to be ROM or RAM.
2235  */
2236 void memory_region_set_readonly(MemoryRegion *mr, bool readonly);
2237 
2238 /**
2239  * memory_region_set_nonvolatile: Turn a memory region non-volatile
2240  *
2241  * Allows a memory region to be marked as non-volatile.
2242  * only useful on RAM regions.
2243  *
2244  * @mr: the region being updated.
2245  * @nonvolatile: whether the region is to be non-volatile.
2246  */
2247 void memory_region_set_nonvolatile(MemoryRegion *mr, bool nonvolatile);
2248 
2249 /**
2250  * memory_region_rom_device_set_romd: enable/disable ROMD mode
2251  *
2252  * Allows a ROM device (initialized with memory_region_init_rom_device() to
2253  * set to ROMD mode (default) or MMIO mode.  When it is in ROMD mode, the
2254  * device is mapped to guest memory and satisfies read access directly.
2255  * When in MMIO mode, reads are forwarded to the #MemoryRegion.read function.
2256  * Writes are always handled by the #MemoryRegion.write function.
2257  *
2258  * @mr: the memory region to be updated
2259  * @romd_mode: %true to put the region into ROMD mode
2260  */
2261 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode);
2262 
2263 /**
2264  * memory_region_set_coalescing: Enable memory coalescing for the region.
2265  *
2266  * Enabled writes to a region to be queued for later processing. MMIO ->write
2267  * callbacks may be delayed until a non-coalesced MMIO is issued.
2268  * Only useful for IO regions.  Roughly similar to write-combining hardware.
2269  *
2270  * @mr: the memory region to be write coalesced
2271  */
2272 void memory_region_set_coalescing(MemoryRegion *mr);
2273 
2274 /**
2275  * memory_region_add_coalescing: Enable memory coalescing for a sub-range of
2276  *                               a region.
2277  *
2278  * Like memory_region_set_coalescing(), but works on a sub-range of a region.
2279  * Multiple calls can be issued coalesced disjoint ranges.
2280  *
2281  * @mr: the memory region to be updated.
2282  * @offset: the start of the range within the region to be coalesced.
2283  * @size: the size of the subrange to be coalesced.
2284  */
2285 void memory_region_add_coalescing(MemoryRegion *mr,
2286                                   hwaddr offset,
2287                                   uint64_t size);
2288 
2289 /**
2290  * memory_region_clear_coalescing: Disable MMIO coalescing for the region.
2291  *
2292  * Disables any coalescing caused by memory_region_set_coalescing() or
2293  * memory_region_add_coalescing().  Roughly equivalent to uncacheble memory
2294  * hardware.
2295  *
2296  * @mr: the memory region to be updated.
2297  */
2298 void memory_region_clear_coalescing(MemoryRegion *mr);
2299 
2300 /**
2301  * memory_region_set_flush_coalesced: Enforce memory coalescing flush before
2302  *                                    accesses.
2303  *
2304  * Ensure that pending coalesced MMIO request are flushed before the memory
2305  * region is accessed. This property is automatically enabled for all regions
2306  * passed to memory_region_set_coalescing() and memory_region_add_coalescing().
2307  *
2308  * @mr: the memory region to be updated.
2309  */
2310 void memory_region_set_flush_coalesced(MemoryRegion *mr);
2311 
2312 /**
2313  * memory_region_clear_flush_coalesced: Disable memory coalescing flush before
2314  *                                      accesses.
2315  *
2316  * Clear the automatic coalesced MMIO flushing enabled via
2317  * memory_region_set_flush_coalesced. Note that this service has no effect on
2318  * memory regions that have MMIO coalescing enabled for themselves. For them,
2319  * automatic flushing will stop once coalescing is disabled.
2320  *
2321  * @mr: the memory region to be updated.
2322  */
2323 void memory_region_clear_flush_coalesced(MemoryRegion *mr);
2324 
2325 /**
2326  * memory_region_add_eventfd: Request an eventfd to be triggered when a word
2327  *                            is written to a location.
2328  *
2329  * Marks a word in an IO region (initialized with memory_region_init_io())
2330  * as a trigger for an eventfd event.  The I/O callback will not be called.
2331  * The caller must be prepared to handle failure (that is, take the required
2332  * action if the callback _is_ called).
2333  *
2334  * @mr: the memory region being updated.
2335  * @addr: the address within @mr that is to be monitored
2336  * @size: the size of the access to trigger the eventfd
2337  * @match_data: whether to match against @data, instead of just @addr
2338  * @data: the data to match against the guest write
2339  * @e: event notifier to be triggered when @addr, @size, and @data all match.
2340  **/
2341 void memory_region_add_eventfd(MemoryRegion *mr,
2342                                hwaddr addr,
2343                                unsigned size,
2344                                bool match_data,
2345                                uint64_t data,
2346                                EventNotifier *e);
2347 
2348 /**
2349  * memory_region_del_eventfd: Cancel an eventfd.
2350  *
2351  * Cancels an eventfd trigger requested by a previous
2352  * memory_region_add_eventfd() call.
2353  *
2354  * @mr: the memory region being updated.
2355  * @addr: the address within @mr that is to be monitored
2356  * @size: the size of the access to trigger the eventfd
2357  * @match_data: whether to match against @data, instead of just @addr
2358  * @data: the data to match against the guest write
2359  * @e: event notifier to be triggered when @addr, @size, and @data all match.
2360  */
2361 void memory_region_del_eventfd(MemoryRegion *mr,
2362                                hwaddr addr,
2363                                unsigned size,
2364                                bool match_data,
2365                                uint64_t data,
2366                                EventNotifier *e);
2367 
2368 /**
2369  * memory_region_add_subregion: Add a subregion to a container.
2370  *
2371  * Adds a subregion at @offset.  The subregion may not overlap with other
2372  * subregions (except for those explicitly marked as overlapping).  A region
2373  * may only be added once as a subregion (unless removed with
2374  * memory_region_del_subregion()); use memory_region_init_alias() if you
2375  * want a region to be a subregion in multiple locations.
2376  *
2377  * @mr: the region to contain the new subregion; must be a container
2378  *      initialized with memory_region_init().
2379  * @offset: the offset relative to @mr where @subregion is added.
2380  * @subregion: the subregion to be added.
2381  */
2382 void memory_region_add_subregion(MemoryRegion *mr,
2383                                  hwaddr offset,
2384                                  MemoryRegion *subregion);
2385 /**
2386  * memory_region_add_subregion_overlap: Add a subregion to a container
2387  *                                      with overlap.
2388  *
2389  * Adds a subregion at @offset.  The subregion may overlap with other
2390  * subregions.  Conflicts are resolved by having a higher @priority hide a
2391  * lower @priority. Subregions without priority are taken as @priority 0.
2392  * A region may only be added once as a subregion (unless removed with
2393  * memory_region_del_subregion()); use memory_region_init_alias() if you
2394  * want a region to be a subregion in multiple locations.
2395  *
2396  * @mr: the region to contain the new subregion; must be a container
2397  *      initialized with memory_region_init().
2398  * @offset: the offset relative to @mr where @subregion is added.
2399  * @subregion: the subregion to be added.
2400  * @priority: used for resolving overlaps; highest priority wins.
2401  */
2402 void memory_region_add_subregion_overlap(MemoryRegion *mr,
2403                                          hwaddr offset,
2404                                          MemoryRegion *subregion,
2405                                          int priority);
2406 
2407 /**
2408  * memory_region_get_ram_addr: Get the ram address associated with a memory
2409  *                             region
2410  *
2411  * @mr: the region to be queried
2412  */
2413 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr);
2414 
2415 uint64_t memory_region_get_alignment(const MemoryRegion *mr);
2416 /**
2417  * memory_region_del_subregion: Remove a subregion.
2418  *
2419  * Removes a subregion from its container.
2420  *
2421  * @mr: the container to be updated.
2422  * @subregion: the region being removed; must be a current subregion of @mr.
2423  */
2424 void memory_region_del_subregion(MemoryRegion *mr,
2425                                  MemoryRegion *subregion);
2426 
2427 /*
2428  * memory_region_set_enabled: dynamically enable or disable a region
2429  *
2430  * Enables or disables a memory region.  A disabled memory region
2431  * ignores all accesses to itself and its subregions.  It does not
2432  * obscure sibling subregions with lower priority - it simply behaves as
2433  * if it was removed from the hierarchy.
2434  *
2435  * Regions default to being enabled.
2436  *
2437  * @mr: the region to be updated
2438  * @enabled: whether to enable or disable the region
2439  */
2440 void memory_region_set_enabled(MemoryRegion *mr, bool enabled);
2441 
2442 /*
2443  * memory_region_set_address: dynamically update the address of a region
2444  *
2445  * Dynamically updates the address of a region, relative to its container.
2446  * May be used on regions are currently part of a memory hierarchy.
2447  *
2448  * @mr: the region to be updated
2449  * @addr: new address, relative to container region
2450  */
2451 void memory_region_set_address(MemoryRegion *mr, hwaddr addr);
2452 
2453 /*
2454  * memory_region_set_size: dynamically update the size of a region.
2455  *
2456  * Dynamically updates the size of a region.
2457  *
2458  * @mr: the region to be updated
2459  * @size: used size of the region.
2460  */
2461 void memory_region_set_size(MemoryRegion *mr, uint64_t size);
2462 
2463 /*
2464  * memory_region_set_alias_offset: dynamically update a memory alias's offset
2465  *
2466  * Dynamically updates the offset into the target region that an alias points
2467  * to, as if the fourth argument to memory_region_init_alias() has changed.
2468  *
2469  * @mr: the #MemoryRegion to be updated; should be an alias.
2470  * @offset: the new offset into the target memory region
2471  */
2472 void memory_region_set_alias_offset(MemoryRegion *mr,
2473                                     hwaddr offset);
2474 
2475 /*
2476  * memory_region_set_unmergeable: Set a memory region unmergeable
2477  *
2478  * Mark a memory region unmergeable, resulting in the memory region (or
2479  * everything contained in a memory region container) not getting merged when
2480  * simplifying the address space and notifying memory listeners. Consequently,
2481  * memory listeners will never get notified about ranges that are larger than
2482  * the original memory regions.
2483  *
2484  * This is primarily useful when multiple aliases to a RAM memory region are
2485  * mapped into a memory region container, and updates (e.g., enable/disable or
2486  * map/unmap) of individual memory region aliases are not supposed to affect
2487  * other memory regions in the same container.
2488  *
2489  * @mr: the #MemoryRegion to be updated
2490  * @unmergeable: whether to mark the #MemoryRegion unmergeable
2491  */
2492 void memory_region_set_unmergeable(MemoryRegion *mr, bool unmergeable);
2493 
2494 /**
2495  * memory_region_present: checks if an address relative to a @container
2496  * translates into #MemoryRegion within @container
2497  *
2498  * Answer whether a #MemoryRegion within @container covers the address
2499  * @addr.
2500  *
2501  * @container: a #MemoryRegion within which @addr is a relative address
2502  * @addr: the area within @container to be searched
2503  */
2504 bool memory_region_present(MemoryRegion *container, hwaddr addr);
2505 
2506 /**
2507  * memory_region_is_mapped: returns true if #MemoryRegion is mapped
2508  * into another memory region, which does not necessarily imply that it is
2509  * mapped into an address space.
2510  *
2511  * @mr: a #MemoryRegion which should be checked if it's mapped
2512  */
2513 bool memory_region_is_mapped(MemoryRegion *mr);
2514 
2515 /**
2516  * memory_region_get_ram_discard_manager: get the #RamDiscardManager for a
2517  * #MemoryRegion
2518  *
2519  * The #RamDiscardManager cannot change while a memory region is mapped.
2520  *
2521  * @mr: the #MemoryRegion
2522  */
2523 RamDiscardManager *memory_region_get_ram_discard_manager(MemoryRegion *mr);
2524 
2525 /**
2526  * memory_region_has_ram_discard_manager: check whether a #MemoryRegion has a
2527  * #RamDiscardManager assigned
2528  *
2529  * @mr: the #MemoryRegion
2530  */
memory_region_has_ram_discard_manager(MemoryRegion * mr)2531 static inline bool memory_region_has_ram_discard_manager(MemoryRegion *mr)
2532 {
2533     return !!memory_region_get_ram_discard_manager(mr);
2534 }
2535 
2536 /**
2537  * memory_region_set_ram_discard_manager: set the #RamDiscardManager for a
2538  * #MemoryRegion
2539  *
2540  * This function must not be called for a mapped #MemoryRegion, a #MemoryRegion
2541  * that does not cover RAM, or a #MemoryRegion that already has a
2542  * #RamDiscardManager assigned. Return 0 if the rdm is set successfully.
2543  *
2544  * @mr: the #MemoryRegion
2545  * @rdm: #RamDiscardManager to set
2546  */
2547 int memory_region_set_ram_discard_manager(MemoryRegion *mr,
2548                                           RamDiscardManager *rdm);
2549 
2550 /**
2551  * memory_region_find: translate an address/size relative to a
2552  * MemoryRegion into a #MemoryRegionSection.
2553  *
2554  * Locates the first #MemoryRegion within @mr that overlaps the range
2555  * given by @addr and @size.
2556  *
2557  * Returns a #MemoryRegionSection that describes a contiguous overlap.
2558  * It will have the following characteristics:
2559  * - @size = 0 iff no overlap was found
2560  * - @mr is non-%NULL iff an overlap was found
2561  *
2562  * Remember that in the return value the @offset_within_region is
2563  * relative to the returned region (in the .@mr field), not to the
2564  * @mr argument.
2565  *
2566  * Similarly, the .@offset_within_address_space is relative to the
2567  * address space that contains both regions, the passed and the
2568  * returned one.  However, in the special case where the @mr argument
2569  * has no container (and thus is the root of the address space), the
2570  * following will hold:
2571  * - @offset_within_address_space >= @addr
2572  * - @offset_within_address_space + .@size <= @addr + @size
2573  *
2574  * @mr: a MemoryRegion within which @addr is a relative address
2575  * @addr: start of the area within @as to be searched
2576  * @size: size of the area to be searched
2577  */
2578 MemoryRegionSection memory_region_find(MemoryRegion *mr,
2579                                        hwaddr addr, uint64_t size);
2580 
2581 /**
2582  * memory_global_dirty_log_sync: synchronize the dirty log for all memory
2583  *
2584  * Synchronizes the dirty page log for all address spaces.
2585  *
2586  * @last_stage: whether this is the last stage of live migration
2587  */
2588 void memory_global_dirty_log_sync(bool last_stage);
2589 
2590 /**
2591  * memory_global_after_dirty_log_sync: synchronize the dirty log for all memory
2592  *
2593  * Synchronizes the vCPUs with a thread that is reading the dirty bitmap.
2594  * This function must be called after the dirty log bitmap is cleared, and
2595  * before dirty guest memory pages are read.  If you are using
2596  * #DirtyBitmapSnapshot, memory_region_snapshot_and_clear_dirty() takes
2597  * care of doing this.
2598  */
2599 void memory_global_after_dirty_log_sync(void);
2600 
2601 /**
2602  * memory_region_transaction_begin: Start a transaction.
2603  *
2604  * During a transaction, changes will be accumulated and made visible
2605  * only when the transaction ends (is committed).
2606  */
2607 void memory_region_transaction_begin(void);
2608 
2609 /**
2610  * memory_region_transaction_commit: Commit a transaction and make changes
2611  *                                   visible to the guest.
2612  */
2613 void memory_region_transaction_commit(void);
2614 
2615 /**
2616  * memory_listener_register: register callbacks to be called when memory
2617  *                           sections are mapped or unmapped into an address
2618  *                           space
2619  *
2620  * @listener: an object containing the callbacks to be called
2621  * @filter: if non-%NULL, only regions in this address space will be observed
2622  */
2623 void memory_listener_register(MemoryListener *listener, AddressSpace *filter);
2624 
2625 /**
2626  * memory_listener_unregister: undo the effect of memory_listener_register()
2627  *
2628  * @listener: an object containing the callbacks to be removed
2629  */
2630 void memory_listener_unregister(MemoryListener *listener);
2631 
2632 /**
2633  * memory_global_dirty_log_start: begin dirty logging for all regions
2634  *
2635  * @flags: purpose of starting dirty log, migration or dirty rate
2636  * @errp: pointer to Error*, to store an error if it happens.
2637  *
2638  * Return: true on success, else false setting @errp with error.
2639  */
2640 bool memory_global_dirty_log_start(unsigned int flags, Error **errp);
2641 
2642 /**
2643  * memory_global_dirty_log_stop: end dirty logging for all regions
2644  *
2645  * @flags: purpose of stopping dirty log, migration or dirty rate
2646  */
2647 void memory_global_dirty_log_stop(unsigned int flags);
2648 
2649 void mtree_info(bool flatview, bool dispatch_tree, bool owner, bool disabled);
2650 
2651 bool memory_region_access_valid(MemoryRegion *mr, hwaddr addr,
2652                                 unsigned size, bool is_write,
2653                                 MemTxAttrs attrs);
2654 
2655 /**
2656  * memory_region_dispatch_read: perform a read directly to the specified
2657  * MemoryRegion.
2658  *
2659  * @mr: #MemoryRegion to access
2660  * @addr: address within that region
2661  * @pval: pointer to uint64_t which the data is written to
2662  * @op: size, sign, and endianness of the memory operation
2663  * @attrs: memory transaction attributes to use for the access
2664  */
2665 MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
2666                                         hwaddr addr,
2667                                         uint64_t *pval,
2668                                         MemOp op,
2669                                         MemTxAttrs attrs);
2670 /**
2671  * memory_region_dispatch_write: perform a write directly to the specified
2672  * MemoryRegion.
2673  *
2674  * @mr: #MemoryRegion to access
2675  * @addr: address within that region
2676  * @data: data to write
2677  * @op: size, sign, and endianness of the memory operation
2678  * @attrs: memory transaction attributes to use for the access
2679  */
2680 MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
2681                                          hwaddr addr,
2682                                          uint64_t data,
2683                                          MemOp op,
2684                                          MemTxAttrs attrs);
2685 
2686 /**
2687  * address_space_init: initializes an address space
2688  *
2689  * @as: an uninitialized #AddressSpace
2690  * @root: a #MemoryRegion that routes addresses for the address space
2691  * @name: an address space name.  The name is only used for debugging
2692  *        output.
2693  */
2694 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name);
2695 
2696 /**
2697  * address_space_destroy: destroy an address space
2698  *
2699  * Releases all resources associated with an address space.  After an address space
2700  * is destroyed, its root memory region (given by address_space_init()) may be destroyed
2701  * as well.
2702  *
2703  * @as: address space to be destroyed
2704  */
2705 void address_space_destroy(AddressSpace *as);
2706 
2707 /**
2708  * address_space_remove_listeners: unregister all listeners of an address space
2709  *
2710  * Removes all callbacks previously registered with memory_listener_register()
2711  * for @as.
2712  *
2713  * @as: an initialized #AddressSpace
2714  */
2715 void address_space_remove_listeners(AddressSpace *as);
2716 
2717 /**
2718  * address_space_rw: read from or write to an address space.
2719  *
2720  * Return a MemTxResult indicating whether the operation succeeded
2721  * or failed (eg unassigned memory, device rejected the transaction,
2722  * IOMMU fault).
2723  *
2724  * @as: #AddressSpace to be accessed
2725  * @addr: address within that address space
2726  * @attrs: memory transaction attributes
2727  * @buf: buffer with the data transferred
2728  * @len: the number of bytes to read or write
2729  * @is_write: indicates the transfer direction
2730  */
2731 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr,
2732                              MemTxAttrs attrs, void *buf,
2733                              hwaddr len, bool is_write);
2734 
2735 /**
2736  * address_space_write: write to address space.
2737  *
2738  * Return a MemTxResult indicating whether the operation succeeded
2739  * or failed (eg unassigned memory, device rejected the transaction,
2740  * IOMMU fault).
2741  *
2742  * @as: #AddressSpace to be accessed
2743  * @addr: address within that address space
2744  * @attrs: memory transaction attributes
2745  * @buf: buffer with the data transferred
2746  * @len: the number of bytes to write
2747  */
2748 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2749                                 MemTxAttrs attrs,
2750                                 const void *buf, hwaddr len);
2751 
2752 /**
2753  * address_space_write_rom: write to address space, including ROM.
2754  *
2755  * This function writes to the specified address space, but will
2756  * write data to both ROM and RAM. This is used for non-guest
2757  * writes like writes from the gdb debug stub or initial loading
2758  * of ROM contents.
2759  *
2760  * Note that portions of the write which attempt to write data to
2761  * a device will be silently ignored -- only real RAM and ROM will
2762  * be written to.
2763  *
2764  * Return a MemTxResult indicating whether the operation succeeded
2765  * or failed (eg unassigned memory, device rejected the transaction,
2766  * IOMMU fault).
2767  *
2768  * @as: #AddressSpace to be accessed
2769  * @addr: address within that address space
2770  * @attrs: memory transaction attributes
2771  * @buf: buffer with the data transferred
2772  * @len: the number of bytes to write
2773  */
2774 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
2775                                     MemTxAttrs attrs,
2776                                     const void *buf, hwaddr len);
2777 
2778 /* address_space_ld*: load from an address space
2779  * address_space_st*: store to an address space
2780  *
2781  * These functions perform a load or store of the byte, word,
2782  * longword or quad to the specified address within the AddressSpace.
2783  * The _le suffixed functions treat the data as little endian;
2784  * _be indicates big endian; no suffix indicates "same endianness
2785  * as guest CPU".
2786  *
2787  * The "guest CPU endianness" accessors are deprecated for use outside
2788  * target-* code; devices should be CPU-agnostic and use either the LE
2789  * or the BE accessors.
2790  *
2791  * @as #AddressSpace to be accessed
2792  * @addr: address within that address space
2793  * @val: data value, for stores
2794  * @attrs: memory transaction attributes
2795  * @result: location to write the success/failure of the transaction;
2796  *   if NULL, this information is discarded
2797  */
2798 
2799 #define SUFFIX
2800 #define ARG1         as
2801 #define ARG1_DECL    AddressSpace *as
2802 #include "exec/memory_ldst.h.inc"
2803 
stl_phys_notdirty(AddressSpace * as,hwaddr addr,uint32_t val)2804 static inline void stl_phys_notdirty(AddressSpace *as, hwaddr addr, uint32_t val)
2805 {
2806     address_space_stl_notdirty(as, addr, val,
2807                                MEMTXATTRS_UNSPECIFIED, NULL);
2808 }
2809 
2810 #define SUFFIX
2811 #define ARG1         as
2812 #define ARG1_DECL    AddressSpace *as
2813 #include "exec/memory_ldst_phys.h.inc"
2814 
2815 struct MemoryRegionCache {
2816     uint8_t *ptr;
2817     hwaddr xlat;
2818     hwaddr len;
2819     FlatView *fv;
2820     MemoryRegionSection mrs;
2821     bool is_write;
2822 };
2823 
2824 /* address_space_ld*_cached: load from a cached #MemoryRegion
2825  * address_space_st*_cached: store into a cached #MemoryRegion
2826  *
2827  * These functions perform a load or store of the byte, word,
2828  * longword or quad to the specified address.  The address is
2829  * a physical address in the AddressSpace, but it must lie within
2830  * a #MemoryRegion that was mapped with address_space_cache_init.
2831  *
2832  * The _le suffixed functions treat the data as little endian;
2833  * _be indicates big endian; no suffix indicates "same endianness
2834  * as guest CPU".
2835  *
2836  * The "guest CPU endianness" accessors are deprecated for use outside
2837  * target-* code; devices should be CPU-agnostic and use either the LE
2838  * or the BE accessors.
2839  *
2840  * @cache: previously initialized #MemoryRegionCache to be accessed
2841  * @addr: address within the address space
2842  * @val: data value, for stores
2843  * @attrs: memory transaction attributes
2844  * @result: location to write the success/failure of the transaction;
2845  *   if NULL, this information is discarded
2846  */
2847 
2848 #define SUFFIX       _cached_slow
2849 #define ARG1         cache
2850 #define ARG1_DECL    MemoryRegionCache *cache
2851 #include "exec/memory_ldst.h.inc"
2852 
2853 /* Inline fast path for direct RAM access.  */
address_space_ldub_cached(MemoryRegionCache * cache,hwaddr addr,MemTxAttrs attrs,MemTxResult * result)2854 static inline uint8_t address_space_ldub_cached(MemoryRegionCache *cache,
2855     hwaddr addr, MemTxAttrs attrs, MemTxResult *result)
2856 {
2857     assert(addr < cache->len);
2858     if (likely(cache->ptr)) {
2859         return ldub_p(cache->ptr + addr);
2860     } else {
2861         return address_space_ldub_cached_slow(cache, addr, attrs, result);
2862     }
2863 }
2864 
address_space_stb_cached(MemoryRegionCache * cache,hwaddr addr,uint8_t val,MemTxAttrs attrs,MemTxResult * result)2865 static inline void address_space_stb_cached(MemoryRegionCache *cache,
2866     hwaddr addr, uint8_t val, MemTxAttrs attrs, MemTxResult *result)
2867 {
2868     assert(addr < cache->len);
2869     if (likely(cache->ptr)) {
2870         stb_p(cache->ptr + addr, val);
2871     } else {
2872         address_space_stb_cached_slow(cache, addr, val, attrs, result);
2873     }
2874 }
2875 
2876 #define ENDIANNESS
2877 #include "exec/memory_ldst_cached.h.inc"
2878 
2879 #define ENDIANNESS   _le
2880 #include "exec/memory_ldst_cached.h.inc"
2881 
2882 #define ENDIANNESS   _be
2883 #include "exec/memory_ldst_cached.h.inc"
2884 
2885 #define SUFFIX       _cached
2886 #define ARG1         cache
2887 #define ARG1_DECL    MemoryRegionCache *cache
2888 #include "exec/memory_ldst_phys.h.inc"
2889 
2890 /* address_space_cache_init: prepare for repeated access to a physical
2891  * memory region
2892  *
2893  * @cache: #MemoryRegionCache to be filled
2894  * @as: #AddressSpace to be accessed
2895  * @addr: address within that address space
2896  * @len: length of buffer
2897  * @is_write: indicates the transfer direction
2898  *
2899  * Will only work with RAM, and may map a subset of the requested range by
2900  * returning a value that is less than @len.  On failure, return a negative
2901  * errno value.
2902  *
2903  * Because it only works with RAM, this function can be used for
2904  * read-modify-write operations.  In this case, is_write should be %true.
2905  *
2906  * Note that addresses passed to the address_space_*_cached functions
2907  * are relative to @addr.
2908  */
2909 int64_t address_space_cache_init(MemoryRegionCache *cache,
2910                                  AddressSpace *as,
2911                                  hwaddr addr,
2912                                  hwaddr len,
2913                                  bool is_write);
2914 
2915 /**
2916  * address_space_cache_init_empty: Initialize empty #MemoryRegionCache
2917  *
2918  * @cache: The #MemoryRegionCache to operate on.
2919  *
2920  * Initializes #MemoryRegionCache structure without memory region attached.
2921  * Cache initialized this way can only be safely destroyed, but not used.
2922  */
address_space_cache_init_empty(MemoryRegionCache * cache)2923 static inline void address_space_cache_init_empty(MemoryRegionCache *cache)
2924 {
2925     cache->mrs.mr = NULL;
2926     /* There is no real need to initialize fv, but it makes Coverity happy. */
2927     cache->fv = NULL;
2928 }
2929 
2930 /**
2931  * address_space_cache_invalidate: complete a write to a #MemoryRegionCache
2932  *
2933  * @cache: The #MemoryRegionCache to operate on.
2934  * @addr: The first physical address that was written, relative to the
2935  * address that was passed to @address_space_cache_init.
2936  * @access_len: The number of bytes that were written starting at @addr.
2937  */
2938 void address_space_cache_invalidate(MemoryRegionCache *cache,
2939                                     hwaddr addr,
2940                                     hwaddr access_len);
2941 
2942 /**
2943  * address_space_cache_destroy: free a #MemoryRegionCache
2944  *
2945  * @cache: The #MemoryRegionCache whose memory should be released.
2946  */
2947 void address_space_cache_destroy(MemoryRegionCache *cache);
2948 
2949 /* address_space_get_iotlb_entry: translate an address into an IOTLB
2950  * entry. Should be called from an RCU critical section.
2951  */
2952 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
2953                                             bool is_write, MemTxAttrs attrs);
2954 
2955 /* address_space_translate: translate an address range into an address space
2956  * into a MemoryRegion and an address range into that section.  Should be
2957  * called from an RCU critical section, to avoid that the last reference
2958  * to the returned region disappears after address_space_translate returns.
2959  *
2960  * @fv: #FlatView to be accessed
2961  * @addr: address within that address space
2962  * @xlat: pointer to address within the returned memory region section's
2963  * #MemoryRegion.
2964  * @len: pointer to length
2965  * @is_write: indicates the transfer direction
2966  * @attrs: memory attributes
2967  */
2968 MemoryRegion *flatview_translate(FlatView *fv,
2969                                  hwaddr addr, hwaddr *xlat,
2970                                  hwaddr *len, bool is_write,
2971                                  MemTxAttrs attrs);
2972 
address_space_translate(AddressSpace * as,hwaddr addr,hwaddr * xlat,hwaddr * len,bool is_write,MemTxAttrs attrs)2973 static inline MemoryRegion *address_space_translate(AddressSpace *as,
2974                                                     hwaddr addr, hwaddr *xlat,
2975                                                     hwaddr *len, bool is_write,
2976                                                     MemTxAttrs attrs)
2977 {
2978     return flatview_translate(address_space_to_flatview(as),
2979                               addr, xlat, len, is_write, attrs);
2980 }
2981 
2982 /* address_space_access_valid: check for validity of accessing an address
2983  * space range
2984  *
2985  * Check whether memory is assigned to the given address space range, and
2986  * access is permitted by any IOMMU regions that are active for the address
2987  * space.
2988  *
2989  * For now, addr and len should be aligned to a page size.  This limitation
2990  * will be lifted in the future.
2991  *
2992  * @as: #AddressSpace to be accessed
2993  * @addr: address within that address space
2994  * @len: length of the area to be checked
2995  * @is_write: indicates the transfer direction
2996  * @attrs: memory attributes
2997  */
2998 bool address_space_access_valid(AddressSpace *as, hwaddr addr, hwaddr len,
2999                                 bool is_write, MemTxAttrs attrs);
3000 
3001 /* address_space_map: map a physical memory region into a host virtual address
3002  *
3003  * May map a subset of the requested range, given by and returned in @plen.
3004  * May return %NULL and set *@plen to zero(0), if resources needed to perform
3005  * the mapping are exhausted.
3006  * Use only for reads OR writes - not for read-modify-write operations.
3007  * Use address_space_register_map_client() to know when retrying the map
3008  * operation is likely to succeed.
3009  *
3010  * @as: #AddressSpace to be accessed
3011  * @addr: address within that address space
3012  * @plen: pointer to length of buffer; updated on return
3013  * @is_write: indicates the transfer direction
3014  * @attrs: memory attributes
3015  */
3016 void *address_space_map(AddressSpace *as, hwaddr addr,
3017                         hwaddr *plen, bool is_write, MemTxAttrs attrs);
3018 
3019 /* address_space_unmap: Unmaps a memory region previously mapped by address_space_map()
3020  *
3021  * Will also mark the memory as dirty if @is_write == %true.  @access_len gives
3022  * the amount of memory that was actually read or written by the caller.
3023  *
3024  * @as: #AddressSpace used
3025  * @buffer: host pointer as returned by address_space_map()
3026  * @len: buffer length as returned by address_space_map()
3027  * @access_len: amount of data actually transferred
3028  * @is_write: indicates the transfer direction
3029  */
3030 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3031                          bool is_write, hwaddr access_len);
3032 
3033 /*
3034  * address_space_register_map_client: Register a callback to invoke when
3035  * resources for address_space_map() are available again.
3036  *
3037  * address_space_map may fail when there are not enough resources available,
3038  * such as when bounce buffer memory would exceed the limit. The callback can
3039  * be used to retry the address_space_map operation. Note that the callback
3040  * gets automatically removed after firing.
3041  *
3042  * @as: #AddressSpace to be accessed
3043  * @bh: callback to invoke when address_space_map() retry is appropriate
3044  */
3045 void address_space_register_map_client(AddressSpace *as, QEMUBH *bh);
3046 
3047 /*
3048  * address_space_unregister_map_client: Unregister a callback that has
3049  * previously been registered and not fired yet.
3050  *
3051  * @as: #AddressSpace to be accessed
3052  * @bh: callback to unregister
3053  */
3054 void address_space_unregister_map_client(AddressSpace *as, QEMUBH *bh);
3055 
3056 /* Internal functions, part of the implementation of address_space_read.  */
3057 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3058                                     MemTxAttrs attrs, void *buf, hwaddr len);
3059 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
3060                                    MemTxAttrs attrs, void *buf,
3061                                    hwaddr len, hwaddr addr1, hwaddr l,
3062                                    MemoryRegion *mr);
3063 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr);
3064 
3065 /* Internal functions, part of the implementation of address_space_read_cached
3066  * and address_space_write_cached.  */
3067 MemTxResult address_space_read_cached_slow(MemoryRegionCache *cache,
3068                                            hwaddr addr, void *buf, hwaddr len);
3069 MemTxResult address_space_write_cached_slow(MemoryRegionCache *cache,
3070                                             hwaddr addr, const void *buf,
3071                                             hwaddr len);
3072 
3073 int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr);
3074 bool prepare_mmio_access(MemoryRegion *mr);
3075 
memory_region_supports_direct_access(MemoryRegion * mr)3076 static inline bool memory_region_supports_direct_access(MemoryRegion *mr)
3077 {
3078     /* ROM DEVICE regions only allow direct access if in ROMD mode. */
3079     if (memory_region_is_romd(mr)) {
3080         return true;
3081     }
3082     if (!memory_region_is_ram(mr)) {
3083         return false;
3084     }
3085     /*
3086      * RAM DEVICE regions can be accessed directly using memcpy, but it might
3087      * be MMIO and access using mempy can be wrong (e.g., using instructions not
3088      * intended for MMIO access). So we treat this as IO.
3089      */
3090     return !memory_region_is_ram_device(mr);
3091 }
3092 
memory_access_is_direct(MemoryRegion * mr,bool is_write,MemTxAttrs attrs)3093 static inline bool memory_access_is_direct(MemoryRegion *mr, bool is_write,
3094                                            MemTxAttrs attrs)
3095 {
3096     if (!memory_region_supports_direct_access(mr)) {
3097         return false;
3098     }
3099     /* Debug access can write to ROM. */
3100     if (is_write && !attrs.debug) {
3101         return !mr->readonly && !mr->rom_device;
3102     }
3103     return true;
3104 }
3105 
3106 /**
3107  * address_space_read: read from an address space.
3108  *
3109  * Return a MemTxResult indicating whether the operation succeeded
3110  * or failed (eg unassigned memory, device rejected the transaction,
3111  * IOMMU fault).  Called within RCU critical section.
3112  *
3113  * @as: #AddressSpace to be accessed
3114  * @addr: address within that address space
3115  * @attrs: memory transaction attributes
3116  * @buf: buffer with the data transferred
3117  * @len: length of the data transferred
3118  */
3119 static inline __attribute__((__always_inline__))
address_space_read(AddressSpace * as,hwaddr addr,MemTxAttrs attrs,void * buf,hwaddr len)3120 MemTxResult address_space_read(AddressSpace *as, hwaddr addr,
3121                                MemTxAttrs attrs, void *buf,
3122                                hwaddr len)
3123 {
3124     MemTxResult result = MEMTX_OK;
3125     hwaddr l, addr1;
3126     void *ptr;
3127     MemoryRegion *mr;
3128     FlatView *fv;
3129 
3130     if (__builtin_constant_p(len)) {
3131         if (len) {
3132             RCU_READ_LOCK_GUARD();
3133             fv = address_space_to_flatview(as);
3134             l = len;
3135             mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
3136             if (len == l && memory_access_is_direct(mr, false, attrs)) {
3137                 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3138                 memcpy(buf, ptr, len);
3139             } else {
3140                 result = flatview_read_continue(fv, addr, attrs, buf, len,
3141                                                 addr1, l, mr);
3142             }
3143         }
3144     } else {
3145         result = address_space_read_full(as, addr, attrs, buf, len);
3146     }
3147     return result;
3148 }
3149 
3150 /**
3151  * address_space_read_cached: read from a cached RAM region
3152  *
3153  * @cache: Cached region to be addressed
3154  * @addr: address relative to the base of the RAM region
3155  * @buf: buffer with the data transferred
3156  * @len: length of the data transferred
3157  */
3158 static inline MemTxResult
address_space_read_cached(MemoryRegionCache * cache,hwaddr addr,void * buf,hwaddr len)3159 address_space_read_cached(MemoryRegionCache *cache, hwaddr addr,
3160                           void *buf, hwaddr len)
3161 {
3162     assert(addr < cache->len && len <= cache->len - addr);
3163     fuzz_dma_read_cb(cache->xlat + addr, len, cache->mrs.mr);
3164     if (likely(cache->ptr)) {
3165         memcpy(buf, cache->ptr + addr, len);
3166         return MEMTX_OK;
3167     } else {
3168         return address_space_read_cached_slow(cache, addr, buf, len);
3169     }
3170 }
3171 
3172 /**
3173  * address_space_write_cached: write to a cached RAM region
3174  *
3175  * @cache: Cached region to be addressed
3176  * @addr: address relative to the base of the RAM region
3177  * @buf: buffer with the data transferred
3178  * @len: length of the data transferred
3179  */
3180 static inline MemTxResult
address_space_write_cached(MemoryRegionCache * cache,hwaddr addr,const void * buf,hwaddr len)3181 address_space_write_cached(MemoryRegionCache *cache, hwaddr addr,
3182                            const void *buf, hwaddr len)
3183 {
3184     assert(addr < cache->len && len <= cache->len - addr);
3185     if (likely(cache->ptr)) {
3186         memcpy(cache->ptr + addr, buf, len);
3187         return MEMTX_OK;
3188     } else {
3189         return address_space_write_cached_slow(cache, addr, buf, len);
3190     }
3191 }
3192 
3193 /**
3194  * address_space_set: Fill address space with a constant byte.
3195  *
3196  * Return a MemTxResult indicating whether the operation succeeded
3197  * or failed (eg unassigned memory, device rejected the transaction,
3198  * IOMMU fault).
3199  *
3200  * @as: #AddressSpace to be accessed
3201  * @addr: address within that address space
3202  * @c: constant byte to fill the memory
3203  * @len: the number of bytes to fill with the constant byte
3204  * @attrs: memory transaction attributes
3205  */
3206 MemTxResult address_space_set(AddressSpace *as, hwaddr addr,
3207                               uint8_t c, hwaddr len, MemTxAttrs attrs);
3208 
3209 /*
3210  * Inhibit technologies that require discarding of pages in RAM blocks, e.g.,
3211  * to manage the actual amount of memory consumed by the VM (then, the memory
3212  * provided by RAM blocks might be bigger than the desired memory consumption).
3213  * This *must* be set if:
3214  * - Discarding parts of a RAM blocks does not result in the change being
3215  *   reflected in the VM and the pages getting freed.
3216  * - All memory in RAM blocks is pinned or duplicated, invaldiating any previous
3217  *   discards blindly.
3218  * - Discarding parts of a RAM blocks will result in integrity issues (e.g.,
3219  *   encrypted VMs).
3220  * Technologies that only temporarily pin the current working set of a
3221  * driver are fine, because we don't expect such pages to be discarded
3222  * (esp. based on guest action like balloon inflation).
3223  *
3224  * This is *not* to be used to protect from concurrent discards (esp.,
3225  * postcopy).
3226  *
3227  * Returns 0 if successful. Returns -EBUSY if a technology that relies on
3228  * discards to work reliably is active.
3229  */
3230 int ram_block_discard_disable(bool state);
3231 
3232 /*
3233  * See ram_block_discard_disable(): only disable uncoordinated discards,
3234  * keeping coordinated discards (via the RamDiscardManager) enabled.
3235  */
3236 int ram_block_uncoordinated_discard_disable(bool state);
3237 
3238 /*
3239  * Inhibit technologies that disable discarding of pages in RAM blocks.
3240  *
3241  * Returns 0 if successful. Returns -EBUSY if discards are already set to
3242  * broken.
3243  */
3244 int ram_block_discard_require(bool state);
3245 
3246 /*
3247  * See ram_block_discard_require(): only inhibit technologies that disable
3248  * uncoordinated discarding of pages in RAM blocks, allowing co-existence with
3249  * technologies that only inhibit uncoordinated discards (via the
3250  * RamDiscardManager).
3251  */
3252 int ram_block_coordinated_discard_require(bool state);
3253 
3254 /*
3255  * Test if any discarding of memory in ram blocks is disabled.
3256  */
3257 bool ram_block_discard_is_disabled(void);
3258 
3259 /*
3260  * Test if any discarding of memory in ram blocks is required to work reliably.
3261  */
3262 bool ram_block_discard_is_required(void);
3263 
3264 void ram_block_add_cpr_blocker(RAMBlock *rb, Error **errp);
3265 void ram_block_del_cpr_blocker(RAMBlock *rb);
3266 
3267 #endif
3268