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