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