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