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