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