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