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