]> Git Repo - qemu.git/blob - softmmu/physmem.c
Merge remote-tracking branch 'remotes/armbru/tags/pull-misc-2021-05-12' into staging
[qemu.git] / softmmu / physmem.c
1 /*
2  * RAM allocation and memory access
3  *
4  *  Copyright (c) 2003 Fabrice Bellard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "qemu/osdep.h"
21 #include "qemu-common.h"
22 #include "qapi/error.h"
23
24 #include "qemu/cutils.h"
25 #include "qemu/cacheflush.h"
26
27 #ifdef CONFIG_TCG
28 #include "hw/core/tcg-cpu-ops.h"
29 #endif /* CONFIG_TCG */
30
31 #include "exec/exec-all.h"
32 #include "exec/target_page.h"
33 #include "hw/qdev-core.h"
34 #include "hw/qdev-properties.h"
35 #include "hw/boards.h"
36 #include "hw/xen/xen.h"
37 #include "sysemu/kvm.h"
38 #include "sysemu/tcg.h"
39 #include "sysemu/qtest.h"
40 #include "qemu/timer.h"
41 #include "qemu/config-file.h"
42 #include "qemu/error-report.h"
43 #include "qemu/qemu-print.h"
44 #include "exec/memory.h"
45 #include "exec/ioport.h"
46 #include "sysemu/dma.h"
47 #include "sysemu/hostmem.h"
48 #include "sysemu/hw_accel.h"
49 #include "sysemu/xen-mapcache.h"
50 #include "trace/trace-root.h"
51
52 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
53 #include <linux/falloc.h>
54 #endif
55
56 #include "qemu/rcu_queue.h"
57 #include "qemu/main-loop.h"
58 #include "exec/translate-all.h"
59 #include "sysemu/replay.h"
60
61 #include "exec/memory-internal.h"
62 #include "exec/ram_addr.h"
63 #include "exec/log.h"
64
65 #include "qemu/pmem.h"
66
67 #include "migration/vmstate.h"
68
69 #include "qemu/range.h"
70 #ifndef _WIN32
71 #include "qemu/mmap-alloc.h"
72 #endif
73
74 #include "monitor/monitor.h"
75
76 #ifdef CONFIG_LIBDAXCTL
77 #include <daxctl/libdaxctl.h>
78 #endif
79
80 //#define DEBUG_SUBPAGE
81
82 /* ram_list is read under rcu_read_lock()/rcu_read_unlock().  Writes
83  * are protected by the ramlist lock.
84  */
85 RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
86
87 static MemoryRegion *system_memory;
88 static MemoryRegion *system_io;
89
90 AddressSpace address_space_io;
91 AddressSpace address_space_memory;
92
93 static MemoryRegion io_mem_unassigned;
94
95 typedef struct PhysPageEntry PhysPageEntry;
96
97 struct PhysPageEntry {
98     /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
99     uint32_t skip : 6;
100      /* index into phys_sections (!skip) or phys_map_nodes (skip) */
101     uint32_t ptr : 26;
102 };
103
104 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
105
106 /* Size of the L2 (and L3, etc) page tables.  */
107 #define ADDR_SPACE_BITS 64
108
109 #define P_L2_BITS 9
110 #define P_L2_SIZE (1 << P_L2_BITS)
111
112 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
113
114 typedef PhysPageEntry Node[P_L2_SIZE];
115
116 typedef struct PhysPageMap {
117     struct rcu_head rcu;
118
119     unsigned sections_nb;
120     unsigned sections_nb_alloc;
121     unsigned nodes_nb;
122     unsigned nodes_nb_alloc;
123     Node *nodes;
124     MemoryRegionSection *sections;
125 } PhysPageMap;
126
127 struct AddressSpaceDispatch {
128     MemoryRegionSection *mru_section;
129     /* This is a multi-level map on the physical address space.
130      * The bottom level has pointers to MemoryRegionSections.
131      */
132     PhysPageEntry phys_map;
133     PhysPageMap map;
134 };
135
136 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
137 typedef struct subpage_t {
138     MemoryRegion iomem;
139     FlatView *fv;
140     hwaddr base;
141     uint16_t sub_section[];
142 } subpage_t;
143
144 #define PHYS_SECTION_UNASSIGNED 0
145
146 static void io_mem_init(void);
147 static void memory_map_init(void);
148 static void tcg_log_global_after_sync(MemoryListener *listener);
149 static void tcg_commit(MemoryListener *listener);
150
151 /**
152  * CPUAddressSpace: all the information a CPU needs about an AddressSpace
153  * @cpu: the CPU whose AddressSpace this is
154  * @as: the AddressSpace itself
155  * @memory_dispatch: its dispatch pointer (cached, RCU protected)
156  * @tcg_as_listener: listener for tracking changes to the AddressSpace
157  */
158 struct CPUAddressSpace {
159     CPUState *cpu;
160     AddressSpace *as;
161     struct AddressSpaceDispatch *memory_dispatch;
162     MemoryListener tcg_as_listener;
163 };
164
165 struct DirtyBitmapSnapshot {
166     ram_addr_t start;
167     ram_addr_t end;
168     unsigned long dirty[];
169 };
170
171 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
172 {
173     static unsigned alloc_hint = 16;
174     if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
175         map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
176         map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
177         alloc_hint = map->nodes_nb_alloc;
178     }
179 }
180
181 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
182 {
183     unsigned i;
184     uint32_t ret;
185     PhysPageEntry e;
186     PhysPageEntry *p;
187
188     ret = map->nodes_nb++;
189     p = map->nodes[ret];
190     assert(ret != PHYS_MAP_NODE_NIL);
191     assert(ret != map->nodes_nb_alloc);
192
193     e.skip = leaf ? 0 : 1;
194     e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
195     for (i = 0; i < P_L2_SIZE; ++i) {
196         memcpy(&p[i], &e, sizeof(e));
197     }
198     return ret;
199 }
200
201 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
202                                 hwaddr *index, uint64_t *nb, uint16_t leaf,
203                                 int level)
204 {
205     PhysPageEntry *p;
206     hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
207
208     if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
209         lp->ptr = phys_map_node_alloc(map, level == 0);
210     }
211     p = map->nodes[lp->ptr];
212     lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
213
214     while (*nb && lp < &p[P_L2_SIZE]) {
215         if ((*index & (step - 1)) == 0 && *nb >= step) {
216             lp->skip = 0;
217             lp->ptr = leaf;
218             *index += step;
219             *nb -= step;
220         } else {
221             phys_page_set_level(map, lp, index, nb, leaf, level - 1);
222         }
223         ++lp;
224     }
225 }
226
227 static void phys_page_set(AddressSpaceDispatch *d,
228                           hwaddr index, uint64_t nb,
229                           uint16_t leaf)
230 {
231     /* Wildly overreserve - it doesn't matter much. */
232     phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
233
234     phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
235 }
236
237 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
238  * and update our entry so we can skip it and go directly to the destination.
239  */
240 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
241 {
242     unsigned valid_ptr = P_L2_SIZE;
243     int valid = 0;
244     PhysPageEntry *p;
245     int i;
246
247     if (lp->ptr == PHYS_MAP_NODE_NIL) {
248         return;
249     }
250
251     p = nodes[lp->ptr];
252     for (i = 0; i < P_L2_SIZE; i++) {
253         if (p[i].ptr == PHYS_MAP_NODE_NIL) {
254             continue;
255         }
256
257         valid_ptr = i;
258         valid++;
259         if (p[i].skip) {
260             phys_page_compact(&p[i], nodes);
261         }
262     }
263
264     /* We can only compress if there's only one child. */
265     if (valid != 1) {
266         return;
267     }
268
269     assert(valid_ptr < P_L2_SIZE);
270
271     /* Don't compress if it won't fit in the # of bits we have. */
272     if (P_L2_LEVELS >= (1 << 6) &&
273         lp->skip + p[valid_ptr].skip >= (1 << 6)) {
274         return;
275     }
276
277     lp->ptr = p[valid_ptr].ptr;
278     if (!p[valid_ptr].skip) {
279         /* If our only child is a leaf, make this a leaf. */
280         /* By design, we should have made this node a leaf to begin with so we
281          * should never reach here.
282          * But since it's so simple to handle this, let's do it just in case we
283          * change this rule.
284          */
285         lp->skip = 0;
286     } else {
287         lp->skip += p[valid_ptr].skip;
288     }
289 }
290
291 void address_space_dispatch_compact(AddressSpaceDispatch *d)
292 {
293     if (d->phys_map.skip) {
294         phys_page_compact(&d->phys_map, d->map.nodes);
295     }
296 }
297
298 static inline bool section_covers_addr(const MemoryRegionSection *section,
299                                        hwaddr addr)
300 {
301     /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
302      * the section must cover the entire address space.
303      */
304     return int128_gethi(section->size) ||
305            range_covers_byte(section->offset_within_address_space,
306                              int128_getlo(section->size), addr);
307 }
308
309 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
310 {
311     PhysPageEntry lp = d->phys_map, *p;
312     Node *nodes = d->map.nodes;
313     MemoryRegionSection *sections = d->map.sections;
314     hwaddr index = addr >> TARGET_PAGE_BITS;
315     int i;
316
317     for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
318         if (lp.ptr == PHYS_MAP_NODE_NIL) {
319             return &sections[PHYS_SECTION_UNASSIGNED];
320         }
321         p = nodes[lp.ptr];
322         lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
323     }
324
325     if (section_covers_addr(&sections[lp.ptr], addr)) {
326         return &sections[lp.ptr];
327     } else {
328         return &sections[PHYS_SECTION_UNASSIGNED];
329     }
330 }
331
332 /* Called from RCU critical section */
333 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
334                                                         hwaddr addr,
335                                                         bool resolve_subpage)
336 {
337     MemoryRegionSection *section = qatomic_read(&d->mru_section);
338     subpage_t *subpage;
339
340     if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
341         !section_covers_addr(section, addr)) {
342         section = phys_page_find(d, addr);
343         qatomic_set(&d->mru_section, section);
344     }
345     if (resolve_subpage && section->mr->subpage) {
346         subpage = container_of(section->mr, subpage_t, iomem);
347         section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
348     }
349     return section;
350 }
351
352 /* Called from RCU critical section */
353 static MemoryRegionSection *
354 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
355                                  hwaddr *plen, bool resolve_subpage)
356 {
357     MemoryRegionSection *section;
358     MemoryRegion *mr;
359     Int128 diff;
360
361     section = address_space_lookup_region(d, addr, resolve_subpage);
362     /* Compute offset within MemoryRegionSection */
363     addr -= section->offset_within_address_space;
364
365     /* Compute offset within MemoryRegion */
366     *xlat = addr + section->offset_within_region;
367
368     mr = section->mr;
369
370     /* MMIO registers can be expected to perform full-width accesses based only
371      * on their address, without considering adjacent registers that could
372      * decode to completely different MemoryRegions.  When such registers
373      * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
374      * regions overlap wildly.  For this reason we cannot clamp the accesses
375      * here.
376      *
377      * If the length is small (as is the case for address_space_ldl/stl),
378      * everything works fine.  If the incoming length is large, however,
379      * the caller really has to do the clamping through memory_access_size.
380      */
381     if (memory_region_is_ram(mr)) {
382         diff = int128_sub(section->size, int128_make64(addr));
383         *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
384     }
385     return section;
386 }
387
388 /**
389  * address_space_translate_iommu - translate an address through an IOMMU
390  * memory region and then through the target address space.
391  *
392  * @iommu_mr: the IOMMU memory region that we start the translation from
393  * @addr: the address to be translated through the MMU
394  * @xlat: the translated address offset within the destination memory region.
395  *        It cannot be %NULL.
396  * @plen_out: valid read/write length of the translated address. It
397  *            cannot be %NULL.
398  * @page_mask_out: page mask for the translated address. This
399  *            should only be meaningful for IOMMU translated
400  *            addresses, since there may be huge pages that this bit
401  *            would tell. It can be %NULL if we don't care about it.
402  * @is_write: whether the translation operation is for write
403  * @is_mmio: whether this can be MMIO, set true if it can
404  * @target_as: the address space targeted by the IOMMU
405  * @attrs: transaction attributes
406  *
407  * This function is called from RCU critical section.  It is the common
408  * part of flatview_do_translate and address_space_translate_cached.
409  */
410 static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
411                                                          hwaddr *xlat,
412                                                          hwaddr *plen_out,
413                                                          hwaddr *page_mask_out,
414                                                          bool is_write,
415                                                          bool is_mmio,
416                                                          AddressSpace **target_as,
417                                                          MemTxAttrs attrs)
418 {
419     MemoryRegionSection *section;
420     hwaddr page_mask = (hwaddr)-1;
421
422     do {
423         hwaddr addr = *xlat;
424         IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
425         int iommu_idx = 0;
426         IOMMUTLBEntry iotlb;
427
428         if (imrc->attrs_to_index) {
429             iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
430         }
431
432         iotlb = imrc->translate(iommu_mr, addr, is_write ?
433                                 IOMMU_WO : IOMMU_RO, iommu_idx);
434
435         if (!(iotlb.perm & (1 << is_write))) {
436             goto unassigned;
437         }
438
439         addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
440                 | (addr & iotlb.addr_mask));
441         page_mask &= iotlb.addr_mask;
442         *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
443         *target_as = iotlb.target_as;
444
445         section = address_space_translate_internal(
446                 address_space_to_dispatch(iotlb.target_as), addr, xlat,
447                 plen_out, is_mmio);
448
449         iommu_mr = memory_region_get_iommu(section->mr);
450     } while (unlikely(iommu_mr));
451
452     if (page_mask_out) {
453         *page_mask_out = page_mask;
454     }
455     return *section;
456
457 unassigned:
458     return (MemoryRegionSection) { .mr = &io_mem_unassigned };
459 }
460
461 /**
462  * flatview_do_translate - translate an address in FlatView
463  *
464  * @fv: the flat view that we want to translate on
465  * @addr: the address to be translated in above address space
466  * @xlat: the translated address offset within memory region. It
467  *        cannot be @NULL.
468  * @plen_out: valid read/write length of the translated address. It
469  *            can be @NULL when we don't care about it.
470  * @page_mask_out: page mask for the translated address. This
471  *            should only be meaningful for IOMMU translated
472  *            addresses, since there may be huge pages that this bit
473  *            would tell. It can be @NULL if we don't care about it.
474  * @is_write: whether the translation operation is for write
475  * @is_mmio: whether this can be MMIO, set true if it can
476  * @target_as: the address space targeted by the IOMMU
477  * @attrs: memory transaction attributes
478  *
479  * This function is called from RCU critical section
480  */
481 static MemoryRegionSection flatview_do_translate(FlatView *fv,
482                                                  hwaddr addr,
483                                                  hwaddr *xlat,
484                                                  hwaddr *plen_out,
485                                                  hwaddr *page_mask_out,
486                                                  bool is_write,
487                                                  bool is_mmio,
488                                                  AddressSpace **target_as,
489                                                  MemTxAttrs attrs)
490 {
491     MemoryRegionSection *section;
492     IOMMUMemoryRegion *iommu_mr;
493     hwaddr plen = (hwaddr)(-1);
494
495     if (!plen_out) {
496         plen_out = &plen;
497     }
498
499     section = address_space_translate_internal(
500             flatview_to_dispatch(fv), addr, xlat,
501             plen_out, is_mmio);
502
503     iommu_mr = memory_region_get_iommu(section->mr);
504     if (unlikely(iommu_mr)) {
505         return address_space_translate_iommu(iommu_mr, xlat,
506                                              plen_out, page_mask_out,
507                                              is_write, is_mmio,
508                                              target_as, attrs);
509     }
510     if (page_mask_out) {
511         /* Not behind an IOMMU, use default page size. */
512         *page_mask_out = ~TARGET_PAGE_MASK;
513     }
514
515     return *section;
516 }
517
518 /* Called from RCU critical section */
519 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
520                                             bool is_write, MemTxAttrs attrs)
521 {
522     MemoryRegionSection section;
523     hwaddr xlat, page_mask;
524
525     /*
526      * This can never be MMIO, and we don't really care about plen,
527      * but page mask.
528      */
529     section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
530                                     NULL, &page_mask, is_write, false, &as,
531                                     attrs);
532
533     /* Illegal translation */
534     if (section.mr == &io_mem_unassigned) {
535         goto iotlb_fail;
536     }
537
538     /* Convert memory region offset into address space offset */
539     xlat += section.offset_within_address_space -
540         section.offset_within_region;
541
542     return (IOMMUTLBEntry) {
543         .target_as = as,
544         .iova = addr & ~page_mask,
545         .translated_addr = xlat & ~page_mask,
546         .addr_mask = page_mask,
547         /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
548         .perm = IOMMU_RW,
549     };
550
551 iotlb_fail:
552     return (IOMMUTLBEntry) {0};
553 }
554
555 /* Called from RCU critical section */
556 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
557                                  hwaddr *plen, bool is_write,
558                                  MemTxAttrs attrs)
559 {
560     MemoryRegion *mr;
561     MemoryRegionSection section;
562     AddressSpace *as = NULL;
563
564     /* This can be MMIO, so setup MMIO bit. */
565     section = flatview_do_translate(fv, addr, xlat, plen, NULL,
566                                     is_write, true, &as, attrs);
567     mr = section.mr;
568
569     if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
570         hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
571         *plen = MIN(page, *plen);
572     }
573
574     return mr;
575 }
576
577 typedef struct TCGIOMMUNotifier {
578     IOMMUNotifier n;
579     MemoryRegion *mr;
580     CPUState *cpu;
581     int iommu_idx;
582     bool active;
583 } TCGIOMMUNotifier;
584
585 static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
586 {
587     TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
588
589     if (!notifier->active) {
590         return;
591     }
592     tlb_flush(notifier->cpu);
593     notifier->active = false;
594     /* We leave the notifier struct on the list to avoid reallocating it later.
595      * Generally the number of IOMMUs a CPU deals with will be small.
596      * In any case we can't unregister the iommu notifier from a notify
597      * callback.
598      */
599 }
600
601 static void tcg_register_iommu_notifier(CPUState *cpu,
602                                         IOMMUMemoryRegion *iommu_mr,
603                                         int iommu_idx)
604 {
605     /* Make sure this CPU has an IOMMU notifier registered for this
606      * IOMMU/IOMMU index combination, so that we can flush its TLB
607      * when the IOMMU tells us the mappings we've cached have changed.
608      */
609     MemoryRegion *mr = MEMORY_REGION(iommu_mr);
610     TCGIOMMUNotifier *notifier = NULL;
611     int i;
612
613     for (i = 0; i < cpu->iommu_notifiers->len; i++) {
614         notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
615         if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
616             break;
617         }
618     }
619     if (i == cpu->iommu_notifiers->len) {
620         /* Not found, add a new entry at the end of the array */
621         cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
622         notifier = g_new0(TCGIOMMUNotifier, 1);
623         g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
624
625         notifier->mr = mr;
626         notifier->iommu_idx = iommu_idx;
627         notifier->cpu = cpu;
628         /* Rather than trying to register interest in the specific part
629          * of the iommu's address space that we've accessed and then
630          * expand it later as subsequent accesses touch more of it, we
631          * just register interest in the whole thing, on the assumption
632          * that iommu reconfiguration will be rare.
633          */
634         iommu_notifier_init(&notifier->n,
635                             tcg_iommu_unmap_notify,
636                             IOMMU_NOTIFIER_UNMAP,
637                             0,
638                             HWADDR_MAX,
639                             iommu_idx);
640         memory_region_register_iommu_notifier(notifier->mr, &notifier->n,
641                                               &error_fatal);
642     }
643
644     if (!notifier->active) {
645         notifier->active = true;
646     }
647 }
648
649 void tcg_iommu_free_notifier_list(CPUState *cpu)
650 {
651     /* Destroy the CPU's notifier list */
652     int i;
653     TCGIOMMUNotifier *notifier;
654
655     for (i = 0; i < cpu->iommu_notifiers->len; i++) {
656         notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
657         memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
658         g_free(notifier);
659     }
660     g_array_free(cpu->iommu_notifiers, true);
661 }
662
663 void tcg_iommu_init_notifier_list(CPUState *cpu)
664 {
665     cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
666 }
667
668 /* Called from RCU critical section */
669 MemoryRegionSection *
670 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
671                                   hwaddr *xlat, hwaddr *plen,
672                                   MemTxAttrs attrs, int *prot)
673 {
674     MemoryRegionSection *section;
675     IOMMUMemoryRegion *iommu_mr;
676     IOMMUMemoryRegionClass *imrc;
677     IOMMUTLBEntry iotlb;
678     int iommu_idx;
679     AddressSpaceDispatch *d =
680         qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
681
682     for (;;) {
683         section = address_space_translate_internal(d, addr, &addr, plen, false);
684
685         iommu_mr = memory_region_get_iommu(section->mr);
686         if (!iommu_mr) {
687             break;
688         }
689
690         imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
691
692         iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
693         tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
694         /* We need all the permissions, so pass IOMMU_NONE so the IOMMU
695          * doesn't short-cut its translation table walk.
696          */
697         iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
698         addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
699                 | (addr & iotlb.addr_mask));
700         /* Update the caller's prot bits to remove permissions the IOMMU
701          * is giving us a failure response for. If we get down to no
702          * permissions left at all we can give up now.
703          */
704         if (!(iotlb.perm & IOMMU_RO)) {
705             *prot &= ~(PAGE_READ | PAGE_EXEC);
706         }
707         if (!(iotlb.perm & IOMMU_WO)) {
708             *prot &= ~PAGE_WRITE;
709         }
710
711         if (!*prot) {
712             goto translate_fail;
713         }
714
715         d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
716     }
717
718     assert(!memory_region_is_iommu(section->mr));
719     *xlat = addr;
720     return section;
721
722 translate_fail:
723     return &d->map.sections[PHYS_SECTION_UNASSIGNED];
724 }
725
726 void cpu_address_space_init(CPUState *cpu, int asidx,
727                             const char *prefix, MemoryRegion *mr)
728 {
729     CPUAddressSpace *newas;
730     AddressSpace *as = g_new0(AddressSpace, 1);
731     char *as_name;
732
733     assert(mr);
734     as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
735     address_space_init(as, mr, as_name);
736     g_free(as_name);
737
738     /* Target code should have set num_ases before calling us */
739     assert(asidx < cpu->num_ases);
740
741     if (asidx == 0) {
742         /* address space 0 gets the convenience alias */
743         cpu->as = as;
744     }
745
746     /* KVM cannot currently support multiple address spaces. */
747     assert(asidx == 0 || !kvm_enabled());
748
749     if (!cpu->cpu_ases) {
750         cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
751     }
752
753     newas = &cpu->cpu_ases[asidx];
754     newas->cpu = cpu;
755     newas->as = as;
756     if (tcg_enabled()) {
757         newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
758         newas->tcg_as_listener.commit = tcg_commit;
759         memory_listener_register(&newas->tcg_as_listener, as);
760     }
761 }
762
763 AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
764 {
765     /* Return the AddressSpace corresponding to the specified index */
766     return cpu->cpu_ases[asidx].as;
767 }
768
769 /* Add a watchpoint.  */
770 int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
771                           int flags, CPUWatchpoint **watchpoint)
772 {
773     CPUWatchpoint *wp;
774     vaddr in_page;
775
776     /* forbid ranges which are empty or run off the end of the address space */
777     if (len == 0 || (addr + len - 1) < addr) {
778         error_report("tried to set invalid watchpoint at %"
779                      VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
780         return -EINVAL;
781     }
782     wp = g_malloc(sizeof(*wp));
783
784     wp->vaddr = addr;
785     wp->len = len;
786     wp->flags = flags;
787
788     /* keep all GDB-injected watchpoints in front */
789     if (flags & BP_GDB) {
790         QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
791     } else {
792         QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
793     }
794
795     in_page = -(addr | TARGET_PAGE_MASK);
796     if (len <= in_page) {
797         tlb_flush_page(cpu, addr);
798     } else {
799         tlb_flush(cpu);
800     }
801
802     if (watchpoint)
803         *watchpoint = wp;
804     return 0;
805 }
806
807 /* Remove a specific watchpoint.  */
808 int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
809                           int flags)
810 {
811     CPUWatchpoint *wp;
812
813     QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
814         if (addr == wp->vaddr && len == wp->len
815                 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
816             cpu_watchpoint_remove_by_ref(cpu, wp);
817             return 0;
818         }
819     }
820     return -ENOENT;
821 }
822
823 /* Remove a specific watchpoint by reference.  */
824 void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
825 {
826     QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
827
828     tlb_flush_page(cpu, watchpoint->vaddr);
829
830     g_free(watchpoint);
831 }
832
833 /* Remove all matching watchpoints.  */
834 void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
835 {
836     CPUWatchpoint *wp, *next;
837
838     QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
839         if (wp->flags & mask) {
840             cpu_watchpoint_remove_by_ref(cpu, wp);
841         }
842     }
843 }
844
845 #ifdef CONFIG_TCG
846 /* Return true if this watchpoint address matches the specified
847  * access (ie the address range covered by the watchpoint overlaps
848  * partially or completely with the address range covered by the
849  * access).
850  */
851 static inline bool watchpoint_address_matches(CPUWatchpoint *wp,
852                                               vaddr addr, vaddr len)
853 {
854     /* We know the lengths are non-zero, but a little caution is
855      * required to avoid errors in the case where the range ends
856      * exactly at the top of the address space and so addr + len
857      * wraps round to zero.
858      */
859     vaddr wpend = wp->vaddr + wp->len - 1;
860     vaddr addrend = addr + len - 1;
861
862     return !(addr > wpend || wp->vaddr > addrend);
863 }
864
865 /* Return flags for watchpoints that match addr + prot.  */
866 int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len)
867 {
868     CPUWatchpoint *wp;
869     int ret = 0;
870
871     QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
872         if (watchpoint_address_matches(wp, addr, len)) {
873             ret |= wp->flags;
874         }
875     }
876     return ret;
877 }
878
879 /* Generate a debug exception if a watchpoint has been hit.  */
880 void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
881                           MemTxAttrs attrs, int flags, uintptr_t ra)
882 {
883     CPUClass *cc = CPU_GET_CLASS(cpu);
884     CPUWatchpoint *wp;
885
886     assert(tcg_enabled());
887     if (cpu->watchpoint_hit) {
888         /*
889          * We re-entered the check after replacing the TB.
890          * Now raise the debug interrupt so that it will
891          * trigger after the current instruction.
892          */
893         qemu_mutex_lock_iothread();
894         cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
895         qemu_mutex_unlock_iothread();
896         return;
897     }
898
899     if (cc->tcg_ops->adjust_watchpoint_address) {
900         /* this is currently used only by ARM BE32 */
901         addr = cc->tcg_ops->adjust_watchpoint_address(cpu, addr, len);
902     }
903     QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
904         if (watchpoint_address_matches(wp, addr, len)
905             && (wp->flags & flags)) {
906             if (replay_running_debug()) {
907                 /*
908                  * Don't process the watchpoints when we are
909                  * in a reverse debugging operation.
910                  */
911                 replay_breakpoint();
912                 return;
913             }
914             if (flags == BP_MEM_READ) {
915                 wp->flags |= BP_WATCHPOINT_HIT_READ;
916             } else {
917                 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
918             }
919             wp->hitaddr = MAX(addr, wp->vaddr);
920             wp->hitattrs = attrs;
921             if (!cpu->watchpoint_hit) {
922                 if (wp->flags & BP_CPU && cc->tcg_ops->debug_check_watchpoint &&
923                     !cc->tcg_ops->debug_check_watchpoint(cpu, wp)) {
924                     wp->flags &= ~BP_WATCHPOINT_HIT;
925                     continue;
926                 }
927                 cpu->watchpoint_hit = wp;
928
929                 mmap_lock();
930                 tb_check_watchpoint(cpu, ra);
931                 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
932                     cpu->exception_index = EXCP_DEBUG;
933                     mmap_unlock();
934                     cpu_loop_exit_restore(cpu, ra);
935                 } else {
936                     /* Force execution of one insn next time.  */
937                     cpu->cflags_next_tb = 1 | curr_cflags(cpu);
938                     mmap_unlock();
939                     if (ra) {
940                         cpu_restore_state(cpu, ra, true);
941                     }
942                     cpu_loop_exit_noexc(cpu);
943                 }
944             }
945         } else {
946             wp->flags &= ~BP_WATCHPOINT_HIT;
947         }
948     }
949 }
950
951 #endif /* CONFIG_TCG */
952
953 /* Called from RCU critical section */
954 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
955 {
956     RAMBlock *block;
957
958     block = qatomic_rcu_read(&ram_list.mru_block);
959     if (block && addr - block->offset < block->max_length) {
960         return block;
961     }
962     RAMBLOCK_FOREACH(block) {
963         if (addr - block->offset < block->max_length) {
964             goto found;
965         }
966     }
967
968     fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
969     abort();
970
971 found:
972     /* It is safe to write mru_block outside the iothread lock.  This
973      * is what happens:
974      *
975      *     mru_block = xxx
976      *     rcu_read_unlock()
977      *                                        xxx removed from list
978      *                  rcu_read_lock()
979      *                  read mru_block
980      *                                        mru_block = NULL;
981      *                                        call_rcu(reclaim_ramblock, xxx);
982      *                  rcu_read_unlock()
983      *
984      * qatomic_rcu_set is not needed here.  The block was already published
985      * when it was placed into the list.  Here we're just making an extra
986      * copy of the pointer.
987      */
988     ram_list.mru_block = block;
989     return block;
990 }
991
992 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
993 {
994     CPUState *cpu;
995     ram_addr_t start1;
996     RAMBlock *block;
997     ram_addr_t end;
998
999     assert(tcg_enabled());
1000     end = TARGET_PAGE_ALIGN(start + length);
1001     start &= TARGET_PAGE_MASK;
1002
1003     RCU_READ_LOCK_GUARD();
1004     block = qemu_get_ram_block(start);
1005     assert(block == qemu_get_ram_block(end - 1));
1006     start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1007     CPU_FOREACH(cpu) {
1008         tlb_reset_dirty(cpu, start1, length);
1009     }
1010 }
1011
1012 /* Note: start and end must be within the same ram block.  */
1013 bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1014                                               ram_addr_t length,
1015                                               unsigned client)
1016 {
1017     DirtyMemoryBlocks *blocks;
1018     unsigned long end, page, start_page;
1019     bool dirty = false;
1020     RAMBlock *ramblock;
1021     uint64_t mr_offset, mr_size;
1022
1023     if (length == 0) {
1024         return false;
1025     }
1026
1027     end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1028     start_page = start >> TARGET_PAGE_BITS;
1029     page = start_page;
1030
1031     WITH_RCU_READ_LOCK_GUARD() {
1032         blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1033         ramblock = qemu_get_ram_block(start);
1034         /* Range sanity check on the ramblock */
1035         assert(start >= ramblock->offset &&
1036                start + length <= ramblock->offset + ramblock->used_length);
1037
1038         while (page < end) {
1039             unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1040             unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1041             unsigned long num = MIN(end - page,
1042                                     DIRTY_MEMORY_BLOCK_SIZE - offset);
1043
1044             dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1045                                                   offset, num);
1046             page += num;
1047         }
1048
1049         mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
1050         mr_size = (end - start_page) << TARGET_PAGE_BITS;
1051         memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
1052     }
1053
1054     if (dirty && tcg_enabled()) {
1055         tlb_reset_dirty_range_all(start, length);
1056     }
1057
1058     return dirty;
1059 }
1060
1061 DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1062     (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
1063 {
1064     DirtyMemoryBlocks *blocks;
1065     ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
1066     unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1067     ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1068     ram_addr_t last  = QEMU_ALIGN_UP(start + length, align);
1069     DirtyBitmapSnapshot *snap;
1070     unsigned long page, end, dest;
1071
1072     snap = g_malloc0(sizeof(*snap) +
1073                      ((last - first) >> (TARGET_PAGE_BITS + 3)));
1074     snap->start = first;
1075     snap->end   = last;
1076
1077     page = first >> TARGET_PAGE_BITS;
1078     end  = last  >> TARGET_PAGE_BITS;
1079     dest = 0;
1080
1081     WITH_RCU_READ_LOCK_GUARD() {
1082         blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1083
1084         while (page < end) {
1085             unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1086             unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1087             unsigned long num = MIN(end - page,
1088                                     DIRTY_MEMORY_BLOCK_SIZE - offset);
1089
1090             assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1091             assert(QEMU_IS_ALIGNED(num,    (1 << BITS_PER_LEVEL)));
1092             offset >>= BITS_PER_LEVEL;
1093
1094             bitmap_copy_and_clear_atomic(snap->dirty + dest,
1095                                          blocks->blocks[idx] + offset,
1096                                          num);
1097             page += num;
1098             dest += num >> BITS_PER_LEVEL;
1099         }
1100     }
1101
1102     if (tcg_enabled()) {
1103         tlb_reset_dirty_range_all(start, length);
1104     }
1105
1106     memory_region_clear_dirty_bitmap(mr, offset, length);
1107
1108     return snap;
1109 }
1110
1111 bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1112                                             ram_addr_t start,
1113                                             ram_addr_t length)
1114 {
1115     unsigned long page, end;
1116
1117     assert(start >= snap->start);
1118     assert(start + length <= snap->end);
1119
1120     end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1121     page = (start - snap->start) >> TARGET_PAGE_BITS;
1122
1123     while (page < end) {
1124         if (test_bit(page, snap->dirty)) {
1125             return true;
1126         }
1127         page++;
1128     }
1129     return false;
1130 }
1131
1132 /* Called from RCU critical section */
1133 hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1134                                        MemoryRegionSection *section)
1135 {
1136     AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
1137     return section - d->map.sections;
1138 }
1139
1140 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
1141                             uint16_t section);
1142 static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1143
1144 static uint16_t phys_section_add(PhysPageMap *map,
1145                                  MemoryRegionSection *section)
1146 {
1147     /* The physical section number is ORed with a page-aligned
1148      * pointer to produce the iotlb entries.  Thus it should
1149      * never overflow into the page-aligned value.
1150      */
1151     assert(map->sections_nb < TARGET_PAGE_SIZE);
1152
1153     if (map->sections_nb == map->sections_nb_alloc) {
1154         map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1155         map->sections = g_renew(MemoryRegionSection, map->sections,
1156                                 map->sections_nb_alloc);
1157     }
1158     map->sections[map->sections_nb] = *section;
1159     memory_region_ref(section->mr);
1160     return map->sections_nb++;
1161 }
1162
1163 static void phys_section_destroy(MemoryRegion *mr)
1164 {
1165     bool have_sub_page = mr->subpage;
1166
1167     memory_region_unref(mr);
1168
1169     if (have_sub_page) {
1170         subpage_t *subpage = container_of(mr, subpage_t, iomem);
1171         object_unref(OBJECT(&subpage->iomem));
1172         g_free(subpage);
1173     }
1174 }
1175
1176 static void phys_sections_free(PhysPageMap *map)
1177 {
1178     while (map->sections_nb > 0) {
1179         MemoryRegionSection *section = &map->sections[--map->sections_nb];
1180         phys_section_destroy(section->mr);
1181     }
1182     g_free(map->sections);
1183     g_free(map->nodes);
1184 }
1185
1186 static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1187 {
1188     AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1189     subpage_t *subpage;
1190     hwaddr base = section->offset_within_address_space
1191         & TARGET_PAGE_MASK;
1192     MemoryRegionSection *existing = phys_page_find(d, base);
1193     MemoryRegionSection subsection = {
1194         .offset_within_address_space = base,
1195         .size = int128_make64(TARGET_PAGE_SIZE),
1196     };
1197     hwaddr start, end;
1198
1199     assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1200
1201     if (!(existing->mr->subpage)) {
1202         subpage = subpage_init(fv, base);
1203         subsection.fv = fv;
1204         subsection.mr = &subpage->iomem;
1205         phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1206                       phys_section_add(&d->map, &subsection));
1207     } else {
1208         subpage = container_of(existing->mr, subpage_t, iomem);
1209     }
1210     start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1211     end = start + int128_get64(section->size) - 1;
1212     subpage_register(subpage, start, end,
1213                      phys_section_add(&d->map, section));
1214 }
1215
1216
1217 static void register_multipage(FlatView *fv,
1218                                MemoryRegionSection *section)
1219 {
1220     AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1221     hwaddr start_addr = section->offset_within_address_space;
1222     uint16_t section_index = phys_section_add(&d->map, section);
1223     uint64_t num_pages = int128_get64(int128_rshift(section->size,
1224                                                     TARGET_PAGE_BITS));
1225
1226     assert(num_pages);
1227     phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1228 }
1229
1230 /*
1231  * The range in *section* may look like this:
1232  *
1233  *      |s|PPPPPPP|s|
1234  *
1235  * where s stands for subpage and P for page.
1236  */
1237 void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1238 {
1239     MemoryRegionSection remain = *section;
1240     Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1241
1242     /* register first subpage */
1243     if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1244         uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1245                         - remain.offset_within_address_space;
1246
1247         MemoryRegionSection now = remain;
1248         now.size = int128_min(int128_make64(left), now.size);
1249         register_subpage(fv, &now);
1250         if (int128_eq(remain.size, now.size)) {
1251             return;
1252         }
1253         remain.size = int128_sub(remain.size, now.size);
1254         remain.offset_within_address_space += int128_get64(now.size);
1255         remain.offset_within_region += int128_get64(now.size);
1256     }
1257
1258     /* register whole pages */
1259     if (int128_ge(remain.size, page_size)) {
1260         MemoryRegionSection now = remain;
1261         now.size = int128_and(now.size, int128_neg(page_size));
1262         register_multipage(fv, &now);
1263         if (int128_eq(remain.size, now.size)) {
1264             return;
1265         }
1266         remain.size = int128_sub(remain.size, now.size);
1267         remain.offset_within_address_space += int128_get64(now.size);
1268         remain.offset_within_region += int128_get64(now.size);
1269     }
1270
1271     /* register last subpage */
1272     register_subpage(fv, &remain);
1273 }
1274
1275 void qemu_flush_coalesced_mmio_buffer(void)
1276 {
1277     if (kvm_enabled())
1278         kvm_flush_coalesced_mmio_buffer();
1279 }
1280
1281 void qemu_mutex_lock_ramlist(void)
1282 {
1283     qemu_mutex_lock(&ram_list.mutex);
1284 }
1285
1286 void qemu_mutex_unlock_ramlist(void)
1287 {
1288     qemu_mutex_unlock(&ram_list.mutex);
1289 }
1290
1291 void ram_block_dump(Monitor *mon)
1292 {
1293     RAMBlock *block;
1294     char *psize;
1295
1296     RCU_READ_LOCK_GUARD();
1297     monitor_printf(mon, "%24s %8s  %18s %18s %18s\n",
1298                    "Block Name", "PSize", "Offset", "Used", "Total");
1299     RAMBLOCK_FOREACH(block) {
1300         psize = size_to_str(block->page_size);
1301         monitor_printf(mon, "%24s %8s  0x%016" PRIx64 " 0x%016" PRIx64
1302                        " 0x%016" PRIx64 "\n", block->idstr, psize,
1303                        (uint64_t)block->offset,
1304                        (uint64_t)block->used_length,
1305                        (uint64_t)block->max_length);
1306         g_free(psize);
1307     }
1308 }
1309
1310 #ifdef __linux__
1311 /*
1312  * FIXME TOCTTOU: this iterates over memory backends' mem-path, which
1313  * may or may not name the same files / on the same filesystem now as
1314  * when we actually open and map them.  Iterate over the file
1315  * descriptors instead, and use qemu_fd_getpagesize().
1316  */
1317 static int find_min_backend_pagesize(Object *obj, void *opaque)
1318 {
1319     long *hpsize_min = opaque;
1320
1321     if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1322         HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1323         long hpsize = host_memory_backend_pagesize(backend);
1324
1325         if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
1326             *hpsize_min = hpsize;
1327         }
1328     }
1329
1330     return 0;
1331 }
1332
1333 static int find_max_backend_pagesize(Object *obj, void *opaque)
1334 {
1335     long *hpsize_max = opaque;
1336
1337     if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1338         HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1339         long hpsize = host_memory_backend_pagesize(backend);
1340
1341         if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1342             *hpsize_max = hpsize;
1343         }
1344     }
1345
1346     return 0;
1347 }
1348
1349 /*
1350  * TODO: We assume right now that all mapped host memory backends are
1351  * used as RAM, however some might be used for different purposes.
1352  */
1353 long qemu_minrampagesize(void)
1354 {
1355     long hpsize = LONG_MAX;
1356     Object *memdev_root = object_resolve_path("/objects", NULL);
1357
1358     object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
1359     return hpsize;
1360 }
1361
1362 long qemu_maxrampagesize(void)
1363 {
1364     long pagesize = 0;
1365     Object *memdev_root = object_resolve_path("/objects", NULL);
1366
1367     object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
1368     return pagesize;
1369 }
1370 #else
1371 long qemu_minrampagesize(void)
1372 {
1373     return qemu_real_host_page_size;
1374 }
1375 long qemu_maxrampagesize(void)
1376 {
1377     return qemu_real_host_page_size;
1378 }
1379 #endif
1380
1381 #ifdef CONFIG_POSIX
1382 static int64_t get_file_size(int fd)
1383 {
1384     int64_t size;
1385 #if defined(__linux__)
1386     struct stat st;
1387
1388     if (fstat(fd, &st) < 0) {
1389         return -errno;
1390     }
1391
1392     /* Special handling for devdax character devices */
1393     if (S_ISCHR(st.st_mode)) {
1394         g_autofree char *subsystem_path = NULL;
1395         g_autofree char *subsystem = NULL;
1396
1397         subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1398                                          major(st.st_rdev), minor(st.st_rdev));
1399         subsystem = g_file_read_link(subsystem_path, NULL);
1400
1401         if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
1402             g_autofree char *size_path = NULL;
1403             g_autofree char *size_str = NULL;
1404
1405             size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
1406                                     major(st.st_rdev), minor(st.st_rdev));
1407
1408             if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
1409                 return g_ascii_strtoll(size_str, NULL, 0);
1410             }
1411         }
1412     }
1413 #endif /* defined(__linux__) */
1414
1415     /* st.st_size may be zero for special files yet lseek(2) works */
1416     size = lseek(fd, 0, SEEK_END);
1417     if (size < 0) {
1418         return -errno;
1419     }
1420     return size;
1421 }
1422
1423 static int64_t get_file_align(int fd)
1424 {
1425     int64_t align = -1;
1426 #if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1427     struct stat st;
1428
1429     if (fstat(fd, &st) < 0) {
1430         return -errno;
1431     }
1432
1433     /* Special handling for devdax character devices */
1434     if (S_ISCHR(st.st_mode)) {
1435         g_autofree char *path = NULL;
1436         g_autofree char *rpath = NULL;
1437         struct daxctl_ctx *ctx;
1438         struct daxctl_region *region;
1439         int rc = 0;
1440
1441         path = g_strdup_printf("/sys/dev/char/%d:%d",
1442                     major(st.st_rdev), minor(st.st_rdev));
1443         rpath = realpath(path, NULL);
1444
1445         rc = daxctl_new(&ctx);
1446         if (rc) {
1447             return -1;
1448         }
1449
1450         daxctl_region_foreach(ctx, region) {
1451             if (strstr(rpath, daxctl_region_get_path(region))) {
1452                 align = daxctl_region_get_align(region);
1453                 break;
1454             }
1455         }
1456         daxctl_unref(ctx);
1457     }
1458 #endif /* defined(__linux__) && defined(CONFIG_LIBDAXCTL) */
1459
1460     return align;
1461 }
1462
1463 static int file_ram_open(const char *path,
1464                          const char *region_name,
1465                          bool readonly,
1466                          bool *created,
1467                          Error **errp)
1468 {
1469     char *filename;
1470     char *sanitized_name;
1471     char *c;
1472     int fd = -1;
1473
1474     *created = false;
1475     for (;;) {
1476         fd = open(path, readonly ? O_RDONLY : O_RDWR);
1477         if (fd >= 0) {
1478             /* @path names an existing file, use it */
1479             break;
1480         }
1481         if (errno == ENOENT) {
1482             /* @path names a file that doesn't exist, create it */
1483             fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1484             if (fd >= 0) {
1485                 *created = true;
1486                 break;
1487             }
1488         } else if (errno == EISDIR) {
1489             /* @path names a directory, create a file there */
1490             /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1491             sanitized_name = g_strdup(region_name);
1492             for (c = sanitized_name; *c != '\0'; c++) {
1493                 if (*c == '/') {
1494                     *c = '_';
1495                 }
1496             }
1497
1498             filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1499                                        sanitized_name);
1500             g_free(sanitized_name);
1501
1502             fd = mkstemp(filename);
1503             if (fd >= 0) {
1504                 unlink(filename);
1505                 g_free(filename);
1506                 break;
1507             }
1508             g_free(filename);
1509         }
1510         if (errno != EEXIST && errno != EINTR) {
1511             error_setg_errno(errp, errno,
1512                              "can't open backing store %s for guest RAM",
1513                              path);
1514             return -1;
1515         }
1516         /*
1517          * Try again on EINTR and EEXIST.  The latter happens when
1518          * something else creates the file between our two open().
1519          */
1520     }
1521
1522     return fd;
1523 }
1524
1525 static void *file_ram_alloc(RAMBlock *block,
1526                             ram_addr_t memory,
1527                             int fd,
1528                             bool readonly,
1529                             bool truncate,
1530                             off_t offset,
1531                             Error **errp)
1532 {
1533     void *area;
1534
1535     block->page_size = qemu_fd_getpagesize(fd);
1536     if (block->mr->align % block->page_size) {
1537         error_setg(errp, "alignment 0x%" PRIx64
1538                    " must be multiples of page size 0x%zx",
1539                    block->mr->align, block->page_size);
1540         return NULL;
1541     } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1542         error_setg(errp, "alignment 0x%" PRIx64
1543                    " must be a power of two", block->mr->align);
1544         return NULL;
1545     }
1546     block->mr->align = MAX(block->page_size, block->mr->align);
1547 #if defined(__s390x__)
1548     if (kvm_enabled()) {
1549         block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1550     }
1551 #endif
1552
1553     if (memory < block->page_size) {
1554         error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1555                    "or larger than page size 0x%zx",
1556                    memory, block->page_size);
1557         return NULL;
1558     }
1559
1560     memory = ROUND_UP(memory, block->page_size);
1561
1562     /*
1563      * ftruncate is not supported by hugetlbfs in older
1564      * hosts, so don't bother bailing out on errors.
1565      * If anything goes wrong with it under other filesystems,
1566      * mmap will fail.
1567      *
1568      * Do not truncate the non-empty backend file to avoid corrupting
1569      * the existing data in the file. Disabling shrinking is not
1570      * enough. For example, the current vNVDIMM implementation stores
1571      * the guest NVDIMM labels at the end of the backend file. If the
1572      * backend file is later extended, QEMU will not be able to find
1573      * those labels. Therefore, extending the non-empty backend file
1574      * is disabled as well.
1575      */
1576     if (truncate && ftruncate(fd, memory)) {
1577         perror("ftruncate");
1578     }
1579
1580     area = qemu_ram_mmap(fd, memory, block->mr->align, readonly,
1581                          block->flags & RAM_SHARED, block->flags & RAM_PMEM,
1582                          offset);
1583     if (area == MAP_FAILED) {
1584         error_setg_errno(errp, errno,
1585                          "unable to map backing store for guest RAM");
1586         return NULL;
1587     }
1588
1589     block->fd = fd;
1590     return area;
1591 }
1592 #endif
1593
1594 /* Allocate space within the ram_addr_t space that governs the
1595  * dirty bitmaps.
1596  * Called with the ramlist lock held.
1597  */
1598 static ram_addr_t find_ram_offset(ram_addr_t size)
1599 {
1600     RAMBlock *block, *next_block;
1601     ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1602
1603     assert(size != 0); /* it would hand out same offset multiple times */
1604
1605     if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1606         return 0;
1607     }
1608
1609     RAMBLOCK_FOREACH(block) {
1610         ram_addr_t candidate, next = RAM_ADDR_MAX;
1611
1612         /* Align blocks to start on a 'long' in the bitmap
1613          * which makes the bitmap sync'ing take the fast path.
1614          */
1615         candidate = block->offset + block->max_length;
1616         candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1617
1618         /* Search for the closest following block
1619          * and find the gap.
1620          */
1621         RAMBLOCK_FOREACH(next_block) {
1622             if (next_block->offset >= candidate) {
1623                 next = MIN(next, next_block->offset);
1624             }
1625         }
1626
1627         /* If it fits remember our place and remember the size
1628          * of gap, but keep going so that we might find a smaller
1629          * gap to fill so avoiding fragmentation.
1630          */
1631         if (next - candidate >= size && next - candidate < mingap) {
1632             offset = candidate;
1633             mingap = next - candidate;
1634         }
1635
1636         trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1637     }
1638
1639     if (offset == RAM_ADDR_MAX) {
1640         fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1641                 (uint64_t)size);
1642         abort();
1643     }
1644
1645     trace_find_ram_offset(size, offset);
1646
1647     return offset;
1648 }
1649
1650 static unsigned long last_ram_page(void)
1651 {
1652     RAMBlock *block;
1653     ram_addr_t last = 0;
1654
1655     RCU_READ_LOCK_GUARD();
1656     RAMBLOCK_FOREACH(block) {
1657         last = MAX(last, block->offset + block->max_length);
1658     }
1659     return last >> TARGET_PAGE_BITS;
1660 }
1661
1662 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1663 {
1664     int ret;
1665
1666     /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1667     if (!machine_dump_guest_core(current_machine)) {
1668         ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1669         if (ret) {
1670             perror("qemu_madvise");
1671             fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1672                             "but dump_guest_core=off specified\n");
1673         }
1674     }
1675 }
1676
1677 const char *qemu_ram_get_idstr(RAMBlock *rb)
1678 {
1679     return rb->idstr;
1680 }
1681
1682 void *qemu_ram_get_host_addr(RAMBlock *rb)
1683 {
1684     return rb->host;
1685 }
1686
1687 ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
1688 {
1689     return rb->offset;
1690 }
1691
1692 ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
1693 {
1694     return rb->used_length;
1695 }
1696
1697 bool qemu_ram_is_shared(RAMBlock *rb)
1698 {
1699     return rb->flags & RAM_SHARED;
1700 }
1701
1702 /* Note: Only set at the start of postcopy */
1703 bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1704 {
1705     return rb->flags & RAM_UF_ZEROPAGE;
1706 }
1707
1708 void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1709 {
1710     rb->flags |= RAM_UF_ZEROPAGE;
1711 }
1712
1713 bool qemu_ram_is_migratable(RAMBlock *rb)
1714 {
1715     return rb->flags & RAM_MIGRATABLE;
1716 }
1717
1718 void qemu_ram_set_migratable(RAMBlock *rb)
1719 {
1720     rb->flags |= RAM_MIGRATABLE;
1721 }
1722
1723 void qemu_ram_unset_migratable(RAMBlock *rb)
1724 {
1725     rb->flags &= ~RAM_MIGRATABLE;
1726 }
1727
1728 /* Called with iothread lock held.  */
1729 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1730 {
1731     RAMBlock *block;
1732
1733     assert(new_block);
1734     assert(!new_block->idstr[0]);
1735
1736     if (dev) {
1737         char *id = qdev_get_dev_path(dev);
1738         if (id) {
1739             snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1740             g_free(id);
1741         }
1742     }
1743     pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1744
1745     RCU_READ_LOCK_GUARD();
1746     RAMBLOCK_FOREACH(block) {
1747         if (block != new_block &&
1748             !strcmp(block->idstr, new_block->idstr)) {
1749             fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1750                     new_block->idstr);
1751             abort();
1752         }
1753     }
1754 }
1755
1756 /* Called with iothread lock held.  */
1757 void qemu_ram_unset_idstr(RAMBlock *block)
1758 {
1759     /* FIXME: arch_init.c assumes that this is not called throughout
1760      * migration.  Ignore the problem since hot-unplug during migration
1761      * does not work anyway.
1762      */
1763     if (block) {
1764         memset(block->idstr, 0, sizeof(block->idstr));
1765     }
1766 }
1767
1768 size_t qemu_ram_pagesize(RAMBlock *rb)
1769 {
1770     return rb->page_size;
1771 }
1772
1773 /* Returns the largest size of page in use */
1774 size_t qemu_ram_pagesize_largest(void)
1775 {
1776     RAMBlock *block;
1777     size_t largest = 0;
1778
1779     RAMBLOCK_FOREACH(block) {
1780         largest = MAX(largest, qemu_ram_pagesize(block));
1781     }
1782
1783     return largest;
1784 }
1785
1786 static int memory_try_enable_merging(void *addr, size_t len)
1787 {
1788     if (!machine_mem_merge(current_machine)) {
1789         /* disabled by the user */
1790         return 0;
1791     }
1792
1793     return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1794 }
1795
1796 /* Only legal before guest might have detected the memory size: e.g. on
1797  * incoming migration, or right after reset.
1798  *
1799  * As memory core doesn't know how is memory accessed, it is up to
1800  * resize callback to update device state and/or add assertions to detect
1801  * misuse, if necessary.
1802  */
1803 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1804 {
1805     const ram_addr_t unaligned_size = newsize;
1806
1807     assert(block);
1808
1809     newsize = HOST_PAGE_ALIGN(newsize);
1810
1811     if (block->used_length == newsize) {
1812         /*
1813          * We don't have to resize the ram block (which only knows aligned
1814          * sizes), however, we have to notify if the unaligned size changed.
1815          */
1816         if (unaligned_size != memory_region_size(block->mr)) {
1817             memory_region_set_size(block->mr, unaligned_size);
1818             if (block->resized) {
1819                 block->resized(block->idstr, unaligned_size, block->host);
1820             }
1821         }
1822         return 0;
1823     }
1824
1825     if (!(block->flags & RAM_RESIZEABLE)) {
1826         error_setg_errno(errp, EINVAL,
1827                          "Size mismatch: %s: 0x" RAM_ADDR_FMT
1828                          " != 0x" RAM_ADDR_FMT, block->idstr,
1829                          newsize, block->used_length);
1830         return -EINVAL;
1831     }
1832
1833     if (block->max_length < newsize) {
1834         error_setg_errno(errp, EINVAL,
1835                          "Size too large: %s: 0x" RAM_ADDR_FMT
1836                          " > 0x" RAM_ADDR_FMT, block->idstr,
1837                          newsize, block->max_length);
1838         return -EINVAL;
1839     }
1840
1841     cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1842     block->used_length = newsize;
1843     cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1844                                         DIRTY_CLIENTS_ALL);
1845     memory_region_set_size(block->mr, unaligned_size);
1846     if (block->resized) {
1847         block->resized(block->idstr, unaligned_size, block->host);
1848     }
1849     return 0;
1850 }
1851
1852 /*
1853  * Trigger sync on the given ram block for range [start, start + length]
1854  * with the backing store if one is available.
1855  * Otherwise no-op.
1856  * @Note: this is supposed to be a synchronous op.
1857  */
1858 void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
1859 {
1860     /* The requested range should fit in within the block range */
1861     g_assert((start + length) <= block->used_length);
1862
1863 #ifdef CONFIG_LIBPMEM
1864     /* The lack of support for pmem should not block the sync */
1865     if (ramblock_is_pmem(block)) {
1866         void *addr = ramblock_ptr(block, start);
1867         pmem_persist(addr, length);
1868         return;
1869     }
1870 #endif
1871     if (block->fd >= 0) {
1872         /**
1873          * Case there is no support for PMEM or the memory has not been
1874          * specified as persistent (or is not one) - use the msync.
1875          * Less optimal but still achieves the same goal
1876          */
1877         void *addr = ramblock_ptr(block, start);
1878         if (qemu_msync(addr, length, block->fd)) {
1879             warn_report("%s: failed to sync memory range: start: "
1880                     RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
1881                     __func__, start, length);
1882         }
1883     }
1884 }
1885
1886 /* Called with ram_list.mutex held */
1887 static void dirty_memory_extend(ram_addr_t old_ram_size,
1888                                 ram_addr_t new_ram_size)
1889 {
1890     ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1891                                              DIRTY_MEMORY_BLOCK_SIZE);
1892     ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1893                                              DIRTY_MEMORY_BLOCK_SIZE);
1894     int i;
1895
1896     /* Only need to extend if block count increased */
1897     if (new_num_blocks <= old_num_blocks) {
1898         return;
1899     }
1900
1901     for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1902         DirtyMemoryBlocks *old_blocks;
1903         DirtyMemoryBlocks *new_blocks;
1904         int j;
1905
1906         old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
1907         new_blocks = g_malloc(sizeof(*new_blocks) +
1908                               sizeof(new_blocks->blocks[0]) * new_num_blocks);
1909
1910         if (old_num_blocks) {
1911             memcpy(new_blocks->blocks, old_blocks->blocks,
1912                    old_num_blocks * sizeof(old_blocks->blocks[0]));
1913         }
1914
1915         for (j = old_num_blocks; j < new_num_blocks; j++) {
1916             new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1917         }
1918
1919         qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1920
1921         if (old_blocks) {
1922             g_free_rcu(old_blocks, rcu);
1923         }
1924     }
1925 }
1926
1927 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
1928 {
1929     RAMBlock *block;
1930     RAMBlock *last_block = NULL;
1931     ram_addr_t old_ram_size, new_ram_size;
1932     Error *err = NULL;
1933
1934     old_ram_size = last_ram_page();
1935
1936     qemu_mutex_lock_ramlist();
1937     new_block->offset = find_ram_offset(new_block->max_length);
1938
1939     if (!new_block->host) {
1940         if (xen_enabled()) {
1941             xen_ram_alloc(new_block->offset, new_block->max_length,
1942                           new_block->mr, &err);
1943             if (err) {
1944                 error_propagate(errp, err);
1945                 qemu_mutex_unlock_ramlist();
1946                 return;
1947             }
1948         } else {
1949             new_block->host = qemu_anon_ram_alloc(new_block->max_length,
1950                                                   &new_block->mr->align,
1951                                                   shared);
1952             if (!new_block->host) {
1953                 error_setg_errno(errp, errno,
1954                                  "cannot set up guest memory '%s'",
1955                                  memory_region_name(new_block->mr));
1956                 qemu_mutex_unlock_ramlist();
1957                 return;
1958             }
1959             memory_try_enable_merging(new_block->host, new_block->max_length);
1960         }
1961     }
1962
1963     new_ram_size = MAX(old_ram_size,
1964               (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1965     if (new_ram_size > old_ram_size) {
1966         dirty_memory_extend(old_ram_size, new_ram_size);
1967     }
1968     /* Keep the list sorted from biggest to smallest block.  Unlike QTAILQ,
1969      * QLIST (which has an RCU-friendly variant) does not have insertion at
1970      * tail, so save the last element in last_block.
1971      */
1972     RAMBLOCK_FOREACH(block) {
1973         last_block = block;
1974         if (block->max_length < new_block->max_length) {
1975             break;
1976         }
1977     }
1978     if (block) {
1979         QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1980     } else if (last_block) {
1981         QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
1982     } else { /* list is empty */
1983         QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
1984     }
1985     ram_list.mru_block = NULL;
1986
1987     /* Write list before version */
1988     smp_wmb();
1989     ram_list.version++;
1990     qemu_mutex_unlock_ramlist();
1991
1992     cpu_physical_memory_set_dirty_range(new_block->offset,
1993                                         new_block->used_length,
1994                                         DIRTY_CLIENTS_ALL);
1995
1996     if (new_block->host) {
1997         qemu_ram_setup_dump(new_block->host, new_block->max_length);
1998         qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
1999         /*
2000          * MADV_DONTFORK is also needed by KVM in absence of synchronous MMU
2001          * Configure it unless the machine is a qtest server, in which case
2002          * KVM is not used and it may be forked (eg for fuzzing purposes).
2003          */
2004         if (!qtest_enabled()) {
2005             qemu_madvise(new_block->host, new_block->max_length,
2006                          QEMU_MADV_DONTFORK);
2007         }
2008         ram_block_notify_add(new_block->host, new_block->max_length);
2009     }
2010 }
2011
2012 #ifdef CONFIG_POSIX
2013 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2014                                  uint32_t ram_flags, int fd, off_t offset,
2015                                  bool readonly, Error **errp)
2016 {
2017     RAMBlock *new_block;
2018     Error *local_err = NULL;
2019     int64_t file_size, file_align;
2020
2021     /* Just support these ram flags by now. */
2022     assert((ram_flags & ~(RAM_SHARED | RAM_PMEM)) == 0);
2023
2024     if (xen_enabled()) {
2025         error_setg(errp, "-mem-path not supported with Xen");
2026         return NULL;
2027     }
2028
2029     if (kvm_enabled() && !kvm_has_sync_mmu()) {
2030         error_setg(errp,
2031                    "host lacks kvm mmu notifiers, -mem-path unsupported");
2032         return NULL;
2033     }
2034
2035     size = HOST_PAGE_ALIGN(size);
2036     file_size = get_file_size(fd);
2037     if (file_size > 0 && file_size < size) {
2038         error_setg(errp, "backing store size 0x%" PRIx64
2039                    " does not match 'size' option 0x" RAM_ADDR_FMT,
2040                    file_size, size);
2041         return NULL;
2042     }
2043
2044     file_align = get_file_align(fd);
2045     if (file_align > 0 && mr && file_align > mr->align) {
2046         error_setg(errp, "backing store align 0x%" PRIx64
2047                    " is larger than 'align' option 0x%" PRIx64,
2048                    file_align, mr->align);
2049         return NULL;
2050     }
2051
2052     new_block = g_malloc0(sizeof(*new_block));
2053     new_block->mr = mr;
2054     new_block->used_length = size;
2055     new_block->max_length = size;
2056     new_block->flags = ram_flags;
2057     new_block->host = file_ram_alloc(new_block, size, fd, readonly,
2058                                      !file_size, offset, errp);
2059     if (!new_block->host) {
2060         g_free(new_block);
2061         return NULL;
2062     }
2063
2064     ram_block_add(new_block, &local_err, ram_flags & RAM_SHARED);
2065     if (local_err) {
2066         g_free(new_block);
2067         error_propagate(errp, local_err);
2068         return NULL;
2069     }
2070     return new_block;
2071
2072 }
2073
2074
2075 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2076                                    uint32_t ram_flags, const char *mem_path,
2077                                    bool readonly, Error **errp)
2078 {
2079     int fd;
2080     bool created;
2081     RAMBlock *block;
2082
2083     fd = file_ram_open(mem_path, memory_region_name(mr), readonly, &created,
2084                        errp);
2085     if (fd < 0) {
2086         return NULL;
2087     }
2088
2089     block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, 0, readonly, errp);
2090     if (!block) {
2091         if (created) {
2092             unlink(mem_path);
2093         }
2094         close(fd);
2095         return NULL;
2096     }
2097
2098     return block;
2099 }
2100 #endif
2101
2102 static
2103 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2104                                   void (*resized)(const char*,
2105                                                   uint64_t length,
2106                                                   void *host),
2107                                   void *host, bool resizeable, bool share,
2108                                   MemoryRegion *mr, Error **errp)
2109 {
2110     RAMBlock *new_block;
2111     Error *local_err = NULL;
2112
2113     size = HOST_PAGE_ALIGN(size);
2114     max_size = HOST_PAGE_ALIGN(max_size);
2115     new_block = g_malloc0(sizeof(*new_block));
2116     new_block->mr = mr;
2117     new_block->resized = resized;
2118     new_block->used_length = size;
2119     new_block->max_length = max_size;
2120     assert(max_size >= size);
2121     new_block->fd = -1;
2122     new_block->page_size = qemu_real_host_page_size;
2123     new_block->host = host;
2124     if (host) {
2125         new_block->flags |= RAM_PREALLOC;
2126     }
2127     if (resizeable) {
2128         new_block->flags |= RAM_RESIZEABLE;
2129     }
2130     ram_block_add(new_block, &local_err, share);
2131     if (local_err) {
2132         g_free(new_block);
2133         error_propagate(errp, local_err);
2134         return NULL;
2135     }
2136     return new_block;
2137 }
2138
2139 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2140                                    MemoryRegion *mr, Error **errp)
2141 {
2142     return qemu_ram_alloc_internal(size, size, NULL, host, false,
2143                                    false, mr, errp);
2144 }
2145
2146 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2147                          MemoryRegion *mr, Error **errp)
2148 {
2149     return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2150                                    share, mr, errp);
2151 }
2152
2153 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2154                                      void (*resized)(const char*,
2155                                                      uint64_t length,
2156                                                      void *host),
2157                                      MemoryRegion *mr, Error **errp)
2158 {
2159     return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2160                                    false, mr, errp);
2161 }
2162
2163 static void reclaim_ramblock(RAMBlock *block)
2164 {
2165     if (block->flags & RAM_PREALLOC) {
2166         ;
2167     } else if (xen_enabled()) {
2168         xen_invalidate_map_cache_entry(block->host);
2169 #ifndef _WIN32
2170     } else if (block->fd >= 0) {
2171         qemu_ram_munmap(block->fd, block->host, block->max_length);
2172         close(block->fd);
2173 #endif
2174     } else {
2175         qemu_anon_ram_free(block->host, block->max_length);
2176     }
2177     g_free(block);
2178 }
2179
2180 void qemu_ram_free(RAMBlock *block)
2181 {
2182     if (!block) {
2183         return;
2184     }
2185
2186     if (block->host) {
2187         ram_block_notify_remove(block->host, block->max_length);
2188     }
2189
2190     qemu_mutex_lock_ramlist();
2191     QLIST_REMOVE_RCU(block, next);
2192     ram_list.mru_block = NULL;
2193     /* Write list before version */
2194     smp_wmb();
2195     ram_list.version++;
2196     call_rcu(block, reclaim_ramblock, rcu);
2197     qemu_mutex_unlock_ramlist();
2198 }
2199
2200 #ifndef _WIN32
2201 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2202 {
2203     RAMBlock *block;
2204     ram_addr_t offset;
2205     int flags;
2206     void *area, *vaddr;
2207
2208     RAMBLOCK_FOREACH(block) {
2209         offset = addr - block->offset;
2210         if (offset < block->max_length) {
2211             vaddr = ramblock_ptr(block, offset);
2212             if (block->flags & RAM_PREALLOC) {
2213                 ;
2214             } else if (xen_enabled()) {
2215                 abort();
2216             } else {
2217                 flags = MAP_FIXED;
2218                 if (block->fd >= 0) {
2219                     flags |= (block->flags & RAM_SHARED ?
2220                               MAP_SHARED : MAP_PRIVATE);
2221                     area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2222                                 flags, block->fd, offset);
2223                 } else {
2224                     flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2225                     area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2226                                 flags, -1, 0);
2227                 }
2228                 if (area != vaddr) {
2229                     error_report("Could not remap addr: "
2230                                  RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2231                                  length, addr);
2232                     exit(1);
2233                 }
2234                 memory_try_enable_merging(vaddr, length);
2235                 qemu_ram_setup_dump(vaddr, length);
2236             }
2237         }
2238     }
2239 }
2240 #endif /* !_WIN32 */
2241
2242 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2243  * This should not be used for general purpose DMA.  Use address_space_map
2244  * or address_space_rw instead. For local memory (e.g. video ram) that the
2245  * device owns, use memory_region_get_ram_ptr.
2246  *
2247  * Called within RCU critical section.
2248  */
2249 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2250 {
2251     RAMBlock *block = ram_block;
2252
2253     if (block == NULL) {
2254         block = qemu_get_ram_block(addr);
2255         addr -= block->offset;
2256     }
2257
2258     if (xen_enabled() && block->host == NULL) {
2259         /* We need to check if the requested address is in the RAM
2260          * because we don't want to map the entire memory in QEMU.
2261          * In that case just map until the end of the page.
2262          */
2263         if (block->offset == 0) {
2264             return xen_map_cache(addr, 0, 0, false);
2265         }
2266
2267         block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2268     }
2269     return ramblock_ptr(block, addr);
2270 }
2271
2272 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2273  * but takes a size argument.
2274  *
2275  * Called within RCU critical section.
2276  */
2277 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2278                                  hwaddr *size, bool lock)
2279 {
2280     RAMBlock *block = ram_block;
2281     if (*size == 0) {
2282         return NULL;
2283     }
2284
2285     if (block == NULL) {
2286         block = qemu_get_ram_block(addr);
2287         addr -= block->offset;
2288     }
2289     *size = MIN(*size, block->max_length - addr);
2290
2291     if (xen_enabled() && block->host == NULL) {
2292         /* We need to check if the requested address is in the RAM
2293          * because we don't want to map the entire memory in QEMU.
2294          * In that case just map the requested area.
2295          */
2296         if (block->offset == 0) {
2297             return xen_map_cache(addr, *size, lock, lock);
2298         }
2299
2300         block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2301     }
2302
2303     return ramblock_ptr(block, addr);
2304 }
2305
2306 /* Return the offset of a hostpointer within a ramblock */
2307 ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2308 {
2309     ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2310     assert((uintptr_t)host >= (uintptr_t)rb->host);
2311     assert(res < rb->max_length);
2312
2313     return res;
2314 }
2315
2316 /*
2317  * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2318  * in that RAMBlock.
2319  *
2320  * ptr: Host pointer to look up
2321  * round_offset: If true round the result offset down to a page boundary
2322  * *ram_addr: set to result ram_addr
2323  * *offset: set to result offset within the RAMBlock
2324  *
2325  * Returns: RAMBlock (or NULL if not found)
2326  *
2327  * By the time this function returns, the returned pointer is not protected
2328  * by RCU anymore.  If the caller is not within an RCU critical section and
2329  * does not hold the iothread lock, it must have other means of protecting the
2330  * pointer, such as a reference to the region that includes the incoming
2331  * ram_addr_t.
2332  */
2333 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2334                                    ram_addr_t *offset)
2335 {
2336     RAMBlock *block;
2337     uint8_t *host = ptr;
2338
2339     if (xen_enabled()) {
2340         ram_addr_t ram_addr;
2341         RCU_READ_LOCK_GUARD();
2342         ram_addr = xen_ram_addr_from_mapcache(ptr);
2343         block = qemu_get_ram_block(ram_addr);
2344         if (block) {
2345             *offset = ram_addr - block->offset;
2346         }
2347         return block;
2348     }
2349
2350     RCU_READ_LOCK_GUARD();
2351     block = qatomic_rcu_read(&ram_list.mru_block);
2352     if (block && block->host && host - block->host < block->max_length) {
2353         goto found;
2354     }
2355
2356     RAMBLOCK_FOREACH(block) {
2357         /* This case append when the block is not mapped. */
2358         if (block->host == NULL) {
2359             continue;
2360         }
2361         if (host - block->host < block->max_length) {
2362             goto found;
2363         }
2364     }
2365
2366     return NULL;
2367
2368 found:
2369     *offset = (host - block->host);
2370     if (round_offset) {
2371         *offset &= TARGET_PAGE_MASK;
2372     }
2373     return block;
2374 }
2375
2376 /*
2377  * Finds the named RAMBlock
2378  *
2379  * name: The name of RAMBlock to find
2380  *
2381  * Returns: RAMBlock (or NULL if not found)
2382  */
2383 RAMBlock *qemu_ram_block_by_name(const char *name)
2384 {
2385     RAMBlock *block;
2386
2387     RAMBLOCK_FOREACH(block) {
2388         if (!strcmp(name, block->idstr)) {
2389             return block;
2390         }
2391     }
2392
2393     return NULL;
2394 }
2395
2396 /* Some of the softmmu routines need to translate from a host pointer
2397    (typically a TLB entry) back to a ram offset.  */
2398 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2399 {
2400     RAMBlock *block;
2401     ram_addr_t offset;
2402
2403     block = qemu_ram_block_from_host(ptr, false, &offset);
2404     if (!block) {
2405         return RAM_ADDR_INVALID;
2406     }
2407
2408     return block->offset + offset;
2409 }
2410
2411 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2412                                  MemTxAttrs attrs, void *buf, hwaddr len);
2413 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2414                                   const void *buf, hwaddr len);
2415 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2416                                   bool is_write, MemTxAttrs attrs);
2417
2418 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2419                                 unsigned len, MemTxAttrs attrs)
2420 {
2421     subpage_t *subpage = opaque;
2422     uint8_t buf[8];
2423     MemTxResult res;
2424
2425 #if defined(DEBUG_SUBPAGE)
2426     printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2427            subpage, len, addr);
2428 #endif
2429     res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2430     if (res) {
2431         return res;
2432     }
2433     *data = ldn_p(buf, len);
2434     return MEMTX_OK;
2435 }
2436
2437 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2438                                  uint64_t value, unsigned len, MemTxAttrs attrs)
2439 {
2440     subpage_t *subpage = opaque;
2441     uint8_t buf[8];
2442
2443 #if defined(DEBUG_SUBPAGE)
2444     printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2445            " value %"PRIx64"\n",
2446            __func__, subpage, len, addr, value);
2447 #endif
2448     stn_p(buf, len, value);
2449     return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2450 }
2451
2452 static bool subpage_accepts(void *opaque, hwaddr addr,
2453                             unsigned len, bool is_write,
2454                             MemTxAttrs attrs)
2455 {
2456     subpage_t *subpage = opaque;
2457 #if defined(DEBUG_SUBPAGE)
2458     printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2459            __func__, subpage, is_write ? 'w' : 'r', len, addr);
2460 #endif
2461
2462     return flatview_access_valid(subpage->fv, addr + subpage->base,
2463                                  len, is_write, attrs);
2464 }
2465
2466 static const MemoryRegionOps subpage_ops = {
2467     .read_with_attrs = subpage_read,
2468     .write_with_attrs = subpage_write,
2469     .impl.min_access_size = 1,
2470     .impl.max_access_size = 8,
2471     .valid.min_access_size = 1,
2472     .valid.max_access_size = 8,
2473     .valid.accepts = subpage_accepts,
2474     .endianness = DEVICE_NATIVE_ENDIAN,
2475 };
2476
2477 static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2478                             uint16_t section)
2479 {
2480     int idx, eidx;
2481
2482     if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2483         return -1;
2484     idx = SUBPAGE_IDX(start);
2485     eidx = SUBPAGE_IDX(end);
2486 #if defined(DEBUG_SUBPAGE)
2487     printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2488            __func__, mmio, start, end, idx, eidx, section);
2489 #endif
2490     for (; idx <= eidx; idx++) {
2491         mmio->sub_section[idx] = section;
2492     }
2493
2494     return 0;
2495 }
2496
2497 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2498 {
2499     subpage_t *mmio;
2500
2501     /* mmio->sub_section is set to PHYS_SECTION_UNASSIGNED with g_malloc0 */
2502     mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2503     mmio->fv = fv;
2504     mmio->base = base;
2505     memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2506                           NULL, TARGET_PAGE_SIZE);
2507     mmio->iomem.subpage = true;
2508 #if defined(DEBUG_SUBPAGE)
2509     printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2510            mmio, base, TARGET_PAGE_SIZE);
2511 #endif
2512
2513     return mmio;
2514 }
2515
2516 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2517 {
2518     assert(fv);
2519     MemoryRegionSection section = {
2520         .fv = fv,
2521         .mr = mr,
2522         .offset_within_address_space = 0,
2523         .offset_within_region = 0,
2524         .size = int128_2_64(),
2525     };
2526
2527     return phys_section_add(map, &section);
2528 }
2529
2530 MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2531                                       hwaddr index, MemTxAttrs attrs)
2532 {
2533     int asidx = cpu_asidx_from_attrs(cpu, attrs);
2534     CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2535     AddressSpaceDispatch *d = qatomic_rcu_read(&cpuas->memory_dispatch);
2536     MemoryRegionSection *sections = d->map.sections;
2537
2538     return &sections[index & ~TARGET_PAGE_MASK];
2539 }
2540
2541 static void io_mem_init(void)
2542 {
2543     memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2544                           NULL, UINT64_MAX);
2545 }
2546
2547 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2548 {
2549     AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2550     uint16_t n;
2551
2552     n = dummy_section(&d->map, fv, &io_mem_unassigned);
2553     assert(n == PHYS_SECTION_UNASSIGNED);
2554
2555     d->phys_map  = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2556
2557     return d;
2558 }
2559
2560 void address_space_dispatch_free(AddressSpaceDispatch *d)
2561 {
2562     phys_sections_free(&d->map);
2563     g_free(d);
2564 }
2565
2566 static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2567 {
2568 }
2569
2570 static void tcg_log_global_after_sync(MemoryListener *listener)
2571 {
2572     CPUAddressSpace *cpuas;
2573
2574     /* Wait for the CPU to end the current TB.  This avoids the following
2575      * incorrect race:
2576      *
2577      *      vCPU                         migration
2578      *      ----------------------       -------------------------
2579      *      TLB check -> slow path
2580      *        notdirty_mem_write
2581      *          write to RAM
2582      *          mark dirty
2583      *                                   clear dirty flag
2584      *      TLB check -> fast path
2585      *                                   read memory
2586      *        write to RAM
2587      *
2588      * by pushing the migration thread's memory read after the vCPU thread has
2589      * written the memory.
2590      */
2591     if (replay_mode == REPLAY_MODE_NONE) {
2592         /*
2593          * VGA can make calls to this function while updating the screen.
2594          * In record/replay mode this causes a deadlock, because
2595          * run_on_cpu waits for rr mutex. Therefore no races are possible
2596          * in this case and no need for making run_on_cpu when
2597          * record/replay is not enabled.
2598          */
2599         cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2600         run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2601     }
2602 }
2603
2604 static void tcg_commit(MemoryListener *listener)
2605 {
2606     CPUAddressSpace *cpuas;
2607     AddressSpaceDispatch *d;
2608
2609     assert(tcg_enabled());
2610     /* since each CPU stores ram addresses in its TLB cache, we must
2611        reset the modified entries */
2612     cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2613     cpu_reloading_memory_map();
2614     /* The CPU and TLB are protected by the iothread lock.
2615      * We reload the dispatch pointer now because cpu_reloading_memory_map()
2616      * may have split the RCU critical section.
2617      */
2618     d = address_space_to_dispatch(cpuas->as);
2619     qatomic_rcu_set(&cpuas->memory_dispatch, d);
2620     tlb_flush(cpuas->cpu);
2621 }
2622
2623 static void memory_map_init(void)
2624 {
2625     system_memory = g_malloc(sizeof(*system_memory));
2626
2627     memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2628     address_space_init(&address_space_memory, system_memory, "memory");
2629
2630     system_io = g_malloc(sizeof(*system_io));
2631     memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2632                           65536);
2633     address_space_init(&address_space_io, system_io, "I/O");
2634 }
2635
2636 MemoryRegion *get_system_memory(void)
2637 {
2638     return system_memory;
2639 }
2640
2641 MemoryRegion *get_system_io(void)
2642 {
2643     return system_io;
2644 }
2645
2646 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2647                                      hwaddr length)
2648 {
2649     uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2650     addr += memory_region_get_ram_addr(mr);
2651
2652     /* No early return if dirty_log_mask is or becomes 0, because
2653      * cpu_physical_memory_set_dirty_range will still call
2654      * xen_modified_memory.
2655      */
2656     if (dirty_log_mask) {
2657         dirty_log_mask =
2658             cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2659     }
2660     if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2661         assert(tcg_enabled());
2662         tb_invalidate_phys_range(addr, addr + length);
2663         dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2664     }
2665     cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2666 }
2667
2668 void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
2669 {
2670     /*
2671      * In principle this function would work on other memory region types too,
2672      * but the ROM device use case is the only one where this operation is
2673      * necessary.  Other memory regions should use the
2674      * address_space_read/write() APIs.
2675      */
2676     assert(memory_region_is_romd(mr));
2677
2678     invalidate_and_set_dirty(mr, addr, size);
2679 }
2680
2681 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2682 {
2683     unsigned access_size_max = mr->ops->valid.max_access_size;
2684
2685     /* Regions are assumed to support 1-4 byte accesses unless
2686        otherwise specified.  */
2687     if (access_size_max == 0) {
2688         access_size_max = 4;
2689     }
2690
2691     /* Bound the maximum access by the alignment of the address.  */
2692     if (!mr->ops->impl.unaligned) {
2693         unsigned align_size_max = addr & -addr;
2694         if (align_size_max != 0 && align_size_max < access_size_max) {
2695             access_size_max = align_size_max;
2696         }
2697     }
2698
2699     /* Don't attempt accesses larger than the maximum.  */
2700     if (l > access_size_max) {
2701         l = access_size_max;
2702     }
2703     l = pow2floor(l);
2704
2705     return l;
2706 }
2707
2708 static bool prepare_mmio_access(MemoryRegion *mr)
2709 {
2710     bool release_lock = false;
2711
2712     if (!qemu_mutex_iothread_locked()) {
2713         qemu_mutex_lock_iothread();
2714         release_lock = true;
2715     }
2716     if (mr->flush_coalesced_mmio) {
2717         qemu_flush_coalesced_mmio_buffer();
2718     }
2719
2720     return release_lock;
2721 }
2722
2723 /* Called within RCU critical section.  */
2724 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
2725                                            MemTxAttrs attrs,
2726                                            const void *ptr,
2727                                            hwaddr len, hwaddr addr1,
2728                                            hwaddr l, MemoryRegion *mr)
2729 {
2730     uint8_t *ram_ptr;
2731     uint64_t val;
2732     MemTxResult result = MEMTX_OK;
2733     bool release_lock = false;
2734     const uint8_t *buf = ptr;
2735
2736     for (;;) {
2737         if (!memory_access_is_direct(mr, true)) {
2738             release_lock |= prepare_mmio_access(mr);
2739             l = memory_access_size(mr, l, addr1);
2740             /* XXX: could force current_cpu to NULL to avoid
2741                potential bugs */
2742             val = ldn_he_p(buf, l);
2743             result |= memory_region_dispatch_write(mr, addr1, val,
2744                                                    size_memop(l), attrs);
2745         } else {
2746             /* RAM case */
2747             ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2748             memcpy(ram_ptr, buf, l);
2749             invalidate_and_set_dirty(mr, addr1, l);
2750         }
2751
2752         if (release_lock) {
2753             qemu_mutex_unlock_iothread();
2754             release_lock = false;
2755         }
2756
2757         len -= l;
2758         buf += l;
2759         addr += l;
2760
2761         if (!len) {
2762             break;
2763         }
2764
2765         l = len;
2766         mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2767     }
2768
2769     return result;
2770 }
2771
2772 /* Called from RCU critical section.  */
2773 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2774                                   const void *buf, hwaddr len)
2775 {
2776     hwaddr l;
2777     hwaddr addr1;
2778     MemoryRegion *mr;
2779     MemTxResult result = MEMTX_OK;
2780
2781     l = len;
2782     mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2783     result = flatview_write_continue(fv, addr, attrs, buf, len,
2784                                      addr1, l, mr);
2785
2786     return result;
2787 }
2788
2789 /* Called within RCU critical section.  */
2790 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
2791                                    MemTxAttrs attrs, void *ptr,
2792                                    hwaddr len, hwaddr addr1, hwaddr l,
2793                                    MemoryRegion *mr)
2794 {
2795     uint8_t *ram_ptr;
2796     uint64_t val;
2797     MemTxResult result = MEMTX_OK;
2798     bool release_lock = false;
2799     uint8_t *buf = ptr;
2800
2801     fuzz_dma_read_cb(addr, len, mr);
2802     for (;;) {
2803         if (!memory_access_is_direct(mr, false)) {
2804             /* I/O case */
2805             release_lock |= prepare_mmio_access(mr);
2806             l = memory_access_size(mr, l, addr1);
2807             result |= memory_region_dispatch_read(mr, addr1, &val,
2808                                                   size_memop(l), attrs);
2809             stn_he_p(buf, l, val);
2810         } else {
2811             /* RAM case */
2812             ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2813             memcpy(buf, ram_ptr, l);
2814         }
2815
2816         if (release_lock) {
2817             qemu_mutex_unlock_iothread();
2818             release_lock = false;
2819         }
2820
2821         len -= l;
2822         buf += l;
2823         addr += l;
2824
2825         if (!len) {
2826             break;
2827         }
2828
2829         l = len;
2830         mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2831     }
2832
2833     return result;
2834 }
2835
2836 /* Called from RCU critical section.  */
2837 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2838                                  MemTxAttrs attrs, void *buf, hwaddr len)
2839 {
2840     hwaddr l;
2841     hwaddr addr1;
2842     MemoryRegion *mr;
2843
2844     l = len;
2845     mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2846     return flatview_read_continue(fv, addr, attrs, buf, len,
2847                                   addr1, l, mr);
2848 }
2849
2850 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2851                                     MemTxAttrs attrs, void *buf, hwaddr len)
2852 {
2853     MemTxResult result = MEMTX_OK;
2854     FlatView *fv;
2855
2856     if (len > 0) {
2857         RCU_READ_LOCK_GUARD();
2858         fv = address_space_to_flatview(as);
2859         result = flatview_read(fv, addr, attrs, buf, len);
2860     }
2861
2862     return result;
2863 }
2864
2865 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2866                                 MemTxAttrs attrs,
2867                                 const void *buf, hwaddr len)
2868 {
2869     MemTxResult result = MEMTX_OK;
2870     FlatView *fv;
2871
2872     if (len > 0) {
2873         RCU_READ_LOCK_GUARD();
2874         fv = address_space_to_flatview(as);
2875         result = flatview_write(fv, addr, attrs, buf, len);
2876     }
2877
2878     return result;
2879 }
2880
2881 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2882                              void *buf, hwaddr len, bool is_write)
2883 {
2884     if (is_write) {
2885         return address_space_write(as, addr, attrs, buf, len);
2886     } else {
2887         return address_space_read_full(as, addr, attrs, buf, len);
2888     }
2889 }
2890
2891 void cpu_physical_memory_rw(hwaddr addr, void *buf,
2892                             hwaddr len, bool is_write)
2893 {
2894     address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
2895                      buf, len, is_write);
2896 }
2897
2898 enum write_rom_type {
2899     WRITE_DATA,
2900     FLUSH_CACHE,
2901 };
2902
2903 static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
2904                                                            hwaddr addr,
2905                                                            MemTxAttrs attrs,
2906                                                            const void *ptr,
2907                                                            hwaddr len,
2908                                                            enum write_rom_type type)
2909 {
2910     hwaddr l;
2911     uint8_t *ram_ptr;
2912     hwaddr addr1;
2913     MemoryRegion *mr;
2914     const uint8_t *buf = ptr;
2915
2916     RCU_READ_LOCK_GUARD();
2917     while (len > 0) {
2918         l = len;
2919         mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
2920
2921         if (!(memory_region_is_ram(mr) ||
2922               memory_region_is_romd(mr))) {
2923             l = memory_access_size(mr, l, addr1);
2924         } else {
2925             /* ROM/RAM case */
2926             ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2927             switch (type) {
2928             case WRITE_DATA:
2929                 memcpy(ram_ptr, buf, l);
2930                 invalidate_and_set_dirty(mr, addr1, l);
2931                 break;
2932             case FLUSH_CACHE:
2933                 flush_idcache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr, l);
2934                 break;
2935             }
2936         }
2937         len -= l;
2938         buf += l;
2939         addr += l;
2940     }
2941     return MEMTX_OK;
2942 }
2943
2944 /* used for ROM loading : can write in RAM and ROM */
2945 MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
2946                                     MemTxAttrs attrs,
2947                                     const void *buf, hwaddr len)
2948 {
2949     return address_space_write_rom_internal(as, addr, attrs,
2950                                             buf, len, WRITE_DATA);
2951 }
2952
2953 void cpu_flush_icache_range(hwaddr start, hwaddr len)
2954 {
2955     /*
2956      * This function should do the same thing as an icache flush that was
2957      * triggered from within the guest. For TCG we are always cache coherent,
2958      * so there is no need to flush anything. For KVM / Xen we need to flush
2959      * the host's instruction cache at least.
2960      */
2961     if (tcg_enabled()) {
2962         return;
2963     }
2964
2965     address_space_write_rom_internal(&address_space_memory,
2966                                      start, MEMTXATTRS_UNSPECIFIED,
2967                                      NULL, len, FLUSH_CACHE);
2968 }
2969
2970 typedef struct {
2971     MemoryRegion *mr;
2972     void *buffer;
2973     hwaddr addr;
2974     hwaddr len;
2975     bool in_use;
2976 } BounceBuffer;
2977
2978 static BounceBuffer bounce;
2979
2980 typedef struct MapClient {
2981     QEMUBH *bh;
2982     QLIST_ENTRY(MapClient) link;
2983 } MapClient;
2984
2985 QemuMutex map_client_list_lock;
2986 static QLIST_HEAD(, MapClient) map_client_list
2987     = QLIST_HEAD_INITIALIZER(map_client_list);
2988
2989 static void cpu_unregister_map_client_do(MapClient *client)
2990 {
2991     QLIST_REMOVE(client, link);
2992     g_free(client);
2993 }
2994
2995 static void cpu_notify_map_clients_locked(void)
2996 {
2997     MapClient *client;
2998
2999     while (!QLIST_EMPTY(&map_client_list)) {
3000         client = QLIST_FIRST(&map_client_list);
3001         qemu_bh_schedule(client->bh);
3002         cpu_unregister_map_client_do(client);
3003     }
3004 }
3005
3006 void cpu_register_map_client(QEMUBH *bh)
3007 {
3008     MapClient *client = g_malloc(sizeof(*client));
3009
3010     qemu_mutex_lock(&map_client_list_lock);
3011     client->bh = bh;
3012     QLIST_INSERT_HEAD(&map_client_list, client, link);
3013     if (!qatomic_read(&bounce.in_use)) {
3014         cpu_notify_map_clients_locked();
3015     }
3016     qemu_mutex_unlock(&map_client_list_lock);
3017 }
3018
3019 void cpu_exec_init_all(void)
3020 {
3021     qemu_mutex_init(&ram_list.mutex);
3022     /* The data structures we set up here depend on knowing the page size,
3023      * so no more changes can be made after this point.
3024      * In an ideal world, nothing we did before we had finished the
3025      * machine setup would care about the target page size, and we could
3026      * do this much later, rather than requiring board models to state
3027      * up front what their requirements are.
3028      */
3029     finalize_target_page_bits();
3030     io_mem_init();
3031     memory_map_init();
3032     qemu_mutex_init(&map_client_list_lock);
3033 }
3034
3035 void cpu_unregister_map_client(QEMUBH *bh)
3036 {
3037     MapClient *client;
3038
3039     qemu_mutex_lock(&map_client_list_lock);
3040     QLIST_FOREACH(client, &map_client_list, link) {
3041         if (client->bh == bh) {
3042             cpu_unregister_map_client_do(client);
3043             break;
3044         }
3045     }
3046     qemu_mutex_unlock(&map_client_list_lock);
3047 }
3048
3049 static void cpu_notify_map_clients(void)
3050 {
3051     qemu_mutex_lock(&map_client_list_lock);
3052     cpu_notify_map_clients_locked();
3053     qemu_mutex_unlock(&map_client_list_lock);
3054 }
3055
3056 static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
3057                                   bool is_write, MemTxAttrs attrs)
3058 {
3059     MemoryRegion *mr;
3060     hwaddr l, xlat;
3061
3062     while (len > 0) {
3063         l = len;
3064         mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3065         if (!memory_access_is_direct(mr, is_write)) {
3066             l = memory_access_size(mr, l, addr);
3067             if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3068                 return false;
3069             }
3070         }
3071
3072         len -= l;
3073         addr += l;
3074     }
3075     return true;
3076 }
3077
3078 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3079                                 hwaddr len, bool is_write,
3080                                 MemTxAttrs attrs)
3081 {
3082     FlatView *fv;
3083     bool result;
3084
3085     RCU_READ_LOCK_GUARD();
3086     fv = address_space_to_flatview(as);
3087     result = flatview_access_valid(fv, addr, len, is_write, attrs);
3088     return result;
3089 }
3090
3091 static hwaddr
3092 flatview_extend_translation(FlatView *fv, hwaddr addr,
3093                             hwaddr target_len,
3094                             MemoryRegion *mr, hwaddr base, hwaddr len,
3095                             bool is_write, MemTxAttrs attrs)
3096 {
3097     hwaddr done = 0;
3098     hwaddr xlat;
3099     MemoryRegion *this_mr;
3100
3101     for (;;) {
3102         target_len -= len;
3103         addr += len;
3104         done += len;
3105         if (target_len == 0) {
3106             return done;
3107         }
3108
3109         len = target_len;
3110         this_mr = flatview_translate(fv, addr, &xlat,
3111                                      &len, is_write, attrs);
3112         if (this_mr != mr || xlat != base + done) {
3113             return done;
3114         }
3115     }
3116 }
3117
3118 /* Map a physical memory region into a host virtual address.
3119  * May map a subset of the requested range, given by and returned in *plen.
3120  * May return NULL if resources needed to perform the mapping are exhausted.
3121  * Use only for reads OR writes - not for read-modify-write operations.
3122  * Use cpu_register_map_client() to know when retrying the map operation is
3123  * likely to succeed.
3124  */
3125 void *address_space_map(AddressSpace *as,
3126                         hwaddr addr,
3127                         hwaddr *plen,
3128                         bool is_write,
3129                         MemTxAttrs attrs)
3130 {
3131     hwaddr len = *plen;
3132     hwaddr l, xlat;
3133     MemoryRegion *mr;
3134     void *ptr;
3135     FlatView *fv;
3136
3137     if (len == 0) {
3138         return NULL;
3139     }
3140
3141     l = len;
3142     RCU_READ_LOCK_GUARD();
3143     fv = address_space_to_flatview(as);
3144     mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3145
3146     if (!memory_access_is_direct(mr, is_write)) {
3147         if (qatomic_xchg(&bounce.in_use, true)) {
3148             *plen = 0;
3149             return NULL;
3150         }
3151         /* Avoid unbounded allocations */
3152         l = MIN(l, TARGET_PAGE_SIZE);
3153         bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3154         bounce.addr = addr;
3155         bounce.len = l;
3156
3157         memory_region_ref(mr);
3158         bounce.mr = mr;
3159         if (!is_write) {
3160             flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3161                                bounce.buffer, l);
3162         }
3163
3164         *plen = l;
3165         return bounce.buffer;
3166     }
3167
3168
3169     memory_region_ref(mr);
3170     *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3171                                         l, is_write, attrs);
3172     fuzz_dma_read_cb(addr, *plen, mr);
3173     ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3174
3175     return ptr;
3176 }
3177
3178 /* Unmaps a memory region previously mapped by address_space_map().
3179  * Will also mark the memory as dirty if is_write is true.  access_len gives
3180  * the amount of memory that was actually read or written by the caller.
3181  */
3182 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3183                          bool is_write, hwaddr access_len)
3184 {
3185     if (buffer != bounce.buffer) {
3186         MemoryRegion *mr;
3187         ram_addr_t addr1;
3188
3189         mr = memory_region_from_host(buffer, &addr1);
3190         assert(mr != NULL);
3191         if (is_write) {
3192             invalidate_and_set_dirty(mr, addr1, access_len);
3193         }
3194         if (xen_enabled()) {
3195             xen_invalidate_map_cache_entry(buffer);
3196         }
3197         memory_region_unref(mr);
3198         return;
3199     }
3200     if (is_write) {
3201         address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3202                             bounce.buffer, access_len);
3203     }
3204     qemu_vfree(bounce.buffer);
3205     bounce.buffer = NULL;
3206     memory_region_unref(bounce.mr);
3207     qatomic_mb_set(&bounce.in_use, false);
3208     cpu_notify_map_clients();
3209 }
3210
3211 void *cpu_physical_memory_map(hwaddr addr,
3212                               hwaddr *plen,
3213                               bool is_write)
3214 {
3215     return address_space_map(&address_space_memory, addr, plen, is_write,
3216                              MEMTXATTRS_UNSPECIFIED);
3217 }
3218
3219 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3220                                bool is_write, hwaddr access_len)
3221 {
3222     return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3223 }
3224
3225 #define ARG1_DECL                AddressSpace *as
3226 #define ARG1                     as
3227 #define SUFFIX
3228 #define TRANSLATE(...)           address_space_translate(as, __VA_ARGS__)
3229 #define RCU_READ_LOCK(...)       rcu_read_lock()
3230 #define RCU_READ_UNLOCK(...)     rcu_read_unlock()
3231 #include "memory_ldst.c.inc"
3232
3233 int64_t address_space_cache_init(MemoryRegionCache *cache,
3234                                  AddressSpace *as,
3235                                  hwaddr addr,
3236                                  hwaddr len,
3237                                  bool is_write)
3238 {
3239     AddressSpaceDispatch *d;
3240     hwaddr l;
3241     MemoryRegion *mr;
3242     Int128 diff;
3243
3244     assert(len > 0);
3245
3246     l = len;
3247     cache->fv = address_space_get_flatview(as);
3248     d = flatview_to_dispatch(cache->fv);
3249     cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3250
3251     /*
3252      * cache->xlat is now relative to cache->mrs.mr, not to the section itself.
3253      * Take that into account to compute how many bytes are there between
3254      * cache->xlat and the end of the section.
3255      */
3256     diff = int128_sub(cache->mrs.size,
3257                       int128_make64(cache->xlat - cache->mrs.offset_within_region));
3258     l = int128_get64(int128_min(diff, int128_make64(l)));
3259
3260     mr = cache->mrs.mr;
3261     memory_region_ref(mr);
3262     if (memory_access_is_direct(mr, is_write)) {
3263         /* We don't care about the memory attributes here as we're only
3264          * doing this if we found actual RAM, which behaves the same
3265          * regardless of attributes; so UNSPECIFIED is fine.
3266          */
3267         l = flatview_extend_translation(cache->fv, addr, len, mr,
3268                                         cache->xlat, l, is_write,
3269                                         MEMTXATTRS_UNSPECIFIED);
3270         cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3271     } else {
3272         cache->ptr = NULL;
3273     }
3274
3275     cache->len = l;
3276     cache->is_write = is_write;
3277     return l;
3278 }
3279
3280 void address_space_cache_invalidate(MemoryRegionCache *cache,
3281                                     hwaddr addr,
3282                                     hwaddr access_len)
3283 {
3284     assert(cache->is_write);
3285     if (likely(cache->ptr)) {
3286         invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3287     }
3288 }
3289
3290 void address_space_cache_destroy(MemoryRegionCache *cache)
3291 {
3292     if (!cache->mrs.mr) {
3293         return;
3294     }
3295
3296     if (xen_enabled()) {
3297         xen_invalidate_map_cache_entry(cache->ptr);
3298     }
3299     memory_region_unref(cache->mrs.mr);
3300     flatview_unref(cache->fv);
3301     cache->mrs.mr = NULL;
3302     cache->fv = NULL;
3303 }
3304
3305 /* Called from RCU critical section.  This function has the same
3306  * semantics as address_space_translate, but it only works on a
3307  * predefined range of a MemoryRegion that was mapped with
3308  * address_space_cache_init.
3309  */
3310 static inline MemoryRegion *address_space_translate_cached(
3311     MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3312     hwaddr *plen, bool is_write, MemTxAttrs attrs)
3313 {
3314     MemoryRegionSection section;
3315     MemoryRegion *mr;
3316     IOMMUMemoryRegion *iommu_mr;
3317     AddressSpace *target_as;
3318
3319     assert(!cache->ptr);
3320     *xlat = addr + cache->xlat;
3321
3322     mr = cache->mrs.mr;
3323     iommu_mr = memory_region_get_iommu(mr);
3324     if (!iommu_mr) {
3325         /* MMIO region.  */
3326         return mr;
3327     }
3328
3329     section = address_space_translate_iommu(iommu_mr, xlat, plen,
3330                                             NULL, is_write, true,
3331                                             &target_as, attrs);
3332     return section.mr;
3333 }
3334
3335 /* Called from RCU critical section. address_space_read_cached uses this
3336  * out of line function when the target is an MMIO or IOMMU region.
3337  */
3338 MemTxResult
3339 address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3340                                    void *buf, hwaddr len)
3341 {
3342     hwaddr addr1, l;
3343     MemoryRegion *mr;
3344
3345     l = len;
3346     mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3347                                         MEMTXATTRS_UNSPECIFIED);
3348     return flatview_read_continue(cache->fv,
3349                                   addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3350                                   addr1, l, mr);
3351 }
3352
3353 /* Called from RCU critical section. address_space_write_cached uses this
3354  * out of line function when the target is an MMIO or IOMMU region.
3355  */
3356 MemTxResult
3357 address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3358                                     const void *buf, hwaddr len)
3359 {
3360     hwaddr addr1, l;
3361     MemoryRegion *mr;
3362
3363     l = len;
3364     mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3365                                         MEMTXATTRS_UNSPECIFIED);
3366     return flatview_write_continue(cache->fv,
3367                                    addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3368                                    addr1, l, mr);
3369 }
3370
3371 #define ARG1_DECL                MemoryRegionCache *cache
3372 #define ARG1                     cache
3373 #define SUFFIX                   _cached_slow
3374 #define TRANSLATE(...)           address_space_translate_cached(cache, __VA_ARGS__)
3375 #define RCU_READ_LOCK()          ((void)0)
3376 #define RCU_READ_UNLOCK()        ((void)0)
3377 #include "memory_ldst.c.inc"
3378
3379 /* virtual memory access for debug (includes writing to ROM) */
3380 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3381                         void *ptr, target_ulong len, bool is_write)
3382 {
3383     hwaddr phys_addr;
3384     target_ulong l, page;
3385     uint8_t *buf = ptr;
3386
3387     cpu_synchronize_state(cpu);
3388     while (len > 0) {
3389         int asidx;
3390         MemTxAttrs attrs;
3391         MemTxResult res;
3392
3393         page = addr & TARGET_PAGE_MASK;
3394         phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3395         asidx = cpu_asidx_from_attrs(cpu, attrs);
3396         /* if no physical page mapped, return an error */
3397         if (phys_addr == -1)
3398             return -1;
3399         l = (page + TARGET_PAGE_SIZE) - addr;
3400         if (l > len)
3401             l = len;
3402         phys_addr += (addr & ~TARGET_PAGE_MASK);
3403         if (is_write) {
3404             res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3405                                           attrs, buf, l);
3406         } else {
3407             res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3408                                      attrs, buf, l);
3409         }
3410         if (res != MEMTX_OK) {
3411             return -1;
3412         }
3413         len -= l;
3414         buf += l;
3415         addr += l;
3416     }
3417     return 0;
3418 }
3419
3420 /*
3421  * Allows code that needs to deal with migration bitmaps etc to still be built
3422  * target independent.
3423  */
3424 size_t qemu_target_page_size(void)
3425 {
3426     return TARGET_PAGE_SIZE;
3427 }
3428
3429 int qemu_target_page_bits(void)
3430 {
3431     return TARGET_PAGE_BITS;
3432 }
3433
3434 int qemu_target_page_bits_min(void)
3435 {
3436     return TARGET_PAGE_BITS_MIN;
3437 }
3438
3439 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3440 {
3441     MemoryRegion*mr;
3442     hwaddr l = 1;
3443     bool res;
3444
3445     RCU_READ_LOCK_GUARD();
3446     mr = address_space_translate(&address_space_memory,
3447                                  phys_addr, &phys_addr, &l, false,
3448                                  MEMTXATTRS_UNSPECIFIED);
3449
3450     res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3451     return res;
3452 }
3453
3454 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3455 {
3456     RAMBlock *block;
3457     int ret = 0;
3458
3459     RCU_READ_LOCK_GUARD();
3460     RAMBLOCK_FOREACH(block) {
3461         ret = func(block, opaque);
3462         if (ret) {
3463             break;
3464         }
3465     }
3466     return ret;
3467 }
3468
3469 /*
3470  * Unmap pages of memory from start to start+length such that
3471  * they a) read as 0, b) Trigger whatever fault mechanism
3472  * the OS provides for postcopy.
3473  * The pages must be unmapped by the end of the function.
3474  * Returns: 0 on success, none-0 on failure
3475  *
3476  */
3477 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3478 {
3479     int ret = -1;
3480
3481     uint8_t *host_startaddr = rb->host + start;
3482
3483     if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
3484         error_report("ram_block_discard_range: Unaligned start address: %p",
3485                      host_startaddr);
3486         goto err;
3487     }
3488
3489     if ((start + length) <= rb->used_length) {
3490         bool need_madvise, need_fallocate;
3491         if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
3492             error_report("ram_block_discard_range: Unaligned length: %zx",
3493                          length);
3494             goto err;
3495         }
3496
3497         errno = ENOTSUP; /* If we are missing MADVISE etc */
3498
3499         /* The logic here is messy;
3500          *    madvise DONTNEED fails for hugepages
3501          *    fallocate works on hugepages and shmem
3502          */
3503         need_madvise = (rb->page_size == qemu_host_page_size);
3504         need_fallocate = rb->fd != -1;
3505         if (need_fallocate) {
3506             /* For a file, this causes the area of the file to be zero'd
3507              * if read, and for hugetlbfs also causes it to be unmapped
3508              * so a userfault will trigger.
3509              */
3510 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3511             ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3512                             start, length);
3513             if (ret) {
3514                 ret = -errno;
3515                 error_report("ram_block_discard_range: Failed to fallocate "
3516                              "%s:%" PRIx64 " +%zx (%d)",
3517                              rb->idstr, start, length, ret);
3518                 goto err;
3519             }
3520 #else
3521             ret = -ENOSYS;
3522             error_report("ram_block_discard_range: fallocate not available/file"
3523                          "%s:%" PRIx64 " +%zx (%d)",
3524                          rb->idstr, start, length, ret);
3525             goto err;
3526 #endif
3527         }
3528         if (need_madvise) {
3529             /* For normal RAM this causes it to be unmapped,
3530              * for shared memory it causes the local mapping to disappear
3531              * and to fall back on the file contents (which we just
3532              * fallocate'd away).
3533              */
3534 #if defined(CONFIG_MADVISE)
3535             ret =  madvise(host_startaddr, length, MADV_DONTNEED);
3536             if (ret) {
3537                 ret = -errno;
3538                 error_report("ram_block_discard_range: Failed to discard range "
3539                              "%s:%" PRIx64 " +%zx (%d)",
3540                              rb->idstr, start, length, ret);
3541                 goto err;
3542             }
3543 #else
3544             ret = -ENOSYS;
3545             error_report("ram_block_discard_range: MADVISE not available"
3546                          "%s:%" PRIx64 " +%zx (%d)",
3547                          rb->idstr, start, length, ret);
3548             goto err;
3549 #endif
3550         }
3551         trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3552                                       need_madvise, need_fallocate, ret);
3553     } else {
3554         error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3555                      "/%zx/" RAM_ADDR_FMT")",
3556                      rb->idstr, start, length, rb->used_length);
3557     }
3558
3559 err:
3560     return ret;
3561 }
3562
3563 bool ramblock_is_pmem(RAMBlock *rb)
3564 {
3565     return rb->flags & RAM_PMEM;
3566 }
3567
3568 static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
3569 {
3570     if (start == end - 1) {
3571         qemu_printf("\t%3d      ", start);
3572     } else {
3573         qemu_printf("\t%3d..%-3d ", start, end - 1);
3574     }
3575     qemu_printf(" skip=%d ", skip);
3576     if (ptr == PHYS_MAP_NODE_NIL) {
3577         qemu_printf(" ptr=NIL");
3578     } else if (!skip) {
3579         qemu_printf(" ptr=#%d", ptr);
3580     } else {
3581         qemu_printf(" ptr=[%d]", ptr);
3582     }
3583     qemu_printf("\n");
3584 }
3585
3586 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3587                            int128_sub((size), int128_one())) : 0)
3588
3589 void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
3590 {
3591     int i;
3592
3593     qemu_printf("  Dispatch\n");
3594     qemu_printf("    Physical sections\n");
3595
3596     for (i = 0; i < d->map.sections_nb; ++i) {
3597         MemoryRegionSection *s = d->map.sections + i;
3598         const char *names[] = { " [unassigned]", " [not dirty]",
3599                                 " [ROM]", " [watch]" };
3600
3601         qemu_printf("      #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx
3602                     " %s%s%s%s%s",
3603             i,
3604             s->offset_within_address_space,
3605             s->offset_within_address_space + MR_SIZE(s->mr->size),
3606             s->mr->name ? s->mr->name : "(noname)",
3607             i < ARRAY_SIZE(names) ? names[i] : "",
3608             s->mr == root ? " [ROOT]" : "",
3609             s == d->mru_section ? " [MRU]" : "",
3610             s->mr->is_iommu ? " [iommu]" : "");
3611
3612         if (s->mr->alias) {
3613             qemu_printf(" alias=%s", s->mr->alias->name ?
3614                     s->mr->alias->name : "noname");
3615         }
3616         qemu_printf("\n");
3617     }
3618
3619     qemu_printf("    Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3620                P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3621     for (i = 0; i < d->map.nodes_nb; ++i) {
3622         int j, jprev;
3623         PhysPageEntry prev;
3624         Node *n = d->map.nodes + i;
3625
3626         qemu_printf("      [%d]\n", i);
3627
3628         for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3629             PhysPageEntry *pe = *n + j;
3630
3631             if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3632                 continue;
3633             }
3634
3635             mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3636
3637             jprev = j;
3638             prev = *pe;
3639         }
3640
3641         if (jprev != ARRAY_SIZE(*n)) {
3642             mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3643         }
3644     }
3645 }
3646
3647 /*
3648  * If positive, discarding RAM is disabled. If negative, discarding RAM is
3649  * required to work and cannot be disabled.
3650  */
3651 static int ram_block_discard_disabled;
3652
3653 int ram_block_discard_disable(bool state)
3654 {
3655     int old;
3656
3657     if (!state) {
3658         qatomic_dec(&ram_block_discard_disabled);
3659         return 0;
3660     }
3661
3662     do {
3663         old = qatomic_read(&ram_block_discard_disabled);
3664         if (old < 0) {
3665             return -EBUSY;
3666         }
3667     } while (qatomic_cmpxchg(&ram_block_discard_disabled,
3668                              old, old + 1) != old);
3669     return 0;
3670 }
3671
3672 int ram_block_discard_require(bool state)
3673 {
3674     int old;
3675
3676     if (!state) {
3677         qatomic_inc(&ram_block_discard_disabled);
3678         return 0;
3679     }
3680
3681     do {
3682         old = qatomic_read(&ram_block_discard_disabled);
3683         if (old > 0) {
3684             return -EBUSY;
3685         }
3686     } while (qatomic_cmpxchg(&ram_block_discard_disabled,
3687                              old, old - 1) != old);
3688     return 0;
3689 }
3690
3691 bool ram_block_discard_is_disabled(void)
3692 {
3693     return qatomic_read(&ram_block_discard_disabled) > 0;
3694 }
3695
3696 bool ram_block_discard_is_required(void)
3697 {
3698     return qatomic_read(&ram_block_discard_disabled) < 0;
3699 }
This page took 0.233206 seconds and 4 git commands to generate.