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