OSDN Git Service

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