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