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