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