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