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