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