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