OSDN Git Service

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