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