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