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