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