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