suspend/resume: changed option name
[sdk/emulator/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 "config.h"
20 #ifdef _WIN32
21 #include <windows.h>
22 #else
23 #include <sys/types.h>
24 #include <sys/mman.h>
25 #endif
26
27 #include "qemu-common.h"
28 #include "cpu.h"
29 #include "tcg.h"
30 #include "hw/hw.h"
31 #include "hw/qdev.h"
32 #include "qemu/osdep.h"
33 #include "sysemu/kvm.h"
34 #include "sysemu/hax.h"
35 #include "sysemu/sysemu.h"
36 #include "hw/xen/xen.h"
37 #include "qemu/timer.h"
38 #include "qemu/config-file.h"
39 #include "exec/memory.h"
40 #include "sysemu/dma.h"
41 #include "exec/address-spaces.h"
42 #if defined(CONFIG_USER_ONLY)
43 #include <qemu.h>
44 #else /* !CONFIG_USER_ONLY */
45 #include "sysemu/xen-mapcache.h"
46 #include "trace.h"
47 #endif
48 #include "exec/cpu-all.h"
49
50 #include "exec/cputlb.h"
51 #include "translate-all.h"
52
53 #include "exec/memory-internal.h"
54
55 //#define DEBUG_SUBPAGE
56
57 #if !defined(CONFIG_USER_ONLY)
58 static int in_migration;
59
60 RAMList ram_list = { .blocks = QTAILQ_HEAD_INITIALIZER(ram_list.blocks) };
61
62 static MemoryRegion *system_memory;
63 static MemoryRegion *system_io;
64
65 AddressSpace address_space_io;
66 AddressSpace address_space_memory;
67
68 MemoryRegion io_mem_rom, io_mem_notdirty;
69 static MemoryRegion io_mem_unassigned;
70
71 #endif
72
73 CPUState *first_cpu;
74 /* current CPU in the current thread. It is only valid inside
75    cpu_exec() */
76 DEFINE_TLS(CPUState *, current_cpu);
77 /* 0 = Do not count executed instructions.
78    1 = Precise instruction counting.
79    2 = Adaptive rate instruction counting.  */
80 int use_icount;
81
82 #if !defined(CONFIG_USER_ONLY)
83
84 typedef struct PhysPageEntry PhysPageEntry;
85
86 struct PhysPageEntry {
87     uint16_t is_leaf : 1;
88      /* index into phys_sections (is_leaf) or phys_map_nodes (!is_leaf) */
89     uint16_t ptr : 15;
90 };
91
92 typedef PhysPageEntry Node[L2_SIZE];
93
94 struct AddressSpaceDispatch {
95     /* This is a multi-level map on the physical address space.
96      * The bottom level has pointers to MemoryRegionSections.
97      */
98     PhysPageEntry phys_map;
99     Node *nodes;
100     MemoryRegionSection *sections;
101     AddressSpace *as;
102 };
103
104 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
105 typedef struct subpage_t {
106     MemoryRegion iomem;
107     AddressSpace *as;
108     hwaddr base;
109     uint16_t sub_section[TARGET_PAGE_SIZE];
110 } subpage_t;
111
112 #define PHYS_SECTION_UNASSIGNED 0
113 #define PHYS_SECTION_NOTDIRTY 1
114 #define PHYS_SECTION_ROM 2
115 #define PHYS_SECTION_WATCH 3
116
117 typedef struct PhysPageMap {
118     unsigned sections_nb;
119     unsigned sections_nb_alloc;
120     unsigned nodes_nb;
121     unsigned nodes_nb_alloc;
122     Node *nodes;
123     MemoryRegionSection *sections;
124 } PhysPageMap;
125
126 static PhysPageMap *prev_map;
127 static PhysPageMap next_map;
128
129 #define PHYS_MAP_NODE_NIL (((uint16_t)~0) >> 1)
130
131 static void io_mem_init(void);
132 static void memory_map_init(void);
133 static void *qemu_safe_ram_ptr(ram_addr_t addr);
134
135 static MemoryRegion io_mem_watch;
136 #endif
137
138 #if !defined(CONFIG_USER_ONLY)
139
140 static void phys_map_node_reserve(unsigned nodes)
141 {
142     if (next_map.nodes_nb + nodes > next_map.nodes_nb_alloc) {
143         next_map.nodes_nb_alloc = MAX(next_map.nodes_nb_alloc * 2,
144                                             16);
145         next_map.nodes_nb_alloc = MAX(next_map.nodes_nb_alloc,
146                                       next_map.nodes_nb + nodes);
147         next_map.nodes = g_renew(Node, next_map.nodes,
148                                  next_map.nodes_nb_alloc);
149     }
150 }
151
152 static uint16_t phys_map_node_alloc(void)
153 {
154     unsigned i;
155     uint16_t ret;
156
157     ret = next_map.nodes_nb++;
158     assert(ret != PHYS_MAP_NODE_NIL);
159     assert(ret != next_map.nodes_nb_alloc);
160     for (i = 0; i < L2_SIZE; ++i) {
161         next_map.nodes[ret][i].is_leaf = 0;
162         next_map.nodes[ret][i].ptr = PHYS_MAP_NODE_NIL;
163     }
164     return ret;
165 }
166
167 static void phys_page_set_level(PhysPageEntry *lp, hwaddr *index,
168                                 hwaddr *nb, uint16_t leaf,
169                                 int level)
170 {
171     PhysPageEntry *p;
172     int i;
173     hwaddr step = (hwaddr)1 << (level * L2_BITS);
174
175     if (!lp->is_leaf && lp->ptr == PHYS_MAP_NODE_NIL) {
176         lp->ptr = phys_map_node_alloc();
177         p = next_map.nodes[lp->ptr];
178         if (level == 0) {
179             for (i = 0; i < L2_SIZE; i++) {
180                 p[i].is_leaf = 1;
181                 p[i].ptr = PHYS_SECTION_UNASSIGNED;
182             }
183         }
184     } else {
185         p = next_map.nodes[lp->ptr];
186     }
187     lp = &p[(*index >> (level * L2_BITS)) & (L2_SIZE - 1)];
188
189     while (*nb && lp < &p[L2_SIZE]) {
190         if ((*index & (step - 1)) == 0 && *nb >= step) {
191             lp->is_leaf = true;
192             lp->ptr = leaf;
193             *index += step;
194             *nb -= step;
195         } else {
196             phys_page_set_level(lp, index, nb, leaf, level - 1);
197         }
198         ++lp;
199     }
200 }
201
202 static void phys_page_set(AddressSpaceDispatch *d,
203                           hwaddr index, hwaddr nb,
204                           uint16_t leaf)
205 {
206     /* Wildly overreserve - it doesn't matter much. */
207     phys_map_node_reserve(3 * P_L2_LEVELS);
208
209     phys_page_set_level(&d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
210 }
211
212 static MemoryRegionSection *phys_page_find(PhysPageEntry lp, hwaddr index,
213                                            Node *nodes, MemoryRegionSection *sections)
214 {
215     PhysPageEntry *p;
216     int i;
217
218     for (i = P_L2_LEVELS - 1; i >= 0 && !lp.is_leaf; i--) {
219         if (lp.ptr == PHYS_MAP_NODE_NIL) {
220             return &sections[PHYS_SECTION_UNASSIGNED];
221         }
222         p = nodes[lp.ptr];
223         lp = p[(index >> (i * L2_BITS)) & (L2_SIZE - 1)];
224     }
225     return &sections[lp.ptr];
226 }
227
228 bool memory_region_is_unassigned(MemoryRegion *mr)
229 {
230     return mr != &io_mem_rom && mr != &io_mem_notdirty && !mr->rom_device
231         && mr != &io_mem_watch;
232 }
233
234 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
235                                                         hwaddr addr,
236                                                         bool resolve_subpage)
237 {
238     MemoryRegionSection *section;
239     subpage_t *subpage;
240
241     section = phys_page_find(d->phys_map, addr >> TARGET_PAGE_BITS,
242                              d->nodes, d->sections);
243     if (resolve_subpage && section->mr->subpage) {
244         subpage = container_of(section->mr, subpage_t, iomem);
245         section = &d->sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
246     }
247     return section;
248 }
249
250 static MemoryRegionSection *
251 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
252                                  hwaddr *plen, bool resolve_subpage)
253 {
254     MemoryRegionSection *section;
255     Int128 diff;
256
257     section = address_space_lookup_region(d, addr, resolve_subpage);
258     /* Compute offset within MemoryRegionSection */
259     addr -= section->offset_within_address_space;
260
261     /* Compute offset within MemoryRegion */
262     *xlat = addr + section->offset_within_region;
263
264     diff = int128_sub(section->mr->size, int128_make64(addr));
265     *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
266     return section;
267 }
268
269 MemoryRegion *address_space_translate(AddressSpace *as, hwaddr addr,
270                                       hwaddr *xlat, hwaddr *plen,
271                                       bool is_write)
272 {
273     IOMMUTLBEntry iotlb;
274     MemoryRegionSection *section;
275     MemoryRegion *mr;
276     hwaddr len = *plen;
277
278     for (;;) {
279         section = address_space_translate_internal(as->dispatch, addr, &addr, plen, true);
280         mr = section->mr;
281
282         if (!mr->iommu_ops) {
283             break;
284         }
285
286         iotlb = mr->iommu_ops->translate(mr, addr);
287         addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
288                 | (addr & iotlb.addr_mask));
289         len = MIN(len, (addr | iotlb.addr_mask) - addr + 1);
290         if (!(iotlb.perm & (1 << is_write))) {
291             mr = &io_mem_unassigned;
292             break;
293         }
294
295         as = iotlb.target_as;
296     }
297
298     *plen = len;
299     *xlat = addr;
300     return mr;
301 }
302
303 MemoryRegionSection *
304 address_space_translate_for_iotlb(AddressSpace *as, hwaddr addr, hwaddr *xlat,
305                                   hwaddr *plen)
306 {
307     MemoryRegionSection *section;
308     section = address_space_translate_internal(as->dispatch, addr, xlat, plen, false);
309
310     assert(!section->mr->iommu_ops);
311     return section;
312 }
313 #endif
314
315 void cpu_exec_init_all(void)
316 {
317 #if !defined(CONFIG_USER_ONLY)
318     qemu_mutex_init(&ram_list.mutex);
319     memory_map_init();
320     io_mem_init();
321 #endif
322 }
323
324 #if !defined(CONFIG_USER_ONLY)
325
326 static int cpu_common_post_load(void *opaque, int version_id)
327 {
328     CPUState *cpu = opaque;
329
330     /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
331        version_id is increased. */
332     cpu->interrupt_request &= ~0x01;
333     tlb_flush(cpu->env_ptr, 1);
334
335     return 0;
336 }
337
338 const VMStateDescription vmstate_cpu_common = {
339     .name = "cpu_common",
340     .version_id = 1,
341     .minimum_version_id = 1,
342     .minimum_version_id_old = 1,
343     .post_load = cpu_common_post_load,
344     .fields      = (VMStateField []) {
345         VMSTATE_UINT32(halted, CPUState),
346         VMSTATE_UINT32(interrupt_request, CPUState),
347         VMSTATE_END_OF_LIST()
348     }
349 };
350
351 #endif
352
353 CPUState *qemu_get_cpu(int index)
354 {
355     CPUState *cpu = first_cpu;
356
357     while (cpu) {
358         if (cpu->cpu_index == index) {
359             break;
360         }
361         cpu = cpu->next_cpu;
362     }
363
364     return cpu;
365 }
366
367 void qemu_for_each_cpu(void (*func)(CPUState *cpu, void *data), void *data)
368 {
369     CPUState *cpu;
370
371     cpu = first_cpu;
372     while (cpu) {
373         func(cpu, data);
374         cpu = cpu->next_cpu;
375     }
376 }
377
378 void cpu_exec_init(CPUArchState *env)
379 {
380     CPUState *cpu = ENV_GET_CPU(env);
381     CPUClass *cc = CPU_GET_CLASS(cpu);
382     CPUState **pcpu;
383     int cpu_index;
384
385 #if defined(CONFIG_USER_ONLY)
386     cpu_list_lock();
387 #endif
388     cpu->next_cpu = NULL;
389     pcpu = &first_cpu;
390     cpu_index = 0;
391     while (*pcpu != NULL) {
392         pcpu = &(*pcpu)->next_cpu;
393         cpu_index++;
394     }
395     cpu->cpu_index = cpu_index;
396     cpu->numa_node = 0;
397     QTAILQ_INIT(&env->breakpoints);
398     QTAILQ_INIT(&env->watchpoints);
399 #ifndef CONFIG_USER_ONLY
400     cpu->thread_id = qemu_get_thread_id();
401 #endif
402     *pcpu = cpu;
403 #if defined(CONFIG_USER_ONLY)
404     cpu_list_unlock();
405 #endif
406     if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {
407         vmstate_register(NULL, cpu_index, &vmstate_cpu_common, cpu);
408     }
409 #if defined(CPU_SAVE_VERSION) && !defined(CONFIG_USER_ONLY)
410     register_savevm(NULL, "cpu", cpu_index, CPU_SAVE_VERSION,
411                     cpu_save, cpu_load, env);
412     assert(cc->vmsd == NULL);
413     assert(qdev_get_vmsd(DEVICE(cpu)) == NULL);
414 #endif
415     if (cc->vmsd != NULL) {
416         vmstate_register(NULL, cpu_index, cc->vmsd, cpu);
417     }
418 }
419
420 #if defined(TARGET_HAS_ICE)
421 #if defined(CONFIG_USER_ONLY)
422 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
423 {
424     tb_invalidate_phys_page_range(pc, pc + 1, 0);
425 }
426 #else
427 static void breakpoint_invalidate(CPUState *cpu, target_ulong pc)
428 {
429     tb_invalidate_phys_addr(cpu_get_phys_page_debug(cpu, pc) |
430             (pc & ~TARGET_PAGE_MASK));
431 }
432 #endif
433 #endif /* TARGET_HAS_ICE */
434
435 #if defined(CONFIG_USER_ONLY)
436 void cpu_watchpoint_remove_all(CPUArchState *env, int mask)
437
438 {
439 }
440
441 int cpu_watchpoint_insert(CPUArchState *env, target_ulong addr, target_ulong len,
442                           int flags, CPUWatchpoint **watchpoint)
443 {
444     return -ENOSYS;
445 }
446 #else
447 /* Add a watchpoint.  */
448 int cpu_watchpoint_insert(CPUArchState *env, target_ulong addr, target_ulong len,
449                           int flags, CPUWatchpoint **watchpoint)
450 {
451     target_ulong len_mask = ~(len - 1);
452     CPUWatchpoint *wp;
453
454     /* sanity checks: allow power-of-2 lengths, deny unaligned watchpoints */
455     if ((len & (len - 1)) || (addr & ~len_mask) ||
456             len == 0 || len > TARGET_PAGE_SIZE) {
457         fprintf(stderr, "qemu: tried to set invalid watchpoint at "
458                 TARGET_FMT_lx ", len=" TARGET_FMT_lu "\n", addr, len);
459         return -EINVAL;
460     }
461     wp = g_malloc(sizeof(*wp));
462
463     wp->vaddr = addr;
464     wp->len_mask = len_mask;
465     wp->flags = flags;
466
467     /* keep all GDB-injected watchpoints in front */
468     if (flags & BP_GDB)
469         QTAILQ_INSERT_HEAD(&env->watchpoints, wp, entry);
470     else
471         QTAILQ_INSERT_TAIL(&env->watchpoints, wp, entry);
472
473     tlb_flush_page(env, addr);
474
475     if (watchpoint)
476         *watchpoint = wp;
477     return 0;
478 }
479
480 /* Remove a specific watchpoint.  */
481 int cpu_watchpoint_remove(CPUArchState *env, target_ulong addr, target_ulong len,
482                           int flags)
483 {
484     target_ulong len_mask = ~(len - 1);
485     CPUWatchpoint *wp;
486
487     QTAILQ_FOREACH(wp, &env->watchpoints, entry) {
488         if (addr == wp->vaddr && len_mask == wp->len_mask
489                 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
490             cpu_watchpoint_remove_by_ref(env, wp);
491             return 0;
492         }
493     }
494     return -ENOENT;
495 }
496
497 /* Remove a specific watchpoint by reference.  */
498 void cpu_watchpoint_remove_by_ref(CPUArchState *env, CPUWatchpoint *watchpoint)
499 {
500     QTAILQ_REMOVE(&env->watchpoints, watchpoint, entry);
501
502     tlb_flush_page(env, watchpoint->vaddr);
503
504     g_free(watchpoint);
505 }
506
507 /* Remove all matching watchpoints.  */
508 void cpu_watchpoint_remove_all(CPUArchState *env, int mask)
509 {
510     CPUWatchpoint *wp, *next;
511
512     QTAILQ_FOREACH_SAFE(wp, &env->watchpoints, entry, next) {
513         if (wp->flags & mask)
514             cpu_watchpoint_remove_by_ref(env, wp);
515     }
516 }
517 #endif
518
519 /* Add a breakpoint.  */
520 int cpu_breakpoint_insert(CPUArchState *env, target_ulong pc, int flags,
521                           CPUBreakpoint **breakpoint)
522 {
523 #if defined(TARGET_HAS_ICE)
524     CPUBreakpoint *bp;
525
526     bp = g_malloc(sizeof(*bp));
527
528     bp->pc = pc;
529     bp->flags = flags;
530
531     /* keep all GDB-injected breakpoints in front */
532     if (flags & BP_GDB) {
533         QTAILQ_INSERT_HEAD(&env->breakpoints, bp, entry);
534     } else {
535         QTAILQ_INSERT_TAIL(&env->breakpoints, bp, entry);
536     }
537
538     breakpoint_invalidate(ENV_GET_CPU(env), pc);
539
540     if (breakpoint) {
541         *breakpoint = bp;
542     }
543     return 0;
544 #else
545     return -ENOSYS;
546 #endif
547 }
548
549 /* Remove a specific breakpoint.  */
550 int cpu_breakpoint_remove(CPUArchState *env, target_ulong pc, int flags)
551 {
552 #if defined(TARGET_HAS_ICE)
553     CPUBreakpoint *bp;
554
555     QTAILQ_FOREACH(bp, &env->breakpoints, entry) {
556         if (bp->pc == pc && bp->flags == flags) {
557             cpu_breakpoint_remove_by_ref(env, bp);
558             return 0;
559         }
560     }
561     return -ENOENT;
562 #else
563     return -ENOSYS;
564 #endif
565 }
566
567 /* Remove a specific breakpoint by reference.  */
568 void cpu_breakpoint_remove_by_ref(CPUArchState *env, CPUBreakpoint *breakpoint)
569 {
570 #if defined(TARGET_HAS_ICE)
571     QTAILQ_REMOVE(&env->breakpoints, breakpoint, entry);
572
573     breakpoint_invalidate(ENV_GET_CPU(env), breakpoint->pc);
574
575     g_free(breakpoint);
576 #endif
577 }
578
579 /* Remove all matching breakpoints. */
580 void cpu_breakpoint_remove_all(CPUArchState *env, int mask)
581 {
582 #if defined(TARGET_HAS_ICE)
583     CPUBreakpoint *bp, *next;
584
585     QTAILQ_FOREACH_SAFE(bp, &env->breakpoints, entry, next) {
586         if (bp->flags & mask)
587             cpu_breakpoint_remove_by_ref(env, bp);
588     }
589 #endif
590 }
591
592 /* enable or disable single step mode. EXCP_DEBUG is returned by the
593    CPU loop after each instruction */
594 void cpu_single_step(CPUState *cpu, int enabled)
595 {
596 #if defined(TARGET_HAS_ICE)
597     if (cpu->singlestep_enabled != enabled) {
598         cpu->singlestep_enabled = enabled;
599         if (kvm_enabled()) {
600             kvm_update_guest_debug(cpu, 0);
601         } else {
602             /* must flush all the translated code to avoid inconsistencies */
603             /* XXX: only flush what is necessary */
604             CPUArchState *env = cpu->env_ptr;
605             tb_flush(env);
606         }
607     }
608 #endif
609 }
610
611 void cpu_abort(CPUArchState *env, const char *fmt, ...)
612 {
613     CPUState *cpu = ENV_GET_CPU(env);
614     va_list ap;
615     va_list ap2;
616
617     va_start(ap, fmt);
618     va_copy(ap2, ap);
619     fprintf(stderr, "qemu: fatal: ");
620     vfprintf(stderr, fmt, ap);
621     fprintf(stderr, "\n");
622     cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU | CPU_DUMP_CCOP);
623     if (qemu_log_enabled()) {
624         qemu_log("qemu: fatal: ");
625         qemu_log_vprintf(fmt, ap2);
626         qemu_log("\n");
627         log_cpu_state(cpu, CPU_DUMP_FPU | CPU_DUMP_CCOP);
628         qemu_log_flush();
629         qemu_log_close();
630     }
631     va_end(ap2);
632     va_end(ap);
633 #if defined(CONFIG_USER_ONLY)
634     {
635         struct sigaction act;
636         sigfillset(&act.sa_mask);
637         act.sa_handler = SIG_DFL;
638         sigaction(SIGABRT, &act, NULL);
639     }
640 #endif
641     abort();
642 }
643
644 CPUArchState *cpu_copy(CPUArchState *env)
645 {
646     CPUArchState *new_env = cpu_init(env->cpu_model_str);
647 #if defined(TARGET_HAS_ICE)
648     CPUBreakpoint *bp;
649     CPUWatchpoint *wp;
650 #endif
651
652     /* Reset non arch specific state */
653     cpu_reset(ENV_GET_CPU(new_env));
654
655     /* Copy arch specific state into the new CPU */
656     memcpy(new_env, env, sizeof(CPUArchState));
657
658     /* Clone all break/watchpoints.
659        Note: Once we support ptrace with hw-debug register access, make sure
660        BP_CPU break/watchpoints are handled correctly on clone. */
661     QTAILQ_INIT(&env->breakpoints);
662     QTAILQ_INIT(&env->watchpoints);
663 #if defined(TARGET_HAS_ICE)
664     QTAILQ_FOREACH(bp, &env->breakpoints, entry) {
665         cpu_breakpoint_insert(new_env, bp->pc, bp->flags, NULL);
666     }
667     QTAILQ_FOREACH(wp, &env->watchpoints, entry) {
668         cpu_watchpoint_insert(new_env, wp->vaddr, (~wp->len_mask) + 1,
669                               wp->flags, NULL);
670     }
671 #endif
672
673     return new_env;
674 }
675
676 #if !defined(CONFIG_USER_ONLY)
677 static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t end,
678                                       uintptr_t length)
679 {
680     uintptr_t start1;
681
682     /* we modify the TLB cache so that the dirty bit will be set again
683        when accessing the range */
684     start1 = (uintptr_t)qemu_safe_ram_ptr(start);
685     /* Check that we don't span multiple blocks - this breaks the
686        address comparisons below.  */
687     if ((uintptr_t)qemu_safe_ram_ptr(end - 1) - start1
688             != (end - 1) - start) {
689         abort();
690     }
691     cpu_tlb_reset_dirty_all(start1, length);
692
693 }
694
695 /* Note: start and end must be within the same ram block.  */
696 void cpu_physical_memory_reset_dirty(ram_addr_t start, ram_addr_t end,
697                                      int dirty_flags)
698 {
699     uintptr_t length;
700
701     start &= TARGET_PAGE_MASK;
702     end = TARGET_PAGE_ALIGN(end);
703
704     length = end - start;
705     if (length == 0)
706         return;
707     cpu_physical_memory_mask_dirty_range(start, length, dirty_flags);
708
709     if (tcg_enabled()) {
710         tlb_reset_dirty_range_all(start, end, length);
711     }
712 }
713
714 static int cpu_physical_memory_set_dirty_tracking(int enable)
715 {
716     int ret = 0;
717     in_migration = enable;
718     return ret;
719 }
720
721 hwaddr memory_region_section_get_iotlb(CPUArchState *env,
722                                        MemoryRegionSection *section,
723                                        target_ulong vaddr,
724                                        hwaddr paddr, hwaddr xlat,
725                                        int prot,
726                                        target_ulong *address)
727 {
728     hwaddr iotlb;
729     CPUWatchpoint *wp;
730
731     if (memory_region_is_ram(section->mr)) {
732         /* Normal RAM.  */
733         iotlb = (memory_region_get_ram_addr(section->mr) & TARGET_PAGE_MASK)
734             + xlat;
735         if (!section->readonly) {
736             iotlb |= PHYS_SECTION_NOTDIRTY;
737         } else {
738             iotlb |= PHYS_SECTION_ROM;
739         }
740     } else {
741         iotlb = section - address_space_memory.dispatch->sections;
742         iotlb += xlat;
743     }
744
745     /* Make accesses to pages with watchpoints go via the
746        watchpoint trap routines.  */
747     QTAILQ_FOREACH(wp, &env->watchpoints, entry) {
748         if (vaddr == (wp->vaddr & TARGET_PAGE_MASK)) {
749             /* Avoid trapping reads of pages with a write breakpoint. */
750             if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {
751                 iotlb = PHYS_SECTION_WATCH + paddr;
752                 *address |= TLB_MMIO;
753                 break;
754             }
755         }
756     }
757
758     return iotlb;
759 }
760 #endif /* defined(CONFIG_USER_ONLY) */
761
762 #if !defined(CONFIG_USER_ONLY)
763
764 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
765                              uint16_t section);
766 static subpage_t *subpage_init(AddressSpace *as, hwaddr base);
767
768 static uint16_t phys_section_add(MemoryRegionSection *section)
769 {
770     /* The physical section number is ORed with a page-aligned
771      * pointer to produce the iotlb entries.  Thus it should
772      * never overflow into the page-aligned value.
773      */
774     assert(next_map.sections_nb < TARGET_PAGE_SIZE);
775
776     if (next_map.sections_nb == next_map.sections_nb_alloc) {
777         next_map.sections_nb_alloc = MAX(next_map.sections_nb_alloc * 2,
778                                          16);
779         next_map.sections = g_renew(MemoryRegionSection, next_map.sections,
780                                     next_map.sections_nb_alloc);
781     }
782     next_map.sections[next_map.sections_nb] = *section;
783     memory_region_ref(section->mr);
784     return next_map.sections_nb++;
785 }
786
787 static void phys_section_destroy(MemoryRegion *mr)
788 {
789     memory_region_unref(mr);
790
791     if (mr->subpage) {
792         subpage_t *subpage = container_of(mr, subpage_t, iomem);
793         memory_region_destroy(&subpage->iomem);
794         g_free(subpage);
795     }
796 }
797
798 static void phys_sections_free(PhysPageMap *map)
799 {
800     while (map->sections_nb > 0) {
801         MemoryRegionSection *section = &map->sections[--map->sections_nb];
802         phys_section_destroy(section->mr);
803     }
804     g_free(map->sections);
805     g_free(map->nodes);
806     g_free(map);
807 }
808
809 static void register_subpage(AddressSpaceDispatch *d, MemoryRegionSection *section)
810 {
811     subpage_t *subpage;
812     hwaddr base = section->offset_within_address_space
813         & TARGET_PAGE_MASK;
814     MemoryRegionSection *existing = phys_page_find(d->phys_map, base >> TARGET_PAGE_BITS,
815                                                    next_map.nodes, next_map.sections);
816     MemoryRegionSection subsection = {
817         .offset_within_address_space = base,
818         .size = int128_make64(TARGET_PAGE_SIZE),
819     };
820     hwaddr start, end;
821
822     assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
823
824     if (!(existing->mr->subpage)) {
825         subpage = subpage_init(d->as, base);
826         subsection.mr = &subpage->iomem;
827         phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
828                       phys_section_add(&subsection));
829     } else {
830         subpage = container_of(existing->mr, subpage_t, iomem);
831     }
832     start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
833     end = start + int128_get64(section->size) - 1;
834     subpage_register(subpage, start, end, phys_section_add(section));
835 }
836
837
838 static void register_multipage(AddressSpaceDispatch *d,
839                                MemoryRegionSection *section)
840 {
841     hwaddr start_addr = section->offset_within_address_space;
842     uint16_t section_index = phys_section_add(section);
843     uint64_t num_pages = int128_get64(int128_rshift(section->size,
844                                                     TARGET_PAGE_BITS));
845
846     assert(num_pages);
847     phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
848 }
849
850 static void mem_add(MemoryListener *listener, MemoryRegionSection *section)
851 {
852     AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
853     AddressSpaceDispatch *d = as->next_dispatch;
854     MemoryRegionSection now = *section, remain = *section;
855     Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
856
857     if (now.offset_within_address_space & ~TARGET_PAGE_MASK) {
858         uint64_t left = TARGET_PAGE_ALIGN(now.offset_within_address_space)
859                        - now.offset_within_address_space;
860
861         now.size = int128_min(int128_make64(left), now.size);
862         register_subpage(d, &now);
863     } else {
864         now.size = int128_zero();
865     }
866     while (int128_ne(remain.size, now.size)) {
867         remain.size = int128_sub(remain.size, now.size);
868         remain.offset_within_address_space += int128_get64(now.size);
869         remain.offset_within_region += int128_get64(now.size);
870         now = remain;
871         if (int128_lt(remain.size, page_size)) {
872             register_subpage(d, &now);
873         } else if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
874             now.size = page_size;
875             register_subpage(d, &now);
876         } else {
877             now.size = int128_and(now.size, int128_neg(page_size));
878             register_multipage(d, &now);
879         }
880     }
881 }
882
883 void qemu_flush_coalesced_mmio_buffer(void)
884 {
885     if (kvm_enabled())
886         kvm_flush_coalesced_mmio_buffer();
887 }
888
889 void qemu_mutex_lock_ramlist(void)
890 {
891     qemu_mutex_lock(&ram_list.mutex);
892 }
893
894 void qemu_mutex_unlock_ramlist(void)
895 {
896     qemu_mutex_unlock(&ram_list.mutex);
897 }
898
899 #if defined(__linux__) && !defined(TARGET_S390X)
900
901 #include <sys/vfs.h>
902
903 #define HUGETLBFS_MAGIC       0x958458f6
904
905 static long gethugepagesize(const char *path)
906 {
907     struct statfs fs;
908     int ret;
909
910     do {
911         ret = statfs(path, &fs);
912     } while (ret != 0 && errno == EINTR);
913
914     if (ret != 0) {
915         perror(path);
916         return 0;
917     }
918
919     if (fs.f_type != HUGETLBFS_MAGIC)
920         fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
921
922     return fs.f_bsize;
923 }
924
925 static void *file_ram_alloc(RAMBlock *block,
926                             ram_addr_t memory,
927                             const char *path)
928 {
929     char *filename;
930     char *sanitized_name;
931     char *c;
932     void *area;
933     int fd;
934 #ifdef MAP_POPULATE
935     int flags;
936 #endif
937     unsigned long hpagesize;
938
939     hpagesize = gethugepagesize(path);
940     if (!hpagesize) {
941         return NULL;
942     }
943
944     if (memory < hpagesize) {
945         return NULL;
946     }
947
948     if (kvm_enabled() && !kvm_has_sync_mmu()) {
949         fprintf(stderr, "host lacks kvm mmu notifiers, -mem-path unsupported\n");
950         return NULL;
951     }
952
953     /* Make name safe to use with mkstemp by replacing '/' with '_'. */
954     sanitized_name = g_strdup(block->mr->name);
955     for (c = sanitized_name; *c != '\0'; c++) {
956         if (*c == '/')
957             *c = '_';
958     }
959
960     filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
961                                sanitized_name);
962     g_free(sanitized_name);
963
964     fd = mkstemp(filename);
965     if (fd < 0) {
966         perror("unable to create backing store for hugepages");
967         g_free(filename);
968         return NULL;
969     }
970     unlink(filename);
971     g_free(filename);
972
973     memory = (memory+hpagesize-1) & ~(hpagesize-1);
974
975     /*
976      * ftruncate is not supported by hugetlbfs in older
977      * hosts, so don't bother bailing out on errors.
978      * If anything goes wrong with it under other filesystems,
979      * mmap will fail.
980      */
981     if (ftruncate(fd, memory))
982         perror("ftruncate");
983
984 #ifdef MAP_POPULATE
985     /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
986      * MAP_PRIVATE is requested.  For mem_prealloc we mmap as MAP_SHARED
987      * to sidestep this quirk.
988      */
989     flags = mem_prealloc ? MAP_POPULATE | MAP_SHARED : MAP_PRIVATE;
990     area = mmap(0, memory, PROT_READ | PROT_WRITE, flags, fd, 0);
991 #else
992     area = mmap(0, memory, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
993 #endif
994     if (area == MAP_FAILED) {
995         perror("file_ram_alloc: can't mmap RAM pages");
996         close(fd);
997         return (NULL);
998     }
999     block->fd = fd;
1000     return area;
1001 }
1002 #endif
1003
1004 static ram_addr_t find_ram_offset(ram_addr_t size)
1005 {
1006     RAMBlock *block, *next_block;
1007     ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1008
1009     assert(size != 0); /* it would hand out same offset multiple times */
1010
1011     if (QTAILQ_EMPTY(&ram_list.blocks))
1012         return 0;
1013
1014     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
1015         ram_addr_t end, next = RAM_ADDR_MAX;
1016
1017         end = block->offset + block->length;
1018
1019         QTAILQ_FOREACH(next_block, &ram_list.blocks, next) {
1020             if (next_block->offset >= end) {
1021                 next = MIN(next, next_block->offset);
1022             }
1023         }
1024         if (next - end >= size && next - end < mingap) {
1025             offset = end;
1026             mingap = next - end;
1027         }
1028     }
1029
1030     if (offset == RAM_ADDR_MAX) {
1031         fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1032                 (uint64_t)size);
1033         abort();
1034     }
1035
1036     return offset;
1037 }
1038
1039 ram_addr_t last_ram_offset(void)
1040 {
1041     RAMBlock *block;
1042     ram_addr_t last = 0;
1043
1044     QTAILQ_FOREACH(block, &ram_list.blocks, next)
1045         last = MAX(last, block->offset + block->length);
1046
1047     return last;
1048 }
1049
1050 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1051 {
1052     int ret;
1053
1054     /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1055     if (!qemu_opt_get_bool(qemu_get_machine_opts(),
1056                            "dump-guest-core", true)) {
1057         ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1058         if (ret) {
1059             perror("qemu_madvise");
1060             fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1061                             "but dump_guest_core=off specified\n");
1062         }
1063     }
1064 }
1065
1066 void qemu_ram_set_idstr(ram_addr_t addr, const char *name, DeviceState *dev)
1067 {
1068     RAMBlock *new_block, *block;
1069
1070     new_block = NULL;
1071     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
1072         if (block->offset == addr) {
1073             new_block = block;
1074             break;
1075         }
1076     }
1077     assert(new_block);
1078     assert(!new_block->idstr[0]);
1079
1080     if (dev) {
1081         char *id = qdev_get_dev_path(dev);
1082         if (id) {
1083             snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1084             g_free(id);
1085         }
1086     }
1087     pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1088
1089     /* This assumes the iothread lock is taken here too.  */
1090     qemu_mutex_lock_ramlist();
1091     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
1092         if (block != new_block && !strcmp(block->idstr, new_block->idstr)) {
1093             fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1094                     new_block->idstr);
1095             abort();
1096         }
1097     }
1098     qemu_mutex_unlock_ramlist();
1099 }
1100
1101 static int memory_try_enable_merging(void *addr, size_t len)
1102 {
1103     if (!qemu_opt_get_bool(qemu_get_machine_opts(), "mem-merge", true)) {
1104         /* disabled by the user */
1105         return 0;
1106     }
1107
1108     return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1109 }
1110
1111 ram_addr_t qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
1112                                    MemoryRegion *mr)
1113 {
1114     RAMBlock *block, *new_block;
1115
1116     size = TARGET_PAGE_ALIGN(size);
1117     new_block = g_malloc0(sizeof(*new_block));
1118
1119     /* This assumes the iothread lock is taken here too.  */
1120     qemu_mutex_lock_ramlist();
1121     new_block->mr = mr;
1122     new_block->offset = find_ram_offset(size);
1123     if (host) {
1124         new_block->host = host;
1125         new_block->flags |= RAM_PREALLOC_MASK;
1126     } else {
1127         if (mem_path) {
1128 #if defined (__linux__) && !defined(TARGET_S390X)
1129             new_block->host = file_ram_alloc(new_block, size, mem_path);
1130             if (!new_block->host) {
1131                 new_block->host = qemu_anon_ram_alloc(size);
1132                 memory_try_enable_merging(new_block->host, size);
1133             }
1134 #else
1135             fprintf(stderr, "-mem-path option unsupported\n");
1136             exit(1);
1137 #endif
1138         } else {
1139             if (xen_enabled()) {
1140                 xen_ram_alloc(new_block->offset, size, mr);
1141             } else if (kvm_enabled()) {
1142                 /* some s390/kvm configurations have special constraints */
1143                 new_block->host = kvm_ram_alloc(size);
1144             } else {
1145                 new_block->host = qemu_anon_ram_alloc(size);
1146 #ifdef CONFIG_HAX
1147                 /*
1148                  * In Hax, the qemu allocate the virtual address, and HAX kernel
1149                  * populate the memory with physical memory. Currently we have no
1150                  * paging, so user should make sure enough free memory in advance
1151                  */
1152                 if (hax_enabled()) {
1153                     int ret;
1154                     ret = hax_populate_ram((uint64_t)new_block->host, size);
1155                     if (ret < 0) {
1156                         fprintf(stderr, "Hax failed to populate ram\n");
1157                         exit(-1);
1158                     }
1159                 }
1160 #endif
1161             }
1162             memory_try_enable_merging(new_block->host, size);
1163         }
1164     }
1165     new_block->length = size;
1166
1167     /* Keep the list sorted from biggest to smallest block.  */
1168     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
1169         if (block->length < new_block->length) {
1170             break;
1171         }
1172     }
1173     if (block) {
1174         QTAILQ_INSERT_BEFORE(block, new_block, next);
1175     } else {
1176         QTAILQ_INSERT_TAIL(&ram_list.blocks, new_block, next);
1177     }
1178     ram_list.mru_block = NULL;
1179
1180     ram_list.version++;
1181     qemu_mutex_unlock_ramlist();
1182
1183     ram_list.phys_dirty = g_realloc(ram_list.phys_dirty,
1184                                        last_ram_offset() >> TARGET_PAGE_BITS);
1185     memset(ram_list.phys_dirty + (new_block->offset >> TARGET_PAGE_BITS),
1186            0, size >> TARGET_PAGE_BITS);
1187     cpu_physical_memory_set_dirty_range(new_block->offset, size, 0xff);
1188
1189     qemu_ram_setup_dump(new_block->host, size);
1190     qemu_madvise(new_block->host, size, QEMU_MADV_HUGEPAGE);
1191     qemu_madvise(new_block->host, size, QEMU_MADV_DONTFORK);
1192
1193     if (kvm_enabled())
1194         kvm_setup_guest_memory(new_block->host, size);
1195
1196     return new_block->offset;
1197 }
1198
1199 ram_addr_t qemu_ram_alloc(ram_addr_t size, MemoryRegion *mr)
1200 {
1201     return qemu_ram_alloc_from_ptr(size, NULL, mr);
1202 }
1203
1204 void qemu_ram_free_from_ptr(ram_addr_t addr)
1205 {
1206     RAMBlock *block;
1207
1208     /* This assumes the iothread lock is taken here too.  */
1209     qemu_mutex_lock_ramlist();
1210     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
1211         if (addr == block->offset) {
1212             QTAILQ_REMOVE(&ram_list.blocks, block, next);
1213             ram_list.mru_block = NULL;
1214             ram_list.version++;
1215             g_free(block);
1216             break;
1217         }
1218     }
1219     qemu_mutex_unlock_ramlist();
1220 }
1221
1222 void qemu_ram_free(ram_addr_t addr)
1223 {
1224     RAMBlock *block;
1225
1226     /* This assumes the iothread lock is taken here too.  */
1227     qemu_mutex_lock_ramlist();
1228     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
1229         if (addr == block->offset) {
1230             QTAILQ_REMOVE(&ram_list.blocks, block, next);
1231             ram_list.mru_block = NULL;
1232             ram_list.version++;
1233             if (block->flags & RAM_PREALLOC_MASK) {
1234                 ;
1235             } else if (mem_path) {
1236 #if defined (__linux__) && !defined(TARGET_S390X)
1237                 if (block->fd) {
1238                     munmap(block->host, block->length);
1239                     close(block->fd);
1240                 } else {
1241                     qemu_anon_ram_free(block->host, block->length);
1242                 }
1243 #else
1244                 abort();
1245 #endif
1246             } else {
1247                 if (xen_enabled()) {
1248                     xen_invalidate_map_cache_entry(block->host);
1249                 } else {
1250                     qemu_anon_ram_free(block->host, block->length);
1251                 }
1252             }
1253             g_free(block);
1254             break;
1255         }
1256     }
1257     qemu_mutex_unlock_ramlist();
1258
1259 }
1260
1261 #ifndef _WIN32
1262 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
1263 {
1264     RAMBlock *block;
1265     ram_addr_t offset;
1266     int flags;
1267     void *area, *vaddr;
1268
1269     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
1270         offset = addr - block->offset;
1271         if (offset < block->length) {
1272             vaddr = block->host + offset;
1273             if (block->flags & RAM_PREALLOC_MASK) {
1274                 ;
1275             } else {
1276                 flags = MAP_FIXED;
1277                 munmap(vaddr, length);
1278                 if (mem_path) {
1279 #if defined(__linux__) && !defined(TARGET_S390X)
1280                     if (block->fd) {
1281 #ifdef MAP_POPULATE
1282                         flags |= mem_prealloc ? MAP_POPULATE | MAP_SHARED :
1283                             MAP_PRIVATE;
1284 #else
1285                         flags |= MAP_PRIVATE;
1286 #endif
1287                         area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
1288                                     flags, block->fd, offset);
1289                     } else {
1290                         flags |= MAP_PRIVATE | MAP_ANONYMOUS;
1291                         area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
1292                                     flags, -1, 0);
1293                     }
1294 #else
1295                     abort();
1296 #endif
1297                 } else {
1298 #if defined(TARGET_S390X) && defined(CONFIG_KVM)
1299                     flags |= MAP_SHARED | MAP_ANONYMOUS;
1300                     area = mmap(vaddr, length, PROT_EXEC|PROT_READ|PROT_WRITE,
1301                                 flags, -1, 0);
1302 #else
1303                     flags |= MAP_PRIVATE | MAP_ANONYMOUS;
1304                     area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
1305                                 flags, -1, 0);
1306 #endif
1307                 }
1308                 if (area != vaddr) {
1309                     fprintf(stderr, "Could not remap addr: "
1310                             RAM_ADDR_FMT "@" RAM_ADDR_FMT "\n",
1311                             length, addr);
1312                     exit(1);
1313                 }
1314                 memory_try_enable_merging(vaddr, length);
1315                 qemu_ram_setup_dump(vaddr, length);
1316             }
1317             return;
1318         }
1319     }
1320 }
1321 #endif /* !_WIN32 */
1322
1323 static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
1324 {
1325     RAMBlock *block;
1326
1327     /* The list is protected by the iothread lock here.  */
1328     block = ram_list.mru_block;
1329     if (block && addr - block->offset < block->length) {
1330         goto found;
1331     }
1332     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
1333         if (addr - block->offset < block->length) {
1334             goto found;
1335         }
1336     }
1337
1338     fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1339     abort();
1340
1341 found:
1342     ram_list.mru_block = block;
1343     return block;
1344 }
1345
1346 /* Return a host pointer to ram allocated with qemu_ram_alloc.
1347    With the exception of the softmmu code in this file, this should
1348    only be used for local memory (e.g. video ram) that the device owns,
1349    and knows it isn't going to access beyond the end of the block.
1350
1351    It should not be used for general purpose DMA.
1352    Use cpu_physical_memory_map/cpu_physical_memory_rw instead.
1353  */
1354 void *qemu_get_ram_ptr(ram_addr_t addr)
1355 {
1356     RAMBlock *block = qemu_get_ram_block(addr);
1357
1358     if (xen_enabled()) {
1359         /* We need to check if the requested address is in the RAM
1360          * because we don't want to map the entire memory in QEMU.
1361          * In that case just map until the end of the page.
1362          */
1363         if (block->offset == 0) {
1364             return xen_map_cache(addr, 0, 0);
1365         } else if (block->host == NULL) {
1366             block->host =
1367                 xen_map_cache(block->offset, block->length, 1);
1368         }
1369     }
1370     return block->host + (addr - block->offset);
1371 }
1372
1373 /* Return a host pointer to ram allocated with qemu_ram_alloc.  Same as
1374  * qemu_get_ram_ptr but do not touch ram_list.mru_block.
1375  *
1376  * ??? Is this still necessary?
1377  */
1378 static void *qemu_safe_ram_ptr(ram_addr_t addr)
1379 {
1380     RAMBlock *block;
1381
1382     /* The list is protected by the iothread lock here.  */
1383     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
1384         if (addr - block->offset < block->length) {
1385             if (xen_enabled()) {
1386                 /* We need to check if the requested address is in the RAM
1387                  * because we don't want to map the entire memory in QEMU.
1388                  * In that case just map until the end of the page.
1389                  */
1390                 if (block->offset == 0) {
1391                     return xen_map_cache(addr, 0, 0);
1392                 } else if (block->host == NULL) {
1393                     block->host =
1394                         xen_map_cache(block->offset, block->length, 1);
1395                 }
1396             }
1397             return block->host + (addr - block->offset);
1398         }
1399     }
1400
1401     fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1402     abort();
1403
1404     return NULL;
1405 }
1406
1407 /* Return a host pointer to guest's ram. Similar to qemu_get_ram_ptr
1408  * but takes a size argument */
1409 static void *qemu_ram_ptr_length(ram_addr_t addr, hwaddr *size)
1410 {
1411     if (*size == 0) {
1412         return NULL;
1413     }
1414     if (xen_enabled()) {
1415         return xen_map_cache(addr, *size, 1);
1416     } else {
1417         RAMBlock *block;
1418
1419         QTAILQ_FOREACH(block, &ram_list.blocks, next) {
1420             if (addr - block->offset < block->length) {
1421                 if (addr - block->offset + *size > block->length)
1422                     *size = block->length - addr + block->offset;
1423                 return block->host + (addr - block->offset);
1424             }
1425         }
1426
1427         fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
1428         abort();
1429     }
1430 }
1431
1432 /* Some of the softmmu routines need to translate from a host pointer
1433    (typically a TLB entry) back to a ram offset.  */
1434 MemoryRegion *qemu_ram_addr_from_host(void *ptr, ram_addr_t *ram_addr)
1435 {
1436     RAMBlock *block;
1437     uint8_t *host = ptr;
1438
1439     if (xen_enabled()) {
1440         *ram_addr = xen_ram_addr_from_mapcache(ptr);
1441         return qemu_get_ram_block(*ram_addr)->mr;
1442     }
1443
1444     block = ram_list.mru_block;
1445     if (block && block->host && host - block->host < block->length) {
1446         goto found;
1447     }
1448
1449     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
1450         /* This case append when the block is not mapped. */
1451         if (block->host == NULL) {
1452             continue;
1453         }
1454         if (host - block->host < block->length) {
1455             goto found;
1456         }
1457     }
1458
1459     return NULL;
1460
1461 found:
1462     *ram_addr = block->offset + (host - block->host);
1463     return block->mr;
1464 }
1465
1466 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
1467                                uint64_t val, unsigned size)
1468 {
1469     int dirty_flags;
1470     dirty_flags = cpu_physical_memory_get_dirty_flags(ram_addr);
1471     if (!(dirty_flags & CODE_DIRTY_FLAG)) {
1472         tb_invalidate_phys_page_fast(ram_addr, size);
1473         dirty_flags = cpu_physical_memory_get_dirty_flags(ram_addr);
1474     }
1475     switch (size) {
1476     case 1:
1477         stb_p(qemu_get_ram_ptr(ram_addr), val);
1478         break;
1479     case 2:
1480         stw_p(qemu_get_ram_ptr(ram_addr), val);
1481         break;
1482     case 4:
1483         stl_p(qemu_get_ram_ptr(ram_addr), val);
1484         break;
1485     default:
1486         abort();
1487     }
1488     dirty_flags |= (0xff & ~CODE_DIRTY_FLAG);
1489     cpu_physical_memory_set_dirty_flags(ram_addr, dirty_flags);
1490     /* we remove the notdirty callback only if the code has been
1491        flushed */
1492     if (dirty_flags == 0xff) {
1493         CPUArchState *env = current_cpu->env_ptr;
1494         tlb_set_dirty(env, env->mem_io_vaddr);
1495     }
1496 }
1497
1498 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
1499                                  unsigned size, bool is_write)
1500 {
1501     return is_write;
1502 }
1503
1504 static const MemoryRegionOps notdirty_mem_ops = {
1505     .write = notdirty_mem_write,
1506     .valid.accepts = notdirty_mem_accepts,
1507     .endianness = DEVICE_NATIVE_ENDIAN,
1508 };
1509
1510 /* Generate a debug exception if a watchpoint has been hit.  */
1511 static void check_watchpoint(int offset, int len_mask, int flags)
1512 {
1513     CPUArchState *env = current_cpu->env_ptr;
1514     target_ulong pc, cs_base;
1515     target_ulong vaddr;
1516     CPUWatchpoint *wp;
1517     int cpu_flags;
1518
1519     if (env->watchpoint_hit) {
1520         /* We re-entered the check after replacing the TB. Now raise
1521          * the debug interrupt so that is will trigger after the
1522          * current instruction. */
1523         cpu_interrupt(ENV_GET_CPU(env), CPU_INTERRUPT_DEBUG);
1524         return;
1525     }
1526     vaddr = (env->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
1527     QTAILQ_FOREACH(wp, &env->watchpoints, entry) {
1528         if ((vaddr == (wp->vaddr & len_mask) ||
1529              (vaddr & wp->len_mask) == wp->vaddr) && (wp->flags & flags)) {
1530             wp->flags |= BP_WATCHPOINT_HIT;
1531             if (!env->watchpoint_hit) {
1532                 env->watchpoint_hit = wp;
1533                 tb_check_watchpoint(env);
1534                 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
1535                     env->exception_index = EXCP_DEBUG;
1536                     cpu_loop_exit(env);
1537                 } else {
1538                     cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags);
1539                     tb_gen_code(env, pc, cs_base, cpu_flags, 1);
1540                     cpu_resume_from_signal(env, NULL);
1541                 }
1542             }
1543         } else {
1544             wp->flags &= ~BP_WATCHPOINT_HIT;
1545         }
1546     }
1547 }
1548
1549 /* Watchpoint access routines.  Watchpoints are inserted using TLB tricks,
1550    so these check for a hit then pass through to the normal out-of-line
1551    phys routines.  */
1552 static uint64_t watch_mem_read(void *opaque, hwaddr addr,
1553                                unsigned size)
1554 {
1555     check_watchpoint(addr & ~TARGET_PAGE_MASK, ~(size - 1), BP_MEM_READ);
1556     switch (size) {
1557     case 1: return ldub_phys(addr);
1558     case 2: return lduw_phys(addr);
1559     case 4: return ldl_phys(addr);
1560     default: abort();
1561     }
1562 }
1563
1564 static void watch_mem_write(void *opaque, hwaddr addr,
1565                             uint64_t val, unsigned size)
1566 {
1567     check_watchpoint(addr & ~TARGET_PAGE_MASK, ~(size - 1), BP_MEM_WRITE);
1568     switch (size) {
1569     case 1:
1570         stb_phys(addr, val);
1571         break;
1572     case 2:
1573         stw_phys(addr, val);
1574         break;
1575     case 4:
1576         stl_phys(addr, val);
1577         break;
1578     default: abort();
1579     }
1580 }
1581
1582 static const MemoryRegionOps watch_mem_ops = {
1583     .read = watch_mem_read,
1584     .write = watch_mem_write,
1585     .endianness = DEVICE_NATIVE_ENDIAN,
1586 };
1587
1588 static uint64_t subpage_read(void *opaque, hwaddr addr,
1589                              unsigned len)
1590 {
1591     subpage_t *subpage = opaque;
1592     uint8_t buf[4];
1593
1594 #if defined(DEBUG_SUBPAGE)
1595     printf("%s: subpage %p len %d addr " TARGET_FMT_plx "\n", __func__,
1596            subpage, len, addr);
1597 #endif
1598     address_space_read(subpage->as, addr + subpage->base, buf, len);
1599     switch (len) {
1600     case 1:
1601         return ldub_p(buf);
1602     case 2:
1603         return lduw_p(buf);
1604     case 4:
1605         return ldl_p(buf);
1606     default:
1607         abort();
1608     }
1609 }
1610
1611 static void subpage_write(void *opaque, hwaddr addr,
1612                           uint64_t value, unsigned len)
1613 {
1614     subpage_t *subpage = opaque;
1615     uint8_t buf[4];
1616
1617 #if defined(DEBUG_SUBPAGE)
1618     printf("%s: subpage %p len %d addr " TARGET_FMT_plx
1619            " value %"PRIx64"\n",
1620            __func__, subpage, len, addr, value);
1621 #endif
1622     switch (len) {
1623     case 1:
1624         stb_p(buf, value);
1625         break;
1626     case 2:
1627         stw_p(buf, value);
1628         break;
1629     case 4:
1630         stl_p(buf, value);
1631         break;
1632     default:
1633         abort();
1634     }
1635     address_space_write(subpage->as, addr + subpage->base, buf, len);
1636 }
1637
1638 static bool subpage_accepts(void *opaque, hwaddr addr,
1639                             unsigned size, bool is_write)
1640 {
1641     subpage_t *subpage = opaque;
1642 #if defined(DEBUG_SUBPAGE)
1643     printf("%s: subpage %p %c len %d addr " TARGET_FMT_plx "\n",
1644            __func__, subpage, is_write ? 'w' : 'r', len, addr);
1645 #endif
1646
1647     return address_space_access_valid(subpage->as, addr + subpage->base,
1648                                       size, is_write);
1649 }
1650
1651 static const MemoryRegionOps subpage_ops = {
1652     .read = subpage_read,
1653     .write = subpage_write,
1654     .valid.accepts = subpage_accepts,
1655     .endianness = DEVICE_NATIVE_ENDIAN,
1656 };
1657
1658 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
1659                              uint16_t section)
1660 {
1661     int idx, eidx;
1662
1663     if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
1664         return -1;
1665     idx = SUBPAGE_IDX(start);
1666     eidx = SUBPAGE_IDX(end);
1667 #if defined(DEBUG_SUBPAGE)
1668     printf("%s: %p start %08x end %08x idx %08x eidx %08x mem %ld\n", __func__,
1669            mmio, start, end, idx, eidx, memory);
1670 #endif
1671     for (; idx <= eidx; idx++) {
1672         mmio->sub_section[idx] = section;
1673     }
1674
1675     return 0;
1676 }
1677
1678 static subpage_t *subpage_init(AddressSpace *as, hwaddr base)
1679 {
1680     subpage_t *mmio;
1681
1682     mmio = g_malloc0(sizeof(subpage_t));
1683
1684     mmio->as = as;
1685     mmio->base = base;
1686     memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
1687                           "subpage", TARGET_PAGE_SIZE);
1688     mmio->iomem.subpage = true;
1689 #if defined(DEBUG_SUBPAGE)
1690     printf("%s: %p base " TARGET_FMT_plx " len %08x %d\n", __func__,
1691            mmio, base, TARGET_PAGE_SIZE, subpage_memory);
1692 #endif
1693     subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
1694
1695     return mmio;
1696 }
1697
1698 static uint16_t dummy_section(MemoryRegion *mr)
1699 {
1700     MemoryRegionSection section = {
1701         .mr = mr,
1702         .offset_within_address_space = 0,
1703         .offset_within_region = 0,
1704         .size = int128_2_64(),
1705     };
1706
1707     return phys_section_add(&section);
1708 }
1709
1710 MemoryRegion *iotlb_to_region(hwaddr index)
1711 {
1712     return address_space_memory.dispatch->sections[index & ~TARGET_PAGE_MASK].mr;
1713 }
1714
1715 static void io_mem_init(void)
1716 {
1717     memory_region_init_io(&io_mem_rom, NULL, &unassigned_mem_ops, NULL, "rom", UINT64_MAX);
1718     memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
1719                           "unassigned", UINT64_MAX);
1720     memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
1721                           "notdirty", UINT64_MAX);
1722     memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
1723                           "watch", UINT64_MAX);
1724 }
1725
1726 static void mem_begin(MemoryListener *listener)
1727 {
1728     AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
1729     AddressSpaceDispatch *d = g_new(AddressSpaceDispatch, 1);
1730
1731     d->phys_map  = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .is_leaf = 0 };
1732     d->as = as;
1733     as->next_dispatch = d;
1734 }
1735
1736 static void mem_commit(MemoryListener *listener)
1737 {
1738     AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);
1739     AddressSpaceDispatch *cur = as->dispatch;
1740     AddressSpaceDispatch *next = as->next_dispatch;
1741
1742     next->nodes = next_map.nodes;
1743     next->sections = next_map.sections;
1744
1745     as->dispatch = next;
1746     g_free(cur);
1747 }
1748
1749 static void core_begin(MemoryListener *listener)
1750 {
1751     uint16_t n;
1752
1753     prev_map = g_new(PhysPageMap, 1);
1754     *prev_map = next_map;
1755
1756     memset(&next_map, 0, sizeof(next_map));
1757     n = dummy_section(&io_mem_unassigned);
1758     assert(n == PHYS_SECTION_UNASSIGNED);
1759     n = dummy_section(&io_mem_notdirty);
1760     assert(n == PHYS_SECTION_NOTDIRTY);
1761     n = dummy_section(&io_mem_rom);
1762     assert(n == PHYS_SECTION_ROM);
1763     n = dummy_section(&io_mem_watch);
1764     assert(n == PHYS_SECTION_WATCH);
1765 }
1766
1767 /* This listener's commit run after the other AddressSpaceDispatch listeners'.
1768  * All AddressSpaceDispatch instances have switched to the next map.
1769  */
1770 static void core_commit(MemoryListener *listener)
1771 {
1772     phys_sections_free(prev_map);
1773 }
1774
1775 static void tcg_commit(MemoryListener *listener)
1776 {
1777     CPUState *cpu;
1778
1779     /* since each CPU stores ram addresses in its TLB cache, we must
1780        reset the modified entries */
1781     /* XXX: slow ! */
1782     for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
1783         CPUArchState *env = cpu->env_ptr;
1784
1785         tlb_flush(env, 1);
1786     }
1787 }
1788
1789 static void core_log_global_start(MemoryListener *listener)
1790 {
1791     cpu_physical_memory_set_dirty_tracking(1);
1792 }
1793
1794 static void core_log_global_stop(MemoryListener *listener)
1795 {
1796     cpu_physical_memory_set_dirty_tracking(0);
1797 }
1798
1799 static MemoryListener core_memory_listener = {
1800     .begin = core_begin,
1801     .commit = core_commit,
1802     .log_global_start = core_log_global_start,
1803     .log_global_stop = core_log_global_stop,
1804     .priority = 1,
1805 };
1806
1807 static MemoryListener tcg_memory_listener = {
1808     .commit = tcg_commit,
1809 };
1810
1811 void address_space_init_dispatch(AddressSpace *as)
1812 {
1813     as->dispatch = NULL;
1814     as->dispatch_listener = (MemoryListener) {
1815         .begin = mem_begin,
1816         .commit = mem_commit,
1817         .region_add = mem_add,
1818         .region_nop = mem_add,
1819         .priority = 0,
1820     };
1821     memory_listener_register(&as->dispatch_listener, as);
1822 }
1823
1824 void address_space_destroy_dispatch(AddressSpace *as)
1825 {
1826     AddressSpaceDispatch *d = as->dispatch;
1827
1828     memory_listener_unregister(&as->dispatch_listener);
1829     g_free(d);
1830     as->dispatch = NULL;
1831 }
1832
1833 static void memory_map_init(void)
1834 {
1835     system_memory = g_malloc(sizeof(*system_memory));
1836     memory_region_init(system_memory, NULL, "system", INT64_MAX);
1837     address_space_init(&address_space_memory, system_memory, "memory");
1838
1839     system_io = g_malloc(sizeof(*system_io));
1840     memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
1841                           65536);
1842     address_space_init(&address_space_io, system_io, "I/O");
1843
1844     memory_listener_register(&core_memory_listener, &address_space_memory);
1845     memory_listener_register(&tcg_memory_listener, &address_space_memory);
1846 }
1847
1848 MemoryRegion *get_system_memory(void)
1849 {
1850     return system_memory;
1851 }
1852
1853 MemoryRegion *get_system_io(void)
1854 {
1855     return system_io;
1856 }
1857
1858 #endif /* !defined(CONFIG_USER_ONLY) */
1859
1860 /* physical memory access (slow version, mainly for debug) */
1861 #if defined(CONFIG_USER_ONLY)
1862 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
1863                         uint8_t *buf, int len, int is_write)
1864 {
1865     int l, flags;
1866     target_ulong page;
1867     void * p;
1868
1869     while (len > 0) {
1870         page = addr & TARGET_PAGE_MASK;
1871         l = (page + TARGET_PAGE_SIZE) - addr;
1872         if (l > len)
1873             l = len;
1874         flags = page_get_flags(page);
1875         if (!(flags & PAGE_VALID))
1876             return -1;
1877         if (is_write) {
1878             if (!(flags & PAGE_WRITE))
1879                 return -1;
1880             /* XXX: this code should not depend on lock_user */
1881             if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
1882                 return -1;
1883             memcpy(p, buf, l);
1884             unlock_user(p, addr, l);
1885         } else {
1886             if (!(flags & PAGE_READ))
1887                 return -1;
1888             /* XXX: this code should not depend on lock_user */
1889             if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
1890                 return -1;
1891             memcpy(buf, p, l);
1892             unlock_user(p, addr, 0);
1893         }
1894         len -= l;
1895         buf += l;
1896         addr += l;
1897     }
1898     return 0;
1899 }
1900
1901 #else
1902
1903 static void invalidate_and_set_dirty(hwaddr addr,
1904                                      hwaddr length)
1905 {
1906     if (!cpu_physical_memory_is_dirty(addr)) {
1907         /* invalidate code */
1908         tb_invalidate_phys_page_range(addr, addr + length, 0);
1909         /* set dirty bit */
1910         cpu_physical_memory_set_dirty_flags(addr, (0xff & ~CODE_DIRTY_FLAG));
1911     }
1912     xen_modified_memory(addr, length);
1913 }
1914
1915 static inline bool memory_access_is_direct(MemoryRegion *mr, bool is_write)
1916 {
1917     if (memory_region_is_ram(mr)) {
1918         return !(is_write && mr->readonly);
1919     }
1920     if (memory_region_is_romd(mr)) {
1921         return !is_write;
1922     }
1923
1924     return false;
1925 }
1926
1927 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
1928 {
1929     unsigned access_size_max = mr->ops->valid.max_access_size;
1930
1931     /* Regions are assumed to support 1-4 byte accesses unless
1932        otherwise specified.  */
1933     if (access_size_max == 0) {
1934         access_size_max = 4;
1935     }
1936
1937     /* Bound the maximum access by the alignment of the address.  */
1938     if (!mr->ops->impl.unaligned) {
1939         unsigned align_size_max = addr & -addr;
1940         if (align_size_max != 0 && align_size_max < access_size_max) {
1941             access_size_max = align_size_max;
1942         }
1943     }
1944
1945     /* Don't attempt accesses larger than the maximum.  */
1946     if (l > access_size_max) {
1947         l = access_size_max;
1948     }
1949     if (l & (l - 1)) {
1950         l = 1 << (qemu_fls(l) - 1);
1951     }
1952
1953     return l;
1954 }
1955
1956 bool address_space_rw(AddressSpace *as, hwaddr addr, uint8_t *buf,
1957                       int len, bool is_write)
1958 {
1959     hwaddr l;
1960     uint8_t *ptr;
1961     uint64_t val;
1962     hwaddr addr1;
1963     MemoryRegion *mr;
1964     bool error = false;
1965
1966     while (len > 0) {
1967         l = len;
1968         mr = address_space_translate(as, addr, &addr1, &l, is_write);
1969
1970         if (is_write) {
1971             if (!memory_access_is_direct(mr, is_write)) {
1972                 l = memory_access_size(mr, l, addr1);
1973                 /* XXX: could force current_cpu to NULL to avoid
1974                    potential bugs */
1975                 switch (l) {
1976                 case 8:
1977                     /* 64 bit write access */
1978                     val = ldq_p(buf);
1979                     error |= io_mem_write(mr, addr1, val, 8);
1980                     break;
1981                 case 4:
1982                     /* 32 bit write access */
1983                     val = ldl_p(buf);
1984                     error |= io_mem_write(mr, addr1, val, 4);
1985                     break;
1986                 case 2:
1987                     /* 16 bit write access */
1988                     val = lduw_p(buf);
1989                     error |= io_mem_write(mr, addr1, val, 2);
1990                     break;
1991                 case 1:
1992                     /* 8 bit write access */
1993                     val = ldub_p(buf);
1994                     error |= io_mem_write(mr, addr1, val, 1);
1995                     break;
1996                 default:
1997                     abort();
1998                 }
1999             } else {
2000                 addr1 += memory_region_get_ram_addr(mr);
2001                 /* RAM case */
2002                 ptr = qemu_get_ram_ptr(addr1);
2003                 memcpy(ptr, buf, l);
2004                 invalidate_and_set_dirty(addr1, l);
2005             }
2006         } else {
2007             if (!memory_access_is_direct(mr, is_write)) {
2008                 /* I/O case */
2009                 l = memory_access_size(mr, l, addr1);
2010                 switch (l) {
2011                 case 8:
2012                     /* 64 bit read access */
2013                     error |= io_mem_read(mr, addr1, &val, 8);
2014                     stq_p(buf, val);
2015                     break;
2016                 case 4:
2017                     /* 32 bit read access */
2018                     error |= io_mem_read(mr, addr1, &val, 4);
2019                     stl_p(buf, val);
2020                     break;
2021                 case 2:
2022                     /* 16 bit read access */
2023                     error |= io_mem_read(mr, addr1, &val, 2);
2024                     stw_p(buf, val);
2025                     break;
2026                 case 1:
2027                     /* 8 bit read access */
2028                     error |= io_mem_read(mr, addr1, &val, 1);
2029                     stb_p(buf, val);
2030                     break;
2031                 default:
2032                     abort();
2033                 }
2034             } else {
2035                 /* RAM case */
2036                 ptr = qemu_get_ram_ptr(mr->ram_addr + addr1);
2037                 memcpy(buf, ptr, l);
2038             }
2039         }
2040         len -= l;
2041         buf += l;
2042         addr += l;
2043     }
2044
2045     return error;
2046 }
2047
2048 bool address_space_write(AddressSpace *as, hwaddr addr,
2049                          const uint8_t *buf, int len)
2050 {
2051     return address_space_rw(as, addr, (uint8_t *)buf, len, true);
2052 }
2053
2054 bool address_space_read(AddressSpace *as, hwaddr addr, uint8_t *buf, int len)
2055 {
2056     return address_space_rw(as, addr, buf, len, false);
2057 }
2058
2059
2060 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
2061                             int len, int is_write)
2062 {
2063     address_space_rw(&address_space_memory, addr, buf, len, is_write);
2064 }
2065
2066 /* used for ROM loading : can write in RAM and ROM */
2067 void cpu_physical_memory_write_rom(hwaddr addr,
2068                                    const uint8_t *buf, int len)
2069 {
2070     hwaddr l;
2071     uint8_t *ptr;
2072     hwaddr addr1;
2073     MemoryRegion *mr;
2074
2075     while (len > 0) {
2076         l = len;
2077         mr = address_space_translate(&address_space_memory,
2078                                      addr, &addr1, &l, true);
2079
2080         if (!(memory_region_is_ram(mr) ||
2081               memory_region_is_romd(mr))) {
2082             /* do nothing */
2083         } else {
2084             addr1 += memory_region_get_ram_addr(mr);
2085             /* ROM/RAM case */
2086             ptr = qemu_get_ram_ptr(addr1);
2087             memcpy(ptr, buf, l);
2088             invalidate_and_set_dirty(addr1, l);
2089         }
2090         len -= l;
2091         buf += l;
2092         addr += l;
2093     }
2094 }
2095
2096 typedef struct {
2097     MemoryRegion *mr;
2098     void *buffer;
2099     hwaddr addr;
2100     hwaddr len;
2101 } BounceBuffer;
2102
2103 static BounceBuffer bounce;
2104
2105 typedef struct MapClient {
2106     void *opaque;
2107     void (*callback)(void *opaque);
2108     QLIST_ENTRY(MapClient) link;
2109 } MapClient;
2110
2111 static QLIST_HEAD(map_client_list, MapClient) map_client_list
2112     = QLIST_HEAD_INITIALIZER(map_client_list);
2113
2114 void *cpu_register_map_client(void *opaque, void (*callback)(void *opaque))
2115 {
2116     MapClient *client = g_malloc(sizeof(*client));
2117
2118     client->opaque = opaque;
2119     client->callback = callback;
2120     QLIST_INSERT_HEAD(&map_client_list, client, link);
2121     return client;
2122 }
2123
2124 static void cpu_unregister_map_client(void *_client)
2125 {
2126     MapClient *client = (MapClient *)_client;
2127
2128     QLIST_REMOVE(client, link);
2129     g_free(client);
2130 }
2131
2132 static void cpu_notify_map_clients(void)
2133 {
2134     MapClient *client;
2135
2136     while (!QLIST_EMPTY(&map_client_list)) {
2137         client = QLIST_FIRST(&map_client_list);
2138         client->callback(client->opaque);
2139         cpu_unregister_map_client(client);
2140     }
2141 }
2142
2143 bool address_space_access_valid(AddressSpace *as, hwaddr addr, int len, bool is_write)
2144 {
2145     MemoryRegion *mr;
2146     hwaddr l, xlat;
2147
2148     while (len > 0) {
2149         l = len;
2150         mr = address_space_translate(as, addr, &xlat, &l, is_write);
2151         if (!memory_access_is_direct(mr, is_write)) {
2152             l = memory_access_size(mr, l, addr);
2153             if (!memory_region_access_valid(mr, xlat, l, is_write)) {
2154                 return false;
2155             }
2156         }
2157
2158         len -= l;
2159         addr += l;
2160     }
2161     return true;
2162 }
2163
2164 /* Map a physical memory region into a host virtual address.
2165  * May map a subset of the requested range, given by and returned in *plen.
2166  * May return NULL if resources needed to perform the mapping are exhausted.
2167  * Use only for reads OR writes - not for read-modify-write operations.
2168  * Use cpu_register_map_client() to know when retrying the map operation is
2169  * likely to succeed.
2170  */
2171 void *address_space_map(AddressSpace *as,
2172                         hwaddr addr,
2173                         hwaddr *plen,
2174                         bool is_write)
2175 {
2176     hwaddr len = *plen;
2177     hwaddr done = 0;
2178     hwaddr l, xlat, base;
2179     MemoryRegion *mr, *this_mr;
2180     ram_addr_t raddr;
2181
2182     if (len == 0) {
2183         return NULL;
2184     }
2185
2186     l = len;
2187     mr = address_space_translate(as, addr, &xlat, &l, is_write);
2188     if (!memory_access_is_direct(mr, is_write)) {
2189         if (bounce.buffer) {
2190             return NULL;
2191         }
2192         bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, TARGET_PAGE_SIZE);
2193         bounce.addr = addr;
2194         bounce.len = l;
2195
2196         memory_region_ref(mr);
2197         bounce.mr = mr;
2198         if (!is_write) {
2199             address_space_read(as, addr, bounce.buffer, l);
2200         }
2201
2202         *plen = l;
2203         return bounce.buffer;
2204     }
2205
2206     base = xlat;
2207     raddr = memory_region_get_ram_addr(mr);
2208
2209     for (;;) {
2210         len -= l;
2211         addr += l;
2212         done += l;
2213         if (len == 0) {
2214             break;
2215         }
2216
2217         l = len;
2218         this_mr = address_space_translate(as, addr, &xlat, &l, is_write);
2219         if (this_mr != mr || xlat != base + done) {
2220             break;
2221         }
2222     }
2223
2224     memory_region_ref(mr);
2225     *plen = done;
2226     return qemu_ram_ptr_length(raddr + base, plen);
2227 }
2228
2229 /* Unmaps a memory region previously mapped by address_space_map().
2230  * Will also mark the memory as dirty if is_write == 1.  access_len gives
2231  * the amount of memory that was actually read or written by the caller.
2232  */
2233 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
2234                          int is_write, hwaddr access_len)
2235 {
2236     if (buffer != bounce.buffer) {
2237         MemoryRegion *mr;
2238         ram_addr_t addr1;
2239
2240         mr = qemu_ram_addr_from_host(buffer, &addr1);
2241         assert(mr != NULL);
2242         if (is_write) {
2243             while (access_len) {
2244                 unsigned l;
2245                 l = TARGET_PAGE_SIZE;
2246                 if (l > access_len)
2247                     l = access_len;
2248                 invalidate_and_set_dirty(addr1, l);
2249                 addr1 += l;
2250                 access_len -= l;
2251             }
2252         }
2253         if (xen_enabled()) {
2254             xen_invalidate_map_cache_entry(buffer);
2255         }
2256         memory_region_unref(mr);
2257         return;
2258     }
2259     if (is_write) {
2260         address_space_write(as, bounce.addr, bounce.buffer, access_len);
2261     }
2262     qemu_vfree(bounce.buffer);
2263     bounce.buffer = NULL;
2264     memory_region_unref(bounce.mr);
2265     cpu_notify_map_clients();
2266 }
2267
2268 void *cpu_physical_memory_map(hwaddr addr,
2269                               hwaddr *plen,
2270                               int is_write)
2271 {
2272     return address_space_map(&address_space_memory, addr, plen, is_write);
2273 }
2274
2275 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
2276                                int is_write, hwaddr access_len)
2277 {
2278     return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
2279 }
2280
2281 /* warning: addr must be aligned */
2282 static inline uint32_t ldl_phys_internal(hwaddr addr,
2283                                          enum device_endian endian)
2284 {
2285     uint8_t *ptr;
2286     uint64_t val;
2287     MemoryRegion *mr;
2288     hwaddr l = 4;
2289     hwaddr addr1;
2290
2291     mr = address_space_translate(&address_space_memory, addr, &addr1, &l,
2292                                  false);
2293     if (l < 4 || !memory_access_is_direct(mr, false)) {
2294         /* I/O case */
2295         io_mem_read(mr, addr1, &val, 4);
2296 #if defined(TARGET_WORDS_BIGENDIAN)
2297         if (endian == DEVICE_LITTLE_ENDIAN) {
2298             val = bswap32(val);
2299         }
2300 #else
2301         if (endian == DEVICE_BIG_ENDIAN) {
2302             val = bswap32(val);
2303         }
2304 #endif
2305     } else {
2306         /* RAM case */
2307         ptr = qemu_get_ram_ptr((memory_region_get_ram_addr(mr)
2308                                 & TARGET_PAGE_MASK)
2309                                + addr1);
2310         switch (endian) {
2311         case DEVICE_LITTLE_ENDIAN:
2312             val = ldl_le_p(ptr);
2313             break;
2314         case DEVICE_BIG_ENDIAN:
2315             val = ldl_be_p(ptr);
2316             break;
2317         default:
2318             val = ldl_p(ptr);
2319             break;
2320         }
2321     }
2322     return val;
2323 }
2324
2325 uint32_t ldl_phys(hwaddr addr)
2326 {
2327     return ldl_phys_internal(addr, DEVICE_NATIVE_ENDIAN);
2328 }
2329
2330 uint32_t ldl_le_phys(hwaddr addr)
2331 {
2332     return ldl_phys_internal(addr, DEVICE_LITTLE_ENDIAN);
2333 }
2334
2335 uint32_t ldl_be_phys(hwaddr addr)
2336 {
2337     return ldl_phys_internal(addr, DEVICE_BIG_ENDIAN);
2338 }
2339
2340 /* warning: addr must be aligned */
2341 static inline uint64_t ldq_phys_internal(hwaddr addr,
2342                                          enum device_endian endian)
2343 {
2344     uint8_t *ptr;
2345     uint64_t val;
2346     MemoryRegion *mr;
2347     hwaddr l = 8;
2348     hwaddr addr1;
2349
2350     mr = address_space_translate(&address_space_memory, addr, &addr1, &l,
2351                                  false);
2352     if (l < 8 || !memory_access_is_direct(mr, false)) {
2353         /* I/O case */
2354         io_mem_read(mr, addr1, &val, 8);
2355 #if defined(TARGET_WORDS_BIGENDIAN)
2356         if (endian == DEVICE_LITTLE_ENDIAN) {
2357             val = bswap64(val);
2358         }
2359 #else
2360         if (endian == DEVICE_BIG_ENDIAN) {
2361             val = bswap64(val);
2362         }
2363 #endif
2364     } else {
2365         /* RAM case */
2366         ptr = qemu_get_ram_ptr((memory_region_get_ram_addr(mr)
2367                                 & TARGET_PAGE_MASK)
2368                                + addr1);
2369         switch (endian) {
2370         case DEVICE_LITTLE_ENDIAN:
2371             val = ldq_le_p(ptr);
2372             break;
2373         case DEVICE_BIG_ENDIAN:
2374             val = ldq_be_p(ptr);
2375             break;
2376         default:
2377             val = ldq_p(ptr);
2378             break;
2379         }
2380     }
2381     return val;
2382 }
2383
2384 uint64_t ldq_phys(hwaddr addr)
2385 {
2386     return ldq_phys_internal(addr, DEVICE_NATIVE_ENDIAN);
2387 }
2388
2389 uint64_t ldq_le_phys(hwaddr addr)
2390 {
2391     return ldq_phys_internal(addr, DEVICE_LITTLE_ENDIAN);
2392 }
2393
2394 uint64_t ldq_be_phys(hwaddr addr)
2395 {
2396     return ldq_phys_internal(addr, DEVICE_BIG_ENDIAN);
2397 }
2398
2399 /* XXX: optimize */
2400 uint32_t ldub_phys(hwaddr addr)
2401 {
2402     uint8_t val;
2403     cpu_physical_memory_read(addr, &val, 1);
2404     return val;
2405 }
2406
2407 /* warning: addr must be aligned */
2408 static inline uint32_t lduw_phys_internal(hwaddr addr,
2409                                           enum device_endian endian)
2410 {
2411     uint8_t *ptr;
2412     uint64_t val;
2413     MemoryRegion *mr;
2414     hwaddr l = 2;
2415     hwaddr addr1;
2416
2417     mr = address_space_translate(&address_space_memory, addr, &addr1, &l,
2418                                  false);
2419     if (l < 2 || !memory_access_is_direct(mr, false)) {
2420         /* I/O case */
2421         io_mem_read(mr, addr1, &val, 2);
2422 #if defined(TARGET_WORDS_BIGENDIAN)
2423         if (endian == DEVICE_LITTLE_ENDIAN) {
2424             val = bswap16(val);
2425         }
2426 #else
2427         if (endian == DEVICE_BIG_ENDIAN) {
2428             val = bswap16(val);
2429         }
2430 #endif
2431     } else {
2432         /* RAM case */
2433         ptr = qemu_get_ram_ptr((memory_region_get_ram_addr(mr)
2434                                 & TARGET_PAGE_MASK)
2435                                + addr1);
2436         switch (endian) {
2437         case DEVICE_LITTLE_ENDIAN:
2438             val = lduw_le_p(ptr);
2439             break;
2440         case DEVICE_BIG_ENDIAN:
2441             val = lduw_be_p(ptr);
2442             break;
2443         default:
2444             val = lduw_p(ptr);
2445             break;
2446         }
2447     }
2448     return val;
2449 }
2450
2451 uint32_t lduw_phys(hwaddr addr)
2452 {
2453     return lduw_phys_internal(addr, DEVICE_NATIVE_ENDIAN);
2454 }
2455
2456 uint32_t lduw_le_phys(hwaddr addr)
2457 {
2458     return lduw_phys_internal(addr, DEVICE_LITTLE_ENDIAN);
2459 }
2460
2461 uint32_t lduw_be_phys(hwaddr addr)
2462 {
2463     return lduw_phys_internal(addr, DEVICE_BIG_ENDIAN);
2464 }
2465
2466 /* warning: addr must be aligned. The ram page is not masked as dirty
2467    and the code inside is not invalidated. It is useful if the dirty
2468    bits are used to track modified PTEs */
2469 void stl_phys_notdirty(hwaddr addr, uint32_t val)
2470 {
2471     uint8_t *ptr;
2472     MemoryRegion *mr;
2473     hwaddr l = 4;
2474     hwaddr addr1;
2475
2476     mr = address_space_translate(&address_space_memory, addr, &addr1, &l,
2477                                  true);
2478     if (l < 4 || !memory_access_is_direct(mr, true)) {
2479         io_mem_write(mr, addr1, val, 4);
2480     } else {
2481         addr1 += memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK;
2482         ptr = qemu_get_ram_ptr(addr1);
2483         stl_p(ptr, val);
2484
2485         if (unlikely(in_migration)) {
2486             if (!cpu_physical_memory_is_dirty(addr1)) {
2487                 /* invalidate code */
2488                 tb_invalidate_phys_page_range(addr1, addr1 + 4, 0);
2489                 /* set dirty bit */
2490                 cpu_physical_memory_set_dirty_flags(
2491                     addr1, (0xff & ~CODE_DIRTY_FLAG));
2492             }
2493         }
2494     }
2495 }
2496
2497 /* warning: addr must be aligned */
2498 static inline void stl_phys_internal(hwaddr addr, uint32_t val,
2499                                      enum device_endian endian)
2500 {
2501     uint8_t *ptr;
2502     MemoryRegion *mr;
2503     hwaddr l = 4;
2504     hwaddr addr1;
2505
2506     mr = address_space_translate(&address_space_memory, addr, &addr1, &l,
2507                                  true);
2508     if (l < 4 || !memory_access_is_direct(mr, true)) {
2509 #if defined(TARGET_WORDS_BIGENDIAN)
2510         if (endian == DEVICE_LITTLE_ENDIAN) {
2511             val = bswap32(val);
2512         }
2513 #else
2514         if (endian == DEVICE_BIG_ENDIAN) {
2515             val = bswap32(val);
2516         }
2517 #endif
2518         io_mem_write(mr, addr1, val, 4);
2519     } else {
2520         /* RAM case */
2521         addr1 += memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK;
2522         ptr = qemu_get_ram_ptr(addr1);
2523         switch (endian) {
2524         case DEVICE_LITTLE_ENDIAN:
2525             stl_le_p(ptr, val);
2526             break;
2527         case DEVICE_BIG_ENDIAN:
2528             stl_be_p(ptr, val);
2529             break;
2530         default:
2531             stl_p(ptr, val);
2532             break;
2533         }
2534         invalidate_and_set_dirty(addr1, 4);
2535     }
2536 }
2537
2538 void stl_phys(hwaddr addr, uint32_t val)
2539 {
2540     stl_phys_internal(addr, val, DEVICE_NATIVE_ENDIAN);
2541 }
2542
2543 void stl_le_phys(hwaddr addr, uint32_t val)
2544 {
2545     stl_phys_internal(addr, val, DEVICE_LITTLE_ENDIAN);
2546 }
2547
2548 void stl_be_phys(hwaddr addr, uint32_t val)
2549 {
2550     stl_phys_internal(addr, val, DEVICE_BIG_ENDIAN);
2551 }
2552
2553 /* XXX: optimize */
2554 void stb_phys(hwaddr addr, uint32_t val)
2555 {
2556     uint8_t v = val;
2557     cpu_physical_memory_write(addr, &v, 1);
2558 }
2559
2560 /* warning: addr must be aligned */
2561 static inline void stw_phys_internal(hwaddr addr, uint32_t val,
2562                                      enum device_endian endian)
2563 {
2564     uint8_t *ptr;
2565     MemoryRegion *mr;
2566     hwaddr l = 2;
2567     hwaddr addr1;
2568
2569     mr = address_space_translate(&address_space_memory, addr, &addr1, &l,
2570                                  true);
2571     if (l < 2 || !memory_access_is_direct(mr, true)) {
2572 #if defined(TARGET_WORDS_BIGENDIAN)
2573         if (endian == DEVICE_LITTLE_ENDIAN) {
2574             val = bswap16(val);
2575         }
2576 #else
2577         if (endian == DEVICE_BIG_ENDIAN) {
2578             val = bswap16(val);
2579         }
2580 #endif
2581         io_mem_write(mr, addr1, val, 2);
2582     } else {
2583         /* RAM case */
2584         addr1 += memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK;
2585         ptr = qemu_get_ram_ptr(addr1);
2586         switch (endian) {
2587         case DEVICE_LITTLE_ENDIAN:
2588             stw_le_p(ptr, val);
2589             break;
2590         case DEVICE_BIG_ENDIAN:
2591             stw_be_p(ptr, val);
2592             break;
2593         default:
2594             stw_p(ptr, val);
2595             break;
2596         }
2597         invalidate_and_set_dirty(addr1, 2);
2598     }
2599 }
2600
2601 void stw_phys(hwaddr addr, uint32_t val)
2602 {
2603     stw_phys_internal(addr, val, DEVICE_NATIVE_ENDIAN);
2604 }
2605
2606 void stw_le_phys(hwaddr addr, uint32_t val)
2607 {
2608     stw_phys_internal(addr, val, DEVICE_LITTLE_ENDIAN);
2609 }
2610
2611 void stw_be_phys(hwaddr addr, uint32_t val)
2612 {
2613     stw_phys_internal(addr, val, DEVICE_BIG_ENDIAN);
2614 }
2615
2616 /* XXX: optimize */
2617 void stq_phys(hwaddr addr, uint64_t val)
2618 {
2619     val = tswap64(val);
2620     cpu_physical_memory_write(addr, &val, 8);
2621 }
2622
2623 void stq_le_phys(hwaddr addr, uint64_t val)
2624 {
2625     val = cpu_to_le64(val);
2626     cpu_physical_memory_write(addr, &val, 8);
2627 }
2628
2629 void stq_be_phys(hwaddr addr, uint64_t val)
2630 {
2631     val = cpu_to_be64(val);
2632     cpu_physical_memory_write(addr, &val, 8);
2633 }
2634
2635 /* virtual memory access for debug (includes writing to ROM) */
2636 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
2637                         uint8_t *buf, int len, int is_write)
2638 {
2639     int l;
2640     hwaddr phys_addr;
2641     target_ulong page;
2642
2643     while (len > 0) {
2644         page = addr & TARGET_PAGE_MASK;
2645         phys_addr = cpu_get_phys_page_debug(cpu, page);
2646         /* if no physical page mapped, return an error */
2647         if (phys_addr == -1)
2648             return -1;
2649         l = (page + TARGET_PAGE_SIZE) - addr;
2650         if (l > len)
2651             l = len;
2652         phys_addr += (addr & ~TARGET_PAGE_MASK);
2653         if (is_write)
2654             cpu_physical_memory_write_rom(phys_addr, buf, l);
2655         else
2656             cpu_physical_memory_rw(phys_addr, buf, l, is_write);
2657         len -= l;
2658         buf += l;
2659         addr += l;
2660     }
2661     return 0;
2662 }
2663 #endif
2664
2665 #if !defined(CONFIG_USER_ONLY)
2666
2667 /*
2668  * A helper function for the _utterly broken_ virtio device model to find out if
2669  * it's running on a big endian machine. Don't do this at home kids!
2670  */
2671 bool virtio_is_big_endian(void);
2672 bool virtio_is_big_endian(void)
2673 {
2674 #if defined(TARGET_WORDS_BIGENDIAN)
2675     return true;
2676 #else
2677     return false;
2678 #endif
2679 }
2680
2681 #endif
2682
2683 #ifndef CONFIG_USER_ONLY
2684 bool cpu_physical_memory_is_io(hwaddr phys_addr)
2685 {
2686     MemoryRegion*mr;
2687     hwaddr l = 1;
2688
2689     mr = address_space_translate(&address_space_memory,
2690                                  phys_addr, &phys_addr, &l, false);
2691
2692     return !(memory_region_is_ram(mr) ||
2693              memory_region_is_romd(mr));
2694 }
2695
2696 void qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
2697 {
2698     RAMBlock *block;
2699
2700     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
2701         func(block->host, block->offset, block->length, opaque);
2702     }
2703 }
2704 #endif