xref: /qemu/include/exec/memory.h (revision 2e8f72ac)
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  * @errp: pointer to Error*, to store an error if it happens.
970  *
971  * Note that this function does not do anything to cause the data in the
972  * RAM memory region to be migrated; that is the responsibility of the caller.
973  */
974 void memory_region_init_ram_from_file(MemoryRegion *mr,
975                                       struct Object *owner,
976                                       const char *name,
977                                       uint64_t size,
978                                       uint64_t align,
979                                       uint32_t ram_flags,
980                                       const char *path,
981                                       Error **errp);
982 
983 /**
984  * memory_region_init_ram_from_fd:  Initialize RAM memory region with a
985  *                                  mmap-ed backend.
986  *
987  * @mr: the #MemoryRegion to be initialized.
988  * @owner: the object that tracks the region's reference count
989  * @name: the name of the region.
990  * @size: size of the region.
991  * @share: %true if memory must be mmaped with the MAP_SHARED flag
992  * @fd: the fd to mmap.
993  * @errp: pointer to Error*, to store an error if it happens.
994  *
995  * Note that this function does not do anything to cause the data in the
996  * RAM memory region to be migrated; that is the responsibility of the caller.
997  */
998 void memory_region_init_ram_from_fd(MemoryRegion *mr,
999                                     struct Object *owner,
1000                                     const char *name,
1001                                     uint64_t size,
1002                                     bool share,
1003                                     int fd,
1004                                     Error **errp);
1005 #endif
1006 
1007 /**
1008  * memory_region_init_ram_ptr:  Initialize RAM memory region from a
1009  *                              user-provided pointer.  Accesses into the
1010  *                              region will modify memory directly.
1011  *
1012  * @mr: the #MemoryRegion to be initialized.
1013  * @owner: the object that tracks the region's reference count
1014  * @name: Region name, becomes part of RAMBlock name used in migration stream
1015  *        must be unique within any device
1016  * @size: size of the region.
1017  * @ptr: memory to be mapped; must contain at least @size bytes.
1018  *
1019  * Note that this function does not do anything to cause the data in the
1020  * RAM memory region to be migrated; that is the responsibility of the caller.
1021  */
1022 void memory_region_init_ram_ptr(MemoryRegion *mr,
1023                                 struct Object *owner,
1024                                 const char *name,
1025                                 uint64_t size,
1026                                 void *ptr);
1027 
1028 /**
1029  * memory_region_init_ram_device_ptr:  Initialize RAM device memory region from
1030  *                                     a user-provided pointer.
1031  *
1032  * A RAM device represents a mapping to a physical device, such as to a PCI
1033  * MMIO BAR of an vfio-pci assigned device.  The memory region may be mapped
1034  * into the VM address space and access to the region will modify memory
1035  * directly.  However, the memory region should not be included in a memory
1036  * dump (device may not be enabled/mapped at the time of the dump), and
1037  * operations incompatible with manipulating MMIO should be avoided.  Replaces
1038  * skip_dump flag.
1039  *
1040  * @mr: the #MemoryRegion to be initialized.
1041  * @owner: the object that tracks the region's reference count
1042  * @name: the name of the region.
1043  * @size: size of the region.
1044  * @ptr: memory to be mapped; must contain at least @size bytes.
1045  *
1046  * Note that this function does not do anything to cause the data in the
1047  * RAM memory region to be migrated; that is the responsibility of the caller.
1048  * (For RAM device memory regions, migrating the contents rarely makes sense.)
1049  */
1050 void memory_region_init_ram_device_ptr(MemoryRegion *mr,
1051                                        struct Object *owner,
1052                                        const char *name,
1053                                        uint64_t size,
1054                                        void *ptr);
1055 
1056 /**
1057  * memory_region_init_alias: Initialize a memory region that aliases all or a
1058  *                           part of another memory region.
1059  *
1060  * @mr: the #MemoryRegion to be initialized.
1061  * @owner: the object that tracks the region's reference count
1062  * @name: used for debugging; not visible to the user or ABI
1063  * @orig: the region to be referenced; @mr will be equivalent to
1064  *        @orig between @offset and @offset + @size - 1.
1065  * @offset: start of the section in @orig to be referenced.
1066  * @size: size of the region.
1067  */
1068 void memory_region_init_alias(MemoryRegion *mr,
1069                               struct Object *owner,
1070                               const char *name,
1071                               MemoryRegion *orig,
1072                               hwaddr offset,
1073                               uint64_t size);
1074 
1075 /**
1076  * memory_region_init_rom_nomigrate: Initialize a ROM memory region.
1077  *
1078  * This has the same effect as calling memory_region_init_ram_nomigrate()
1079  * and then marking the resulting region read-only with
1080  * memory_region_set_readonly().
1081  *
1082  * Note that this function does not do anything to cause the data in the
1083  * RAM side of the memory region to be migrated; that is the responsibility
1084  * of the caller.
1085  *
1086  * @mr: the #MemoryRegion to be initialized.
1087  * @owner: the object that tracks the region's reference count
1088  * @name: Region name, becomes part of RAMBlock name used in migration stream
1089  *        must be unique within any device
1090  * @size: size of the region.
1091  * @errp: pointer to Error*, to store an error if it happens.
1092  */
1093 void memory_region_init_rom_nomigrate(MemoryRegion *mr,
1094                                       struct Object *owner,
1095                                       const char *name,
1096                                       uint64_t size,
1097                                       Error **errp);
1098 
1099 /**
1100  * memory_region_init_rom_device_nomigrate:  Initialize a ROM memory region.
1101  *                                 Writes are handled via callbacks.
1102  *
1103  * Note that this function does not do anything to cause the data in the
1104  * RAM side of the memory region to be migrated; that is the responsibility
1105  * of the caller.
1106  *
1107  * @mr: the #MemoryRegion to be initialized.
1108  * @owner: the object that tracks the region's reference count
1109  * @ops: callbacks for write access handling (must not be NULL).
1110  * @opaque: passed to the read and write callbacks of the @ops structure.
1111  * @name: Region name, becomes part of RAMBlock name used in migration stream
1112  *        must be unique within any device
1113  * @size: size of the region.
1114  * @errp: pointer to Error*, to store an error if it happens.
1115  */
1116 void memory_region_init_rom_device_nomigrate(MemoryRegion *mr,
1117                                              struct Object *owner,
1118                                              const MemoryRegionOps *ops,
1119                                              void *opaque,
1120                                              const char *name,
1121                                              uint64_t size,
1122                                              Error **errp);
1123 
1124 /**
1125  * memory_region_init_iommu: Initialize a memory region of a custom type
1126  * that translates addresses
1127  *
1128  * An IOMMU region translates addresses and forwards accesses to a target
1129  * memory region.
1130  *
1131  * The IOMMU implementation must define a subclass of TYPE_IOMMU_MEMORY_REGION.
1132  * @_iommu_mr should be a pointer to enough memory for an instance of
1133  * that subclass, @instance_size is the size of that subclass, and
1134  * @mrtypename is its name. This function will initialize @_iommu_mr as an
1135  * instance of the subclass, and its methods will then be called to handle
1136  * accesses to the memory region. See the documentation of
1137  * #IOMMUMemoryRegionClass for further details.
1138  *
1139  * @_iommu_mr: the #IOMMUMemoryRegion to be initialized
1140  * @instance_size: the IOMMUMemoryRegion subclass instance size
1141  * @mrtypename: the type name of the #IOMMUMemoryRegion
1142  * @owner: the object that tracks the region's reference count
1143  * @name: used for debugging; not visible to the user or ABI
1144  * @size: size of the region.
1145  */
1146 void memory_region_init_iommu(void *_iommu_mr,
1147                               size_t instance_size,
1148                               const char *mrtypename,
1149                               Object *owner,
1150                               const char *name,
1151                               uint64_t size);
1152 
1153 /**
1154  * memory_region_init_ram - Initialize RAM memory region.  Accesses into the
1155  *                          region will modify memory directly.
1156  *
1157  * @mr: the #MemoryRegion to be initialized
1158  * @owner: the object that tracks the region's reference count (must be
1159  *         TYPE_DEVICE or a subclass of TYPE_DEVICE, or NULL)
1160  * @name: name of the memory region
1161  * @size: size of the region in bytes
1162  * @errp: pointer to Error*, to store an error if it happens.
1163  *
1164  * This function allocates RAM for a board model or device, and
1165  * arranges for it to be migrated (by calling vmstate_register_ram()
1166  * if @owner is a DeviceState, or vmstate_register_ram_global() if
1167  * @owner is NULL).
1168  *
1169  * TODO: Currently we restrict @owner to being either NULL (for
1170  * global RAM regions with no owner) or devices, so that we can
1171  * give the RAM block a unique name for migration purposes.
1172  * We should lift this restriction and allow arbitrary Objects.
1173  * If you pass a non-NULL non-device @owner then we will assert.
1174  */
1175 void memory_region_init_ram(MemoryRegion *mr,
1176                             struct Object *owner,
1177                             const char *name,
1178                             uint64_t size,
1179                             Error **errp);
1180 
1181 /**
1182  * memory_region_init_rom: Initialize a ROM memory region.
1183  *
1184  * This has the same effect as calling memory_region_init_ram()
1185  * and then marking the resulting region read-only with
1186  * memory_region_set_readonly(). This includes arranging for the
1187  * contents to be migrated.
1188  *
1189  * TODO: Currently we restrict @owner to being either NULL (for
1190  * global RAM regions with no owner) or devices, so that we can
1191  * give the RAM block a unique name for migration purposes.
1192  * We should lift this restriction and allow arbitrary Objects.
1193  * If you pass a non-NULL non-device @owner then we will assert.
1194  *
1195  * @mr: the #MemoryRegion to be initialized.
1196  * @owner: the object that tracks the region's reference count
1197  * @name: Region name, becomes part of RAMBlock name used in migration stream
1198  *        must be unique within any device
1199  * @size: size of the region.
1200  * @errp: pointer to Error*, to store an error if it happens.
1201  */
1202 void memory_region_init_rom(MemoryRegion *mr,
1203                             struct Object *owner,
1204                             const char *name,
1205                             uint64_t size,
1206                             Error **errp);
1207 
1208 /**
1209  * memory_region_init_rom_device:  Initialize a ROM memory region.
1210  *                                 Writes are handled via callbacks.
1211  *
1212  * This function initializes a memory region backed by RAM for reads
1213  * and callbacks for writes, and arranges for the RAM backing to
1214  * be migrated (by calling vmstate_register_ram()
1215  * if @owner is a DeviceState, or vmstate_register_ram_global() if
1216  * @owner is NULL).
1217  *
1218  * TODO: Currently we restrict @owner to being either NULL (for
1219  * global RAM regions with no owner) or devices, so that we can
1220  * give the RAM block a unique name for migration purposes.
1221  * We should lift this restriction and allow arbitrary Objects.
1222  * If you pass a non-NULL non-device @owner then we will assert.
1223  *
1224  * @mr: the #MemoryRegion to be initialized.
1225  * @owner: the object that tracks the region's reference count
1226  * @ops: callbacks for write access handling (must not be NULL).
1227  * @opaque: passed to the read and write callbacks of the @ops structure.
1228  * @name: Region name, becomes part of RAMBlock name used in migration stream
1229  *        must be unique within any device
1230  * @size: size of the region.
1231  * @errp: pointer to Error*, to store an error if it happens.
1232  */
1233 void memory_region_init_rom_device(MemoryRegion *mr,
1234                                    struct Object *owner,
1235                                    const MemoryRegionOps *ops,
1236                                    void *opaque,
1237                                    const char *name,
1238                                    uint64_t size,
1239                                    Error **errp);
1240 
1241 
1242 /**
1243  * memory_region_owner: get a memory region's owner.
1244  *
1245  * @mr: the memory region being queried.
1246  */
1247 struct Object *memory_region_owner(MemoryRegion *mr);
1248 
1249 /**
1250  * memory_region_size: get a memory region's size.
1251  *
1252  * @mr: the memory region being queried.
1253  */
1254 uint64_t memory_region_size(MemoryRegion *mr);
1255 
1256 /**
1257  * memory_region_is_ram: check whether a memory region is random access
1258  *
1259  * Returns %true if a memory region is random access.
1260  *
1261  * @mr: the memory region being queried
1262  */
1263 static inline bool memory_region_is_ram(MemoryRegion *mr)
1264 {
1265     return mr->ram;
1266 }
1267 
1268 /**
1269  * memory_region_is_ram_device: check whether a memory region is a ram device
1270  *
1271  * Returns %true if a memory region is a device backed ram region
1272  *
1273  * @mr: the memory region being queried
1274  */
1275 bool memory_region_is_ram_device(MemoryRegion *mr);
1276 
1277 /**
1278  * memory_region_is_romd: check whether a memory region is in ROMD mode
1279  *
1280  * Returns %true if a memory region is a ROM device and currently set to allow
1281  * direct reads.
1282  *
1283  * @mr: the memory region being queried
1284  */
1285 static inline bool memory_region_is_romd(MemoryRegion *mr)
1286 {
1287     return mr->rom_device && mr->romd_mode;
1288 }
1289 
1290 /**
1291  * memory_region_get_iommu: check whether a memory region is an iommu
1292  *
1293  * Returns pointer to IOMMUMemoryRegion if a memory region is an iommu,
1294  * otherwise NULL.
1295  *
1296  * @mr: the memory region being queried
1297  */
1298 static inline IOMMUMemoryRegion *memory_region_get_iommu(MemoryRegion *mr)
1299 {
1300     if (mr->alias) {
1301         return memory_region_get_iommu(mr->alias);
1302     }
1303     if (mr->is_iommu) {
1304         return (IOMMUMemoryRegion *) mr;
1305     }
1306     return NULL;
1307 }
1308 
1309 /**
1310  * memory_region_get_iommu_class_nocheck: returns iommu memory region class
1311  *   if an iommu or NULL if not
1312  *
1313  * Returns pointer to IOMMUMemoryRegionClass if a memory region is an iommu,
1314  * otherwise NULL. This is fast path avoiding QOM checking, use with caution.
1315  *
1316  * @iommu_mr: the memory region being queried
1317  */
1318 static inline IOMMUMemoryRegionClass *memory_region_get_iommu_class_nocheck(
1319         IOMMUMemoryRegion *iommu_mr)
1320 {
1321     return (IOMMUMemoryRegionClass *) (((Object *)iommu_mr)->class);
1322 }
1323 
1324 #define memory_region_is_iommu(mr) (memory_region_get_iommu(mr) != NULL)
1325 
1326 /**
1327  * memory_region_iommu_get_min_page_size: get minimum supported page size
1328  * for an iommu
1329  *
1330  * Returns minimum supported page size for an iommu.
1331  *
1332  * @iommu_mr: the memory region being queried
1333  */
1334 uint64_t memory_region_iommu_get_min_page_size(IOMMUMemoryRegion *iommu_mr);
1335 
1336 /**
1337  * memory_region_notify_iommu: notify a change in an IOMMU translation entry.
1338  *
1339  * Note: for any IOMMU implementation, an in-place mapping change
1340  * should be notified with an UNMAP followed by a MAP.
1341  *
1342  * @iommu_mr: the memory region that was changed
1343  * @iommu_idx: the IOMMU index for the translation table which has changed
1344  * @event: TLB event with the new entry in the IOMMU translation table.
1345  *         The entry replaces all old entries for the same virtual I/O address
1346  *         range.
1347  */
1348 void memory_region_notify_iommu(IOMMUMemoryRegion *iommu_mr,
1349                                 int iommu_idx,
1350                                 IOMMUTLBEvent event);
1351 
1352 /**
1353  * memory_region_notify_iommu_one: notify a change in an IOMMU translation
1354  *                           entry to a single notifier
1355  *
1356  * This works just like memory_region_notify_iommu(), but it only
1357  * notifies a specific notifier, not all of them.
1358  *
1359  * @notifier: the notifier to be notified
1360  * @event: TLB event with the new entry in the IOMMU translation table.
1361  *         The entry replaces all old entries for the same virtual I/O address
1362  *         range.
1363  */
1364 void memory_region_notify_iommu_one(IOMMUNotifier *notifier,
1365                                     IOMMUTLBEvent *event);
1366 
1367 /**
1368  * memory_region_register_iommu_notifier: register a notifier for changes to
1369  * IOMMU translation entries.
1370  *
1371  * Returns 0 on success, or a negative errno otherwise. In particular,
1372  * -EINVAL indicates that at least one of the attributes of the notifier
1373  * is not supported (flag/range) by the IOMMU memory region. In case of error
1374  * the error object must be created.
1375  *
1376  * @mr: the memory region to observe
1377  * @n: the IOMMUNotifier to be added; the notify callback receives a
1378  *     pointer to an #IOMMUTLBEntry as the opaque value; the pointer
1379  *     ceases to be valid on exit from the notifier.
1380  * @errp: pointer to Error*, to store an error if it happens.
1381  */
1382 int memory_region_register_iommu_notifier(MemoryRegion *mr,
1383                                           IOMMUNotifier *n, Error **errp);
1384 
1385 /**
1386  * memory_region_iommu_replay: replay existing IOMMU translations to
1387  * a notifier with the minimum page granularity returned by
1388  * mr->iommu_ops->get_page_size().
1389  *
1390  * Note: this is not related to record-and-replay functionality.
1391  *
1392  * @iommu_mr: the memory region to observe
1393  * @n: the notifier to which to replay iommu mappings
1394  */
1395 void memory_region_iommu_replay(IOMMUMemoryRegion *iommu_mr, IOMMUNotifier *n);
1396 
1397 /**
1398  * memory_region_unregister_iommu_notifier: unregister a notifier for
1399  * changes to IOMMU translation entries.
1400  *
1401  * @mr: the memory region which was observed and for which notity_stopped()
1402  *      needs to be called
1403  * @n: the notifier to be removed.
1404  */
1405 void memory_region_unregister_iommu_notifier(MemoryRegion *mr,
1406                                              IOMMUNotifier *n);
1407 
1408 /**
1409  * memory_region_iommu_get_attr: return an IOMMU attr if get_attr() is
1410  * defined on the IOMMU.
1411  *
1412  * Returns 0 on success, or a negative errno otherwise. In particular,
1413  * -EINVAL indicates that the IOMMU does not support the requested
1414  * attribute.
1415  *
1416  * @iommu_mr: the memory region
1417  * @attr: the requested attribute
1418  * @data: a pointer to the requested attribute data
1419  */
1420 int memory_region_iommu_get_attr(IOMMUMemoryRegion *iommu_mr,
1421                                  enum IOMMUMemoryRegionAttr attr,
1422                                  void *data);
1423 
1424 /**
1425  * memory_region_iommu_attrs_to_index: return the IOMMU index to
1426  * use for translations with the given memory transaction attributes.
1427  *
1428  * @iommu_mr: the memory region
1429  * @attrs: the memory transaction attributes
1430  */
1431 int memory_region_iommu_attrs_to_index(IOMMUMemoryRegion *iommu_mr,
1432                                        MemTxAttrs attrs);
1433 
1434 /**
1435  * memory_region_iommu_num_indexes: return the total number of IOMMU
1436  * indexes that this IOMMU supports.
1437  *
1438  * @iommu_mr: the memory region
1439  */
1440 int memory_region_iommu_num_indexes(IOMMUMemoryRegion *iommu_mr);
1441 
1442 /**
1443  * memory_region_iommu_set_page_size_mask: set the supported page
1444  * sizes for a given IOMMU memory region
1445  *
1446  * @iommu_mr: IOMMU memory region
1447  * @page_size_mask: supported page size mask
1448  * @errp: pointer to Error*, to store an error if it happens.
1449  */
1450 int memory_region_iommu_set_page_size_mask(IOMMUMemoryRegion *iommu_mr,
1451                                            uint64_t page_size_mask,
1452                                            Error **errp);
1453 
1454 /**
1455  * memory_region_name: get a memory region's name
1456  *
1457  * Returns the string that was used to initialize the memory region.
1458  *
1459  * @mr: the memory region being queried
1460  */
1461 const char *memory_region_name(const MemoryRegion *mr);
1462 
1463 /**
1464  * memory_region_is_logging: return whether a memory region is logging writes
1465  *
1466  * Returns %true if the memory region is logging writes for the given client
1467  *
1468  * @mr: the memory region being queried
1469  * @client: the client being queried
1470  */
1471 bool memory_region_is_logging(MemoryRegion *mr, uint8_t client);
1472 
1473 /**
1474  * memory_region_get_dirty_log_mask: return the clients for which a
1475  * memory region is logging writes.
1476  *
1477  * Returns a bitmap of clients, in which the DIRTY_MEMORY_* constants
1478  * are the bit indices.
1479  *
1480  * @mr: the memory region being queried
1481  */
1482 uint8_t memory_region_get_dirty_log_mask(MemoryRegion *mr);
1483 
1484 /**
1485  * memory_region_is_rom: check whether a memory region is ROM
1486  *
1487  * Returns %true if a memory region is read-only memory.
1488  *
1489  * @mr: the memory region being queried
1490  */
1491 static inline bool memory_region_is_rom(MemoryRegion *mr)
1492 {
1493     return mr->ram && mr->readonly;
1494 }
1495 
1496 /**
1497  * memory_region_is_nonvolatile: check whether a memory region is non-volatile
1498  *
1499  * Returns %true is a memory region is non-volatile memory.
1500  *
1501  * @mr: the memory region being queried
1502  */
1503 static inline bool memory_region_is_nonvolatile(MemoryRegion *mr)
1504 {
1505     return mr->nonvolatile;
1506 }
1507 
1508 /**
1509  * memory_region_get_fd: Get a file descriptor backing a RAM memory region.
1510  *
1511  * Returns a file descriptor backing a file-based RAM memory region,
1512  * or -1 if the region is not a file-based RAM memory region.
1513  *
1514  * @mr: the RAM or alias memory region being queried.
1515  */
1516 int memory_region_get_fd(MemoryRegion *mr);
1517 
1518 /**
1519  * memory_region_from_host: Convert a pointer into a RAM memory region
1520  * and an offset within it.
1521  *
1522  * Given a host pointer inside a RAM memory region (created with
1523  * memory_region_init_ram() or memory_region_init_ram_ptr()), return
1524  * the MemoryRegion and the offset within it.
1525  *
1526  * Use with care; by the time this function returns, the returned pointer is
1527  * not protected by RCU anymore.  If the caller is not within an RCU critical
1528  * section and does not hold the iothread lock, it must have other means of
1529  * protecting the pointer, such as a reference to the region that includes
1530  * the incoming ram_addr_t.
1531  *
1532  * @ptr: the host pointer to be converted
1533  * @offset: the offset within memory region
1534  */
1535 MemoryRegion *memory_region_from_host(void *ptr, ram_addr_t *offset);
1536 
1537 /**
1538  * memory_region_get_ram_ptr: Get a pointer into a RAM memory region.
1539  *
1540  * Returns a host pointer to a RAM memory region (created with
1541  * memory_region_init_ram() or memory_region_init_ram_ptr()).
1542  *
1543  * Use with care; by the time this function returns, the returned pointer is
1544  * not protected by RCU anymore.  If the caller is not within an RCU critical
1545  * section and does not hold the iothread lock, it must have other means of
1546  * protecting the pointer, such as a reference to the region that includes
1547  * the incoming ram_addr_t.
1548  *
1549  * @mr: the memory region being queried.
1550  */
1551 void *memory_region_get_ram_ptr(MemoryRegion *mr);
1552 
1553 /* memory_region_ram_resize: Resize a RAM region.
1554  *
1555  * Only legal before guest might have detected the memory size: e.g. on
1556  * incoming migration, or right after reset.
1557  *
1558  * @mr: a memory region created with @memory_region_init_resizeable_ram.
1559  * @newsize: the new size the region
1560  * @errp: pointer to Error*, to store an error if it happens.
1561  */
1562 void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize,
1563                               Error **errp);
1564 
1565 /**
1566  * memory_region_msync: Synchronize selected address range of
1567  * a memory mapped region
1568  *
1569  * @mr: the memory region to be msync
1570  * @addr: the initial address of the range to be sync
1571  * @size: the size of the range to be sync
1572  */
1573 void memory_region_msync(MemoryRegion *mr, hwaddr addr, hwaddr size);
1574 
1575 /**
1576  * memory_region_writeback: Trigger cache writeback for
1577  * selected address range
1578  *
1579  * @mr: the memory region to be updated
1580  * @addr: the initial address of the range to be written back
1581  * @size: the size of the range to be written back
1582  */
1583 void memory_region_writeback(MemoryRegion *mr, hwaddr addr, hwaddr size);
1584 
1585 /**
1586  * memory_region_set_log: Turn dirty logging on or off for a region.
1587  *
1588  * Turns dirty logging on or off for a specified client (display, migration).
1589  * Only meaningful for RAM regions.
1590  *
1591  * @mr: the memory region being updated.
1592  * @log: whether dirty logging is to be enabled or disabled.
1593  * @client: the user of the logging information; %DIRTY_MEMORY_VGA only.
1594  */
1595 void memory_region_set_log(MemoryRegion *mr, bool log, unsigned client);
1596 
1597 /**
1598  * memory_region_set_dirty: Mark a range of bytes as dirty in a memory region.
1599  *
1600  * Marks a range of bytes as dirty, after it has been dirtied outside
1601  * guest code.
1602  *
1603  * @mr: the memory region being dirtied.
1604  * @addr: the address (relative to the start of the region) being dirtied.
1605  * @size: size of the range being dirtied.
1606  */
1607 void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,
1608                              hwaddr size);
1609 
1610 /**
1611  * memory_region_clear_dirty_bitmap - clear dirty bitmap for memory range
1612  *
1613  * This function is called when the caller wants to clear the remote
1614  * dirty bitmap of a memory range within the memory region.  This can
1615  * be used by e.g. KVM to manually clear dirty log when
1616  * KVM_CAP_MANUAL_DIRTY_LOG_PROTECT is declared support by the host
1617  * kernel.
1618  *
1619  * @mr:     the memory region to clear the dirty log upon
1620  * @start:  start address offset within the memory region
1621  * @len:    length of the memory region to clear dirty bitmap
1622  */
1623 void memory_region_clear_dirty_bitmap(MemoryRegion *mr, hwaddr start,
1624                                       hwaddr len);
1625 
1626 /**
1627  * memory_region_snapshot_and_clear_dirty: Get a snapshot of the dirty
1628  *                                         bitmap and clear it.
1629  *
1630  * Creates a snapshot of the dirty bitmap, clears the dirty bitmap and
1631  * returns the snapshot.  The snapshot can then be used to query dirty
1632  * status, using memory_region_snapshot_get_dirty.  Snapshotting allows
1633  * querying the same page multiple times, which is especially useful for
1634  * display updates where the scanlines often are not page aligned.
1635  *
1636  * The dirty bitmap region which gets copyed into the snapshot (and
1637  * cleared afterwards) can be larger than requested.  The boundaries
1638  * are rounded up/down so complete bitmap longs (covering 64 pages on
1639  * 64bit hosts) can be copied over into the bitmap snapshot.  Which
1640  * isn't a problem for display updates as the extra pages are outside
1641  * the visible area, and in case the visible area changes a full
1642  * display redraw is due anyway.  Should other use cases for this
1643  * function emerge we might have to revisit this implementation
1644  * detail.
1645  *
1646  * Use g_free to release DirtyBitmapSnapshot.
1647  *
1648  * @mr: the memory region being queried.
1649  * @addr: the address (relative to the start of the region) being queried.
1650  * @size: the size of the range being queried.
1651  * @client: the user of the logging information; typically %DIRTY_MEMORY_VGA.
1652  */
1653 DirtyBitmapSnapshot *memory_region_snapshot_and_clear_dirty(MemoryRegion *mr,
1654                                                             hwaddr addr,
1655                                                             hwaddr size,
1656                                                             unsigned client);
1657 
1658 /**
1659  * memory_region_snapshot_get_dirty: Check whether a range of bytes is dirty
1660  *                                   in the specified dirty bitmap snapshot.
1661  *
1662  * @mr: the memory region being queried.
1663  * @snap: the dirty bitmap snapshot
1664  * @addr: the address (relative to the start of the region) being queried.
1665  * @size: the size of the range being queried.
1666  */
1667 bool memory_region_snapshot_get_dirty(MemoryRegion *mr,
1668                                       DirtyBitmapSnapshot *snap,
1669                                       hwaddr addr, hwaddr size);
1670 
1671 /**
1672  * memory_region_reset_dirty: Mark a range of pages as clean, for a specified
1673  *                            client.
1674  *
1675  * Marks a range of pages as no longer dirty.
1676  *
1677  * @mr: the region being updated.
1678  * @addr: the start of the subrange being cleaned.
1679  * @size: the size of the subrange being cleaned.
1680  * @client: the user of the logging information; %DIRTY_MEMORY_MIGRATION or
1681  *          %DIRTY_MEMORY_VGA.
1682  */
1683 void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,
1684                                hwaddr size, unsigned client);
1685 
1686 /**
1687  * memory_region_flush_rom_device: Mark a range of pages dirty and invalidate
1688  *                                 TBs (for self-modifying code).
1689  *
1690  * The MemoryRegionOps->write() callback of a ROM device must use this function
1691  * to mark byte ranges that have been modified internally, such as by directly
1692  * accessing the memory returned by memory_region_get_ram_ptr().
1693  *
1694  * This function marks the range dirty and invalidates TBs so that TCG can
1695  * detect self-modifying code.
1696  *
1697  * @mr: the region being flushed.
1698  * @addr: the start, relative to the start of the region, of the range being
1699  *        flushed.
1700  * @size: the size, in bytes, of the range being flushed.
1701  */
1702 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size);
1703 
1704 /**
1705  * memory_region_set_readonly: Turn a memory region read-only (or read-write)
1706  *
1707  * Allows a memory region to be marked as read-only (turning it into a ROM).
1708  * only useful on RAM regions.
1709  *
1710  * @mr: the region being updated.
1711  * @readonly: whether rhe region is to be ROM or RAM.
1712  */
1713 void memory_region_set_readonly(MemoryRegion *mr, bool readonly);
1714 
1715 /**
1716  * memory_region_set_nonvolatile: Turn a memory region non-volatile
1717  *
1718  * Allows a memory region to be marked as non-volatile.
1719  * only useful on RAM regions.
1720  *
1721  * @mr: the region being updated.
1722  * @nonvolatile: whether rhe region is to be non-volatile.
1723  */
1724 void memory_region_set_nonvolatile(MemoryRegion *mr, bool nonvolatile);
1725 
1726 /**
1727  * memory_region_rom_device_set_romd: enable/disable ROMD mode
1728  *
1729  * Allows a ROM device (initialized with memory_region_init_rom_device() to
1730  * set to ROMD mode (default) or MMIO mode.  When it is in ROMD mode, the
1731  * device is mapped to guest memory and satisfies read access directly.
1732  * When in MMIO mode, reads are forwarded to the #MemoryRegion.read function.
1733  * Writes are always handled by the #MemoryRegion.write function.
1734  *
1735  * @mr: the memory region to be updated
1736  * @romd_mode: %true to put the region into ROMD mode
1737  */
1738 void memory_region_rom_device_set_romd(MemoryRegion *mr, bool romd_mode);
1739 
1740 /**
1741  * memory_region_set_coalescing: Enable memory coalescing for the region.
1742  *
1743  * Enabled writes to a region to be queued for later processing. MMIO ->write
1744  * callbacks may be delayed until a non-coalesced MMIO is issued.
1745  * Only useful for IO regions.  Roughly similar to write-combining hardware.
1746  *
1747  * @mr: the memory region to be write coalesced
1748  */
1749 void memory_region_set_coalescing(MemoryRegion *mr);
1750 
1751 /**
1752  * memory_region_add_coalescing: Enable memory coalescing for a sub-range of
1753  *                               a region.
1754  *
1755  * Like memory_region_set_coalescing(), but works on a sub-range of a region.
1756  * Multiple calls can be issued coalesced disjoint ranges.
1757  *
1758  * @mr: the memory region to be updated.
1759  * @offset: the start of the range within the region to be coalesced.
1760  * @size: the size of the subrange to be coalesced.
1761  */
1762 void memory_region_add_coalescing(MemoryRegion *mr,
1763                                   hwaddr offset,
1764                                   uint64_t size);
1765 
1766 /**
1767  * memory_region_clear_coalescing: Disable MMIO coalescing for the region.
1768  *
1769  * Disables any coalescing caused by memory_region_set_coalescing() or
1770  * memory_region_add_coalescing().  Roughly equivalent to uncacheble memory
1771  * hardware.
1772  *
1773  * @mr: the memory region to be updated.
1774  */
1775 void memory_region_clear_coalescing(MemoryRegion *mr);
1776 
1777 /**
1778  * memory_region_set_flush_coalesced: Enforce memory coalescing flush before
1779  *                                    accesses.
1780  *
1781  * Ensure that pending coalesced MMIO request are flushed before the memory
1782  * region is accessed. This property is automatically enabled for all regions
1783  * passed to memory_region_set_coalescing() and memory_region_add_coalescing().
1784  *
1785  * @mr: the memory region to be updated.
1786  */
1787 void memory_region_set_flush_coalesced(MemoryRegion *mr);
1788 
1789 /**
1790  * memory_region_clear_flush_coalesced: Disable memory coalescing flush before
1791  *                                      accesses.
1792  *
1793  * Clear the automatic coalesced MMIO flushing enabled via
1794  * memory_region_set_flush_coalesced. Note that this service has no effect on
1795  * memory regions that have MMIO coalescing enabled for themselves. For them,
1796  * automatic flushing will stop once coalescing is disabled.
1797  *
1798  * @mr: the memory region to be updated.
1799  */
1800 void memory_region_clear_flush_coalesced(MemoryRegion *mr);
1801 
1802 /**
1803  * memory_region_add_eventfd: Request an eventfd to be triggered when a word
1804  *                            is written to a location.
1805  *
1806  * Marks a word in an IO region (initialized with memory_region_init_io())
1807  * as a trigger for an eventfd event.  The I/O callback will not be called.
1808  * The caller must be prepared to handle failure (that is, take the required
1809  * action if the callback _is_ called).
1810  *
1811  * @mr: the memory region being updated.
1812  * @addr: the address within @mr that is to be monitored
1813  * @size: the size of the access to trigger the eventfd
1814  * @match_data: whether to match against @data, instead of just @addr
1815  * @data: the data to match against the guest write
1816  * @e: event notifier to be triggered when @addr, @size, and @data all match.
1817  **/
1818 void memory_region_add_eventfd(MemoryRegion *mr,
1819                                hwaddr addr,
1820                                unsigned size,
1821                                bool match_data,
1822                                uint64_t data,
1823                                EventNotifier *e);
1824 
1825 /**
1826  * memory_region_del_eventfd: Cancel an eventfd.
1827  *
1828  * Cancels an eventfd trigger requested by a previous
1829  * memory_region_add_eventfd() call.
1830  *
1831  * @mr: the memory region being updated.
1832  * @addr: the address within @mr that is to be monitored
1833  * @size: the size of the access to trigger the eventfd
1834  * @match_data: whether to match against @data, instead of just @addr
1835  * @data: the data to match against the guest write
1836  * @e: event notifier to be triggered when @addr, @size, and @data all match.
1837  */
1838 void memory_region_del_eventfd(MemoryRegion *mr,
1839                                hwaddr addr,
1840                                unsigned size,
1841                                bool match_data,
1842                                uint64_t data,
1843                                EventNotifier *e);
1844 
1845 /**
1846  * memory_region_add_subregion: Add a subregion to a container.
1847  *
1848  * Adds a subregion at @offset.  The subregion may not overlap with other
1849  * subregions (except for those explicitly marked as overlapping).  A region
1850  * may only be added once as a subregion (unless removed with
1851  * memory_region_del_subregion()); use memory_region_init_alias() if you
1852  * want a region to be a subregion in multiple locations.
1853  *
1854  * @mr: the region to contain the new subregion; must be a container
1855  *      initialized with memory_region_init().
1856  * @offset: the offset relative to @mr where @subregion is added.
1857  * @subregion: the subregion to be added.
1858  */
1859 void memory_region_add_subregion(MemoryRegion *mr,
1860                                  hwaddr offset,
1861                                  MemoryRegion *subregion);
1862 /**
1863  * memory_region_add_subregion_overlap: Add a subregion to a container
1864  *                                      with overlap.
1865  *
1866  * Adds a subregion at @offset.  The subregion may overlap with other
1867  * subregions.  Conflicts are resolved by having a higher @priority hide a
1868  * lower @priority. Subregions without priority are taken as @priority 0.
1869  * A region may only be added once as a subregion (unless removed with
1870  * memory_region_del_subregion()); use memory_region_init_alias() if you
1871  * want a region to be a subregion in multiple locations.
1872  *
1873  * @mr: the region to contain the new subregion; must be a container
1874  *      initialized with memory_region_init().
1875  * @offset: the offset relative to @mr where @subregion is added.
1876  * @subregion: the subregion to be added.
1877  * @priority: used for resolving overlaps; highest priority wins.
1878  */
1879 void memory_region_add_subregion_overlap(MemoryRegion *mr,
1880                                          hwaddr offset,
1881                                          MemoryRegion *subregion,
1882                                          int priority);
1883 
1884 /**
1885  * memory_region_get_ram_addr: Get the ram address associated with a memory
1886  *                             region
1887  *
1888  * @mr: the region to be queried
1889  */
1890 ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr);
1891 
1892 uint64_t memory_region_get_alignment(const MemoryRegion *mr);
1893 /**
1894  * memory_region_del_subregion: Remove a subregion.
1895  *
1896  * Removes a subregion from its container.
1897  *
1898  * @mr: the container to be updated.
1899  * @subregion: the region being removed; must be a current subregion of @mr.
1900  */
1901 void memory_region_del_subregion(MemoryRegion *mr,
1902                                  MemoryRegion *subregion);
1903 
1904 /*
1905  * memory_region_set_enabled: dynamically enable or disable a region
1906  *
1907  * Enables or disables a memory region.  A disabled memory region
1908  * ignores all accesses to itself and its subregions.  It does not
1909  * obscure sibling subregions with lower priority - it simply behaves as
1910  * if it was removed from the hierarchy.
1911  *
1912  * Regions default to being enabled.
1913  *
1914  * @mr: the region to be updated
1915  * @enabled: whether to enable or disable the region
1916  */
1917 void memory_region_set_enabled(MemoryRegion *mr, bool enabled);
1918 
1919 /*
1920  * memory_region_set_address: dynamically update the address of a region
1921  *
1922  * Dynamically updates the address of a region, relative to its container.
1923  * May be used on regions are currently part of a memory hierarchy.
1924  *
1925  * @mr: the region to be updated
1926  * @addr: new address, relative to container region
1927  */
1928 void memory_region_set_address(MemoryRegion *mr, hwaddr addr);
1929 
1930 /*
1931  * memory_region_set_size: dynamically update the size of a region.
1932  *
1933  * Dynamically updates the size of a region.
1934  *
1935  * @mr: the region to be updated
1936  * @size: used size of the region.
1937  */
1938 void memory_region_set_size(MemoryRegion *mr, uint64_t size);
1939 
1940 /*
1941  * memory_region_set_alias_offset: dynamically update a memory alias's offset
1942  *
1943  * Dynamically updates the offset into the target region that an alias points
1944  * to, as if the fourth argument to memory_region_init_alias() has changed.
1945  *
1946  * @mr: the #MemoryRegion to be updated; should be an alias.
1947  * @offset: the new offset into the target memory region
1948  */
1949 void memory_region_set_alias_offset(MemoryRegion *mr,
1950                                     hwaddr offset);
1951 
1952 /**
1953  * memory_region_present: checks if an address relative to a @container
1954  * translates into #MemoryRegion within @container
1955  *
1956  * Answer whether a #MemoryRegion within @container covers the address
1957  * @addr.
1958  *
1959  * @container: a #MemoryRegion within which @addr is a relative address
1960  * @addr: the area within @container to be searched
1961  */
1962 bool memory_region_present(MemoryRegion *container, hwaddr addr);
1963 
1964 /**
1965  * memory_region_is_mapped: returns true if #MemoryRegion is mapped
1966  * into any address space.
1967  *
1968  * @mr: a #MemoryRegion which should be checked if it's mapped
1969  */
1970 bool memory_region_is_mapped(MemoryRegion *mr);
1971 
1972 /**
1973  * memory_region_find: translate an address/size relative to a
1974  * MemoryRegion into a #MemoryRegionSection.
1975  *
1976  * Locates the first #MemoryRegion within @mr that overlaps the range
1977  * given by @addr and @size.
1978  *
1979  * Returns a #MemoryRegionSection that describes a contiguous overlap.
1980  * It will have the following characteristics:
1981  * - @size = 0 iff no overlap was found
1982  * - @mr is non-%NULL iff an overlap was found
1983  *
1984  * Remember that in the return value the @offset_within_region is
1985  * relative to the returned region (in the .@mr field), not to the
1986  * @mr argument.
1987  *
1988  * Similarly, the .@offset_within_address_space is relative to the
1989  * address space that contains both regions, the passed and the
1990  * returned one.  However, in the special case where the @mr argument
1991  * has no container (and thus is the root of the address space), the
1992  * following will hold:
1993  * - @offset_within_address_space >= @addr
1994  * - @offset_within_address_space + .@size <= @addr + @size
1995  *
1996  * @mr: a MemoryRegion within which @addr is a relative address
1997  * @addr: start of the area within @as to be searched
1998  * @size: size of the area to be searched
1999  */
2000 MemoryRegionSection memory_region_find(MemoryRegion *mr,
2001                                        hwaddr addr, uint64_t size);
2002 
2003 /**
2004  * memory_global_dirty_log_sync: synchronize the dirty log for all memory
2005  *
2006  * Synchronizes the dirty page log for all address spaces.
2007  */
2008 void memory_global_dirty_log_sync(void);
2009 
2010 /**
2011  * memory_global_dirty_log_sync: synchronize the dirty log for all memory
2012  *
2013  * Synchronizes the vCPUs with a thread that is reading the dirty bitmap.
2014  * This function must be called after the dirty log bitmap is cleared, and
2015  * before dirty guest memory pages are read.  If you are using
2016  * #DirtyBitmapSnapshot, memory_region_snapshot_and_clear_dirty() takes
2017  * care of doing this.
2018  */
2019 void memory_global_after_dirty_log_sync(void);
2020 
2021 /**
2022  * memory_region_transaction_begin: Start a transaction.
2023  *
2024  * During a transaction, changes will be accumulated and made visible
2025  * only when the transaction ends (is committed).
2026  */
2027 void memory_region_transaction_begin(void);
2028 
2029 /**
2030  * memory_region_transaction_commit: Commit a transaction and make changes
2031  *                                   visible to the guest.
2032  */
2033 void memory_region_transaction_commit(void);
2034 
2035 /**
2036  * memory_listener_register: register callbacks to be called when memory
2037  *                           sections are mapped or unmapped into an address
2038  *                           space
2039  *
2040  * @listener: an object containing the callbacks to be called
2041  * @filter: if non-%NULL, only regions in this address space will be observed
2042  */
2043 void memory_listener_register(MemoryListener *listener, AddressSpace *filter);
2044 
2045 /**
2046  * memory_listener_unregister: undo the effect of memory_listener_register()
2047  *
2048  * @listener: an object containing the callbacks to be removed
2049  */
2050 void memory_listener_unregister(MemoryListener *listener);
2051 
2052 /**
2053  * memory_global_dirty_log_start: begin dirty logging for all regions
2054  */
2055 void memory_global_dirty_log_start(void);
2056 
2057 /**
2058  * memory_global_dirty_log_stop: end dirty logging for all regions
2059  */
2060 void memory_global_dirty_log_stop(void);
2061 
2062 void mtree_info(bool flatview, bool dispatch_tree, bool owner, bool disabled);
2063 
2064 /**
2065  * memory_region_dispatch_read: perform a read directly to the specified
2066  * MemoryRegion.
2067  *
2068  * @mr: #MemoryRegion to access
2069  * @addr: address within that region
2070  * @pval: pointer to uint64_t which the data is written to
2071  * @op: size, sign, and endianness of the memory operation
2072  * @attrs: memory transaction attributes to use for the access
2073  */
2074 MemTxResult memory_region_dispatch_read(MemoryRegion *mr,
2075                                         hwaddr addr,
2076                                         uint64_t *pval,
2077                                         MemOp op,
2078                                         MemTxAttrs attrs);
2079 /**
2080  * memory_region_dispatch_write: perform a write directly to the specified
2081  * MemoryRegion.
2082  *
2083  * @mr: #MemoryRegion to access
2084  * @addr: address within that region
2085  * @data: data to write
2086  * @op: size, sign, and endianness of the memory operation
2087  * @attrs: memory transaction attributes to use for the access
2088  */
2089 MemTxResult memory_region_dispatch_write(MemoryRegion *mr,
2090                                          hwaddr addr,
2091                                          uint64_t data,
2092                                          MemOp op,
2093                                          MemTxAttrs attrs);
2094 
2095 /**
2096  * address_space_init: initializes an address space
2097  *
2098  * @as: an uninitialized #AddressSpace
2099  * @root: a #MemoryRegion that routes addresses for the address space
2100  * @name: an address space name.  The name is only used for debugging
2101  *        output.
2102  */
2103 void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name);
2104 
2105 /**
2106  * address_space_destroy: destroy an address space
2107  *
2108  * Releases all resources associated with an address space.  After an address space
2109  * is destroyed, its root memory region (given by address_space_init()) may be destroyed
2110  * as well.
2111  *
2112  * @as: address space to be destroyed
2113  */
2114 void address_space_destroy(AddressSpace *as);
2115 
2116 /**
2117  * address_space_remove_listeners: unregister all listeners of an address space
2118  *
2119  * Removes all callbacks previously registered with memory_listener_register()
2120  * for @as.
2121  *
2122  * @as: an initialized #AddressSpace
2123  */
2124 void address_space_remove_listeners(AddressSpace *as);
2125 
2126 /**
2127  * address_space_rw: read from or write to an address space.
2128  *
2129  * Return a MemTxResult indicating whether the operation succeeded
2130  * or failed (eg unassigned memory, device rejected the transaction,
2131  * IOMMU fault).
2132  *
2133  * @as: #AddressSpace to be accessed
2134  * @addr: address within that address space
2135  * @attrs: memory transaction attributes
2136  * @buf: buffer with the data transferred
2137  * @len: the number of bytes to read or write
2138  * @is_write: indicates the transfer direction
2139  */
2140 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr,
2141                              MemTxAttrs attrs, void *buf,
2142                              hwaddr len, bool is_write);
2143 
2144 /**
2145  * address_space_write: write to address space.
2146  *
2147  * Return a MemTxResult indicating whether the operation succeeded
2148  * or failed (eg unassigned memory, device rejected the transaction,
2149  * IOMMU fault).
2150  *
2151  * @as: #AddressSpace to be accessed
2152  * @addr: address within that address space
2153  * @attrs: memory transaction attributes
2154  * @buf: buffer with the data transferred
2155  * @len: the number of bytes to write
2156  */
2157 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2158                                 MemTxAttrs attrs,
2159                                 const void *buf, hwaddr len);
2160 
2161 /**
2162  * address_space_write_rom: write to address space, including ROM.
2163  *
2164  * This function writes to the specified address space, but will
2165  * write data to both ROM and RAM. This is used for non-guest
2166  * writes like writes from the gdb debug stub or initial loading
2167  * of ROM contents.
2168  *
2169  * Note that portions of the write which attempt to write data to
2170  * a device will be silently ignored -- only real RAM and ROM will
2171  * be written to.
2172  *
2173  * Return a MemTxResult indicating whether the operation succeeded
2174  * or failed (eg unassigned memory, device rejected the transaction,
2175  * IOMMU fault).
2176  *
2177  * @as: #AddressSpace to be accessed
2178  * @addr: address within that address space
2179  * @attrs: memory transaction attributes
2180  * @buf: buffer with the data transferred
2181  * @len: the number of bytes to write
2182  */
2183 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
2184                                     MemTxAttrs attrs,
2185                                     const void *buf, hwaddr len);
2186 
2187 /* address_space_ld*: load from an address space
2188  * address_space_st*: store to an address space
2189  *
2190  * These functions perform a load or store of the byte, word,
2191  * longword or quad to the specified address within the AddressSpace.
2192  * The _le suffixed functions treat the data as little endian;
2193  * _be indicates big endian; no suffix indicates "same endianness
2194  * as guest CPU".
2195  *
2196  * The "guest CPU endianness" accessors are deprecated for use outside
2197  * target-* code; devices should be CPU-agnostic and use either the LE
2198  * or the BE accessors.
2199  *
2200  * @as #AddressSpace to be accessed
2201  * @addr: address within that address space
2202  * @val: data value, for stores
2203  * @attrs: memory transaction attributes
2204  * @result: location to write the success/failure of the transaction;
2205  *   if NULL, this information is discarded
2206  */
2207 
2208 #define SUFFIX
2209 #define ARG1         as
2210 #define ARG1_DECL    AddressSpace *as
2211 #include "exec/memory_ldst.h.inc"
2212 
2213 #define SUFFIX
2214 #define ARG1         as
2215 #define ARG1_DECL    AddressSpace *as
2216 #include "exec/memory_ldst_phys.h.inc"
2217 
2218 struct MemoryRegionCache {
2219     void *ptr;
2220     hwaddr xlat;
2221     hwaddr len;
2222     FlatView *fv;
2223     MemoryRegionSection mrs;
2224     bool is_write;
2225 };
2226 
2227 #define MEMORY_REGION_CACHE_INVALID ((MemoryRegionCache) { .mrs.mr = NULL })
2228 
2229 
2230 /* address_space_ld*_cached: load from a cached #MemoryRegion
2231  * address_space_st*_cached: store into a cached #MemoryRegion
2232  *
2233  * These functions perform a load or store of the byte, word,
2234  * longword or quad to the specified address.  The address is
2235  * a physical address in the AddressSpace, but it must lie within
2236  * a #MemoryRegion that was mapped with address_space_cache_init.
2237  *
2238  * The _le suffixed functions treat the data as little endian;
2239  * _be indicates big endian; no suffix indicates "same endianness
2240  * as guest CPU".
2241  *
2242  * The "guest CPU endianness" accessors are deprecated for use outside
2243  * target-* code; devices should be CPU-agnostic and use either the LE
2244  * or the BE accessors.
2245  *
2246  * @cache: previously initialized #MemoryRegionCache to be accessed
2247  * @addr: address within the address space
2248  * @val: data value, for stores
2249  * @attrs: memory transaction attributes
2250  * @result: location to write the success/failure of the transaction;
2251  *   if NULL, this information is discarded
2252  */
2253 
2254 #define SUFFIX       _cached_slow
2255 #define ARG1         cache
2256 #define ARG1_DECL    MemoryRegionCache *cache
2257 #include "exec/memory_ldst.h.inc"
2258 
2259 /* Inline fast path for direct RAM access.  */
2260 static inline uint8_t address_space_ldub_cached(MemoryRegionCache *cache,
2261     hwaddr addr, MemTxAttrs attrs, MemTxResult *result)
2262 {
2263     assert(addr < cache->len);
2264     if (likely(cache->ptr)) {
2265         return ldub_p(cache->ptr + addr);
2266     } else {
2267         return address_space_ldub_cached_slow(cache, addr, attrs, result);
2268     }
2269 }
2270 
2271 static inline void address_space_stb_cached(MemoryRegionCache *cache,
2272     hwaddr addr, uint32_t val, MemTxAttrs attrs, MemTxResult *result)
2273 {
2274     assert(addr < cache->len);
2275     if (likely(cache->ptr)) {
2276         stb_p(cache->ptr + addr, val);
2277     } else {
2278         address_space_stb_cached_slow(cache, addr, val, attrs, result);
2279     }
2280 }
2281 
2282 #define ENDIANNESS   _le
2283 #include "exec/memory_ldst_cached.h.inc"
2284 
2285 #define ENDIANNESS   _be
2286 #include "exec/memory_ldst_cached.h.inc"
2287 
2288 #define SUFFIX       _cached
2289 #define ARG1         cache
2290 #define ARG1_DECL    MemoryRegionCache *cache
2291 #include "exec/memory_ldst_phys.h.inc"
2292 
2293 /* address_space_cache_init: prepare for repeated access to a physical
2294  * memory region
2295  *
2296  * @cache: #MemoryRegionCache to be filled
2297  * @as: #AddressSpace to be accessed
2298  * @addr: address within that address space
2299  * @len: length of buffer
2300  * @is_write: indicates the transfer direction
2301  *
2302  * Will only work with RAM, and may map a subset of the requested range by
2303  * returning a value that is less than @len.  On failure, return a negative
2304  * errno value.
2305  *
2306  * Because it only works with RAM, this function can be used for
2307  * read-modify-write operations.  In this case, is_write should be %true.
2308  *
2309  * Note that addresses passed to the address_space_*_cached functions
2310  * are relative to @addr.
2311  */
2312 int64_t address_space_cache_init(MemoryRegionCache *cache,
2313                                  AddressSpace *as,
2314                                  hwaddr addr,
2315                                  hwaddr len,
2316                                  bool is_write);
2317 
2318 /**
2319  * address_space_cache_invalidate: complete a write to a #MemoryRegionCache
2320  *
2321  * @cache: The #MemoryRegionCache to operate on.
2322  * @addr: The first physical address that was written, relative to the
2323  * address that was passed to @address_space_cache_init.
2324  * @access_len: The number of bytes that were written starting at @addr.
2325  */
2326 void address_space_cache_invalidate(MemoryRegionCache *cache,
2327                                     hwaddr addr,
2328                                     hwaddr access_len);
2329 
2330 /**
2331  * address_space_cache_destroy: free a #MemoryRegionCache
2332  *
2333  * @cache: The #MemoryRegionCache whose memory should be released.
2334  */
2335 void address_space_cache_destroy(MemoryRegionCache *cache);
2336 
2337 /* address_space_get_iotlb_entry: translate an address into an IOTLB
2338  * entry. Should be called from an RCU critical section.
2339  */
2340 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
2341                                             bool is_write, MemTxAttrs attrs);
2342 
2343 /* address_space_translate: translate an address range into an address space
2344  * into a MemoryRegion and an address range into that section.  Should be
2345  * called from an RCU critical section, to avoid that the last reference
2346  * to the returned region disappears after address_space_translate returns.
2347  *
2348  * @fv: #FlatView to be accessed
2349  * @addr: address within that address space
2350  * @xlat: pointer to address within the returned memory region section's
2351  * #MemoryRegion.
2352  * @len: pointer to length
2353  * @is_write: indicates the transfer direction
2354  * @attrs: memory attributes
2355  */
2356 MemoryRegion *flatview_translate(FlatView *fv,
2357                                  hwaddr addr, hwaddr *xlat,
2358                                  hwaddr *len, bool is_write,
2359                                  MemTxAttrs attrs);
2360 
2361 static inline MemoryRegion *address_space_translate(AddressSpace *as,
2362                                                     hwaddr addr, hwaddr *xlat,
2363                                                     hwaddr *len, bool is_write,
2364                                                     MemTxAttrs attrs)
2365 {
2366     return flatview_translate(address_space_to_flatview(as),
2367                               addr, xlat, len, is_write, attrs);
2368 }
2369 
2370 /* address_space_access_valid: check for validity of accessing an address
2371  * space range
2372  *
2373  * Check whether memory is assigned to the given address space range, and
2374  * access is permitted by any IOMMU regions that are active for the address
2375  * space.
2376  *
2377  * For now, addr and len should be aligned to a page size.  This limitation
2378  * will be lifted in the future.
2379  *
2380  * @as: #AddressSpace to be accessed
2381  * @addr: address within that address space
2382  * @len: length of the area to be checked
2383  * @is_write: indicates the transfer direction
2384  * @attrs: memory attributes
2385  */
2386 bool address_space_access_valid(AddressSpace *as, hwaddr addr, hwaddr len,
2387                                 bool is_write, MemTxAttrs attrs);
2388 
2389 /* address_space_map: map a physical memory region into a host virtual address
2390  *
2391  * May map a subset of the requested range, given by and returned in @plen.
2392  * May return %NULL and set *@plen to zero(0), if resources needed to perform
2393  * the mapping are exhausted.
2394  * Use only for reads OR writes - not for read-modify-write operations.
2395  * Use cpu_register_map_client() to know when retrying the map operation is
2396  * likely to succeed.
2397  *
2398  * @as: #AddressSpace to be accessed
2399  * @addr: address within that address space
2400  * @plen: pointer to length of buffer; updated on return
2401  * @is_write: indicates the transfer direction
2402  * @attrs: memory attributes
2403  */
2404 void *address_space_map(AddressSpace *as, hwaddr addr,
2405                         hwaddr *plen, bool is_write, MemTxAttrs attrs);
2406 
2407 /* address_space_unmap: Unmaps a memory region previously mapped by address_space_map()
2408  *
2409  * Will also mark the memory as dirty if @is_write == %true.  @access_len gives
2410  * the amount of memory that was actually read or written by the caller.
2411  *
2412  * @as: #AddressSpace used
2413  * @buffer: host pointer as returned by address_space_map()
2414  * @len: buffer length as returned by address_space_map()
2415  * @access_len: amount of data actually transferred
2416  * @is_write: indicates the transfer direction
2417  */
2418 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
2419                          bool is_write, hwaddr access_len);
2420 
2421 
2422 /* Internal functions, part of the implementation of address_space_read.  */
2423 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2424                                     MemTxAttrs attrs, void *buf, hwaddr len);
2425 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
2426                                    MemTxAttrs attrs, void *buf,
2427                                    hwaddr len, hwaddr addr1, hwaddr l,
2428                                    MemoryRegion *mr);
2429 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr);
2430 
2431 /* Internal functions, part of the implementation of address_space_read_cached
2432  * and address_space_write_cached.  */
2433 MemTxResult address_space_read_cached_slow(MemoryRegionCache *cache,
2434                                            hwaddr addr, void *buf, hwaddr len);
2435 MemTxResult address_space_write_cached_slow(MemoryRegionCache *cache,
2436                                             hwaddr addr, const void *buf,
2437                                             hwaddr len);
2438 
2439 static inline bool memory_access_is_direct(MemoryRegion *mr, bool is_write)
2440 {
2441     if (is_write) {
2442         return memory_region_is_ram(mr) && !mr->readonly &&
2443                !mr->rom_device && !memory_region_is_ram_device(mr);
2444     } else {
2445         return (memory_region_is_ram(mr) && !memory_region_is_ram_device(mr)) ||
2446                memory_region_is_romd(mr);
2447     }
2448 }
2449 
2450 /**
2451  * address_space_read: read from an address space.
2452  *
2453  * Return a MemTxResult indicating whether the operation succeeded
2454  * or failed (eg unassigned memory, device rejected the transaction,
2455  * IOMMU fault).  Called within RCU critical section.
2456  *
2457  * @as: #AddressSpace to be accessed
2458  * @addr: address within that address space
2459  * @attrs: memory transaction attributes
2460  * @buf: buffer with the data transferred
2461  * @len: length of the data transferred
2462  */
2463 static inline __attribute__((__always_inline__))
2464 MemTxResult address_space_read(AddressSpace *as, hwaddr addr,
2465                                MemTxAttrs attrs, void *buf,
2466                                hwaddr len)
2467 {
2468     MemTxResult result = MEMTX_OK;
2469     hwaddr l, addr1;
2470     void *ptr;
2471     MemoryRegion *mr;
2472     FlatView *fv;
2473 
2474     if (__builtin_constant_p(len)) {
2475         if (len) {
2476             RCU_READ_LOCK_GUARD();
2477             fv = address_space_to_flatview(as);
2478             l = len;
2479             mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2480             if (len == l && memory_access_is_direct(mr, false)) {
2481                 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2482                 memcpy(buf, ptr, len);
2483             } else {
2484                 result = flatview_read_continue(fv, addr, attrs, buf, len,
2485                                                 addr1, l, mr);
2486             }
2487         }
2488     } else {
2489         result = address_space_read_full(as, addr, attrs, buf, len);
2490     }
2491     return result;
2492 }
2493 
2494 /**
2495  * address_space_read_cached: read from a cached RAM region
2496  *
2497  * @cache: Cached region to be addressed
2498  * @addr: address relative to the base of the RAM region
2499  * @buf: buffer with the data transferred
2500  * @len: length of the data transferred
2501  */
2502 static inline MemTxResult
2503 address_space_read_cached(MemoryRegionCache *cache, hwaddr addr,
2504                           void *buf, hwaddr len)
2505 {
2506     assert(addr < cache->len && len <= cache->len - addr);
2507     fuzz_dma_read_cb(cache->xlat + addr, len, cache->mrs.mr, false);
2508     if (likely(cache->ptr)) {
2509         memcpy(buf, cache->ptr + addr, len);
2510         return MEMTX_OK;
2511     } else {
2512         return address_space_read_cached_slow(cache, addr, buf, len);
2513     }
2514 }
2515 
2516 /**
2517  * address_space_write_cached: write to a cached RAM region
2518  *
2519  * @cache: Cached region to be addressed
2520  * @addr: address relative to the base of the RAM region
2521  * @buf: buffer with the data transferred
2522  * @len: length of the data transferred
2523  */
2524 static inline MemTxResult
2525 address_space_write_cached(MemoryRegionCache *cache, hwaddr addr,
2526                            const void *buf, hwaddr len)
2527 {
2528     assert(addr < cache->len && len <= cache->len - addr);
2529     if (likely(cache->ptr)) {
2530         memcpy(cache->ptr + addr, buf, len);
2531         return MEMTX_OK;
2532     } else {
2533         return address_space_write_cached_slow(cache, addr, buf, len);
2534     }
2535 }
2536 
2537 #ifdef NEED_CPU_H
2538 /* enum device_endian to MemOp.  */
2539 static inline MemOp devend_memop(enum device_endian end)
2540 {
2541     QEMU_BUILD_BUG_ON(DEVICE_HOST_ENDIAN != DEVICE_LITTLE_ENDIAN &&
2542                       DEVICE_HOST_ENDIAN != DEVICE_BIG_ENDIAN);
2543 
2544 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
2545     /* Swap if non-host endianness or native (target) endianness */
2546     return (end == DEVICE_HOST_ENDIAN) ? 0 : MO_BSWAP;
2547 #else
2548     const int non_host_endianness =
2549         DEVICE_LITTLE_ENDIAN ^ DEVICE_BIG_ENDIAN ^ DEVICE_HOST_ENDIAN;
2550 
2551     /* In this case, native (target) endianness needs no swap.  */
2552     return (end == non_host_endianness) ? MO_BSWAP : 0;
2553 #endif
2554 }
2555 #endif
2556 
2557 /*
2558  * Inhibit technologies that require discarding of pages in RAM blocks, e.g.,
2559  * to manage the actual amount of memory consumed by the VM (then, the memory
2560  * provided by RAM blocks might be bigger than the desired memory consumption).
2561  * This *must* be set if:
2562  * - Discarding parts of a RAM blocks does not result in the change being
2563  *   reflected in the VM and the pages getting freed.
2564  * - All memory in RAM blocks is pinned or duplicated, invaldiating any previous
2565  *   discards blindly.
2566  * - Discarding parts of a RAM blocks will result in integrity issues (e.g.,
2567  *   encrypted VMs).
2568  * Technologies that only temporarily pin the current working set of a
2569  * driver are fine, because we don't expect such pages to be discarded
2570  * (esp. based on guest action like balloon inflation).
2571  *
2572  * This is *not* to be used to protect from concurrent discards (esp.,
2573  * postcopy).
2574  *
2575  * Returns 0 if successful. Returns -EBUSY if a technology that relies on
2576  * discards to work reliably is active.
2577  */
2578 int ram_block_discard_disable(bool state);
2579 
2580 /*
2581  * Inhibit technologies that disable discarding of pages in RAM blocks.
2582  *
2583  * Returns 0 if successful. Returns -EBUSY if discards are already set to
2584  * broken.
2585  */
2586 int ram_block_discard_require(bool state);
2587 
2588 /*
2589  * Test if discarding of memory in ram blocks is disabled.
2590  */
2591 bool ram_block_discard_is_disabled(void);
2592 
2593 /*
2594  * Test if discarding of memory in ram blocks is required to work reliably.
2595  */
2596 bool ram_block_discard_is_required(void);
2597 
2598 #endif
2599 
2600 #endif
2601