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