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