]> git.proxmox.com Git - mirror_qemu.git/blob - exec.c
Merge remote-tracking branch 'remotes/ehabkost/tags/machine-next-pull-request' into...
[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 #endif
103
104 #ifdef TARGET_PAGE_BITS_VARY
105 int target_page_bits;
106 bool target_page_bits_decided;
107 #endif
108
109 struct CPUTailQ cpus = QTAILQ_HEAD_INITIALIZER(cpus);
110 /* current CPU in the current thread. It is only valid inside
111 cpu_exec() */
112 __thread CPUState *current_cpu;
113 /* 0 = Do not count executed instructions.
114 1 = Precise instruction counting.
115 2 = Adaptive rate instruction counting. */
116 int use_icount;
117
118 uintptr_t qemu_host_page_size;
119 intptr_t qemu_host_page_mask;
120
121 bool set_preferred_target_page_bits(int bits)
122 {
123 /* The target page size is the lowest common denominator for all
124 * the CPUs in the system, so we can only make it smaller, never
125 * larger. And we can't make it smaller once we've committed to
126 * a particular size.
127 */
128 #ifdef TARGET_PAGE_BITS_VARY
129 assert(bits >= TARGET_PAGE_BITS_MIN);
130 if (target_page_bits == 0 || target_page_bits > bits) {
131 if (target_page_bits_decided) {
132 return false;
133 }
134 target_page_bits = bits;
135 }
136 #endif
137 return true;
138 }
139
140 #if !defined(CONFIG_USER_ONLY)
141
142 static void finalize_target_page_bits(void)
143 {
144 #ifdef TARGET_PAGE_BITS_VARY
145 if (target_page_bits == 0) {
146 target_page_bits = TARGET_PAGE_BITS_MIN;
147 }
148 target_page_bits_decided = true;
149 #endif
150 }
151
152 typedef struct PhysPageEntry PhysPageEntry;
153
154 struct PhysPageEntry {
155 /* How many bits skip to next level (in units of L2_SIZE). 0 for a leaf. */
156 uint32_t skip : 6;
157 /* index into phys_sections (!skip) or phys_map_nodes (skip) */
158 uint32_t ptr : 26;
159 };
160
161 #define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
162
163 /* Size of the L2 (and L3, etc) page tables. */
164 #define ADDR_SPACE_BITS 64
165
166 #define P_L2_BITS 9
167 #define P_L2_SIZE (1 << P_L2_BITS)
168
169 #define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
170
171 typedef PhysPageEntry Node[P_L2_SIZE];
172
173 typedef struct PhysPageMap {
174 struct rcu_head rcu;
175
176 unsigned sections_nb;
177 unsigned sections_nb_alloc;
178 unsigned nodes_nb;
179 unsigned nodes_nb_alloc;
180 Node *nodes;
181 MemoryRegionSection *sections;
182 } PhysPageMap;
183
184 struct AddressSpaceDispatch {
185 MemoryRegionSection *mru_section;
186 /* This is a multi-level map on the physical address space.
187 * The bottom level has pointers to MemoryRegionSections.
188 */
189 PhysPageEntry phys_map;
190 PhysPageMap map;
191 };
192
193 #define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
194 typedef struct subpage_t {
195 MemoryRegion iomem;
196 FlatView *fv;
197 hwaddr base;
198 uint16_t sub_section[];
199 } subpage_t;
200
201 #define PHYS_SECTION_UNASSIGNED 0
202 #define PHYS_SECTION_NOTDIRTY 1
203 #define PHYS_SECTION_ROM 2
204 #define PHYS_SECTION_WATCH 3
205
206 static void io_mem_init(void);
207 static void memory_map_init(void);
208 static void tcg_commit(MemoryListener *listener);
209
210 static MemoryRegion io_mem_watch;
211
212 /**
213 * CPUAddressSpace: all the information a CPU needs about an AddressSpace
214 * @cpu: the CPU whose AddressSpace this is
215 * @as: the AddressSpace itself
216 * @memory_dispatch: its dispatch pointer (cached, RCU protected)
217 * @tcg_as_listener: listener for tracking changes to the AddressSpace
218 */
219 struct CPUAddressSpace {
220 CPUState *cpu;
221 AddressSpace *as;
222 struct AddressSpaceDispatch *memory_dispatch;
223 MemoryListener tcg_as_listener;
224 };
225
226 struct DirtyBitmapSnapshot {
227 ram_addr_t start;
228 ram_addr_t end;
229 unsigned long dirty[];
230 };
231
232 #endif
233
234 #if !defined(CONFIG_USER_ONLY)
235
236 static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
237 {
238 static unsigned alloc_hint = 16;
239 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
240 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, alloc_hint);
241 map->nodes_nb_alloc = MAX(map->nodes_nb_alloc, map->nodes_nb + nodes);
242 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
243 alloc_hint = map->nodes_nb_alloc;
244 }
245 }
246
247 static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
248 {
249 unsigned i;
250 uint32_t ret;
251 PhysPageEntry e;
252 PhysPageEntry *p;
253
254 ret = map->nodes_nb++;
255 p = map->nodes[ret];
256 assert(ret != PHYS_MAP_NODE_NIL);
257 assert(ret != map->nodes_nb_alloc);
258
259 e.skip = leaf ? 0 : 1;
260 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
261 for (i = 0; i < P_L2_SIZE; ++i) {
262 memcpy(&p[i], &e, sizeof(e));
263 }
264 return ret;
265 }
266
267 static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
268 hwaddr *index, hwaddr *nb, uint16_t leaf,
269 int level)
270 {
271 PhysPageEntry *p;
272 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
273
274 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
275 lp->ptr = phys_map_node_alloc(map, level == 0);
276 }
277 p = map->nodes[lp->ptr];
278 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
279
280 while (*nb && lp < &p[P_L2_SIZE]) {
281 if ((*index & (step - 1)) == 0 && *nb >= step) {
282 lp->skip = 0;
283 lp->ptr = leaf;
284 *index += step;
285 *nb -= step;
286 } else {
287 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
288 }
289 ++lp;
290 }
291 }
292
293 static void phys_page_set(AddressSpaceDispatch *d,
294 hwaddr index, hwaddr nb,
295 uint16_t leaf)
296 {
297 /* Wildly overreserve - it doesn't matter much. */
298 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
299
300 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
301 }
302
303 /* Compact a non leaf page entry. Simply detect that the entry has a single child,
304 * and update our entry so we can skip it and go directly to the destination.
305 */
306 static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
307 {
308 unsigned valid_ptr = P_L2_SIZE;
309 int valid = 0;
310 PhysPageEntry *p;
311 int i;
312
313 if (lp->ptr == PHYS_MAP_NODE_NIL) {
314 return;
315 }
316
317 p = nodes[lp->ptr];
318 for (i = 0; i < P_L2_SIZE; i++) {
319 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
320 continue;
321 }
322
323 valid_ptr = i;
324 valid++;
325 if (p[i].skip) {
326 phys_page_compact(&p[i], nodes);
327 }
328 }
329
330 /* We can only compress if there's only one child. */
331 if (valid != 1) {
332 return;
333 }
334
335 assert(valid_ptr < P_L2_SIZE);
336
337 /* Don't compress if it won't fit in the # of bits we have. */
338 if (lp->skip + p[valid_ptr].skip >= (1 << 3)) {
339 return;
340 }
341
342 lp->ptr = p[valid_ptr].ptr;
343 if (!p[valid_ptr].skip) {
344 /* If our only child is a leaf, make this a leaf. */
345 /* By design, we should have made this node a leaf to begin with so we
346 * should never reach here.
347 * But since it's so simple to handle this, let's do it just in case we
348 * change this rule.
349 */
350 lp->skip = 0;
351 } else {
352 lp->skip += p[valid_ptr].skip;
353 }
354 }
355
356 void address_space_dispatch_compact(AddressSpaceDispatch *d)
357 {
358 if (d->phys_map.skip) {
359 phys_page_compact(&d->phys_map, d->map.nodes);
360 }
361 }
362
363 static inline bool section_covers_addr(const MemoryRegionSection *section,
364 hwaddr addr)
365 {
366 /* Memory topology clips a memory region to [0, 2^64); size.hi > 0 means
367 * the section must cover the entire address space.
368 */
369 return int128_gethi(section->size) ||
370 range_covers_byte(section->offset_within_address_space,
371 int128_getlo(section->size), addr);
372 }
373
374 static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
375 {
376 PhysPageEntry lp = d->phys_map, *p;
377 Node *nodes = d->map.nodes;
378 MemoryRegionSection *sections = d->map.sections;
379 hwaddr index = addr >> TARGET_PAGE_BITS;
380 int i;
381
382 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
383 if (lp.ptr == PHYS_MAP_NODE_NIL) {
384 return &sections[PHYS_SECTION_UNASSIGNED];
385 }
386 p = nodes[lp.ptr];
387 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
388 }
389
390 if (section_covers_addr(&sections[lp.ptr], addr)) {
391 return &sections[lp.ptr];
392 } else {
393 return &sections[PHYS_SECTION_UNASSIGNED];
394 }
395 }
396
397 bool memory_region_is_unassigned(MemoryRegion *mr)
398 {
399 return mr != &io_mem_rom && mr != &io_mem_notdirty && !mr->rom_device
400 && mr != &io_mem_watch;
401 }
402
403 /* Called from RCU critical section */
404 static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
405 hwaddr addr,
406 bool resolve_subpage)
407 {
408 MemoryRegionSection *section = atomic_read(&d->mru_section);
409 subpage_t *subpage;
410
411 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
412 !section_covers_addr(section, addr)) {
413 section = phys_page_find(d, addr);
414 atomic_set(&d->mru_section, section);
415 }
416 if (resolve_subpage && section->mr->subpage) {
417 subpage = container_of(section->mr, subpage_t, iomem);
418 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
419 }
420 return section;
421 }
422
423 /* Called from RCU critical section */
424 static MemoryRegionSection *
425 address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
426 hwaddr *plen, bool resolve_subpage)
427 {
428 MemoryRegionSection *section;
429 MemoryRegion *mr;
430 Int128 diff;
431
432 section = address_space_lookup_region(d, addr, resolve_subpage);
433 /* Compute offset within MemoryRegionSection */
434 addr -= section->offset_within_address_space;
435
436 /* Compute offset within MemoryRegion */
437 *xlat = addr + section->offset_within_region;
438
439 mr = section->mr;
440
441 /* MMIO registers can be expected to perform full-width accesses based only
442 * on their address, without considering adjacent registers that could
443 * decode to completely different MemoryRegions. When such registers
444 * exist (e.g. I/O ports 0xcf8 and 0xcf9 on most PC chipsets), MMIO
445 * regions overlap wildly. For this reason we cannot clamp the accesses
446 * here.
447 *
448 * If the length is small (as is the case for address_space_ldl/stl),
449 * everything works fine. If the incoming length is large, however,
450 * the caller really has to do the clamping through memory_access_size.
451 */
452 if (memory_region_is_ram(mr)) {
453 diff = int128_sub(section->size, int128_make64(addr));
454 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
455 }
456 return section;
457 }
458
459 /**
460 * flatview_do_translate - translate an address in FlatView
461 *
462 * @fv: the flat view that we want to translate on
463 * @addr: the address to be translated in above address space
464 * @xlat: the translated address offset within memory region. It
465 * cannot be @NULL.
466 * @plen_out: valid read/write length of the translated address. It
467 * can be @NULL when we don't care about it.
468 * @page_mask_out: page mask for the translated address. This
469 * should only be meaningful for IOMMU translated
470 * addresses, since there may be huge pages that this bit
471 * would tell. It can be @NULL if we don't care about it.
472 * @is_write: whether the translation operation is for write
473 * @is_mmio: whether this can be MMIO, set true if it can
474 *
475 * This function is called from RCU critical section
476 */
477 static MemoryRegionSection flatview_do_translate(FlatView *fv,
478 hwaddr addr,
479 hwaddr *xlat,
480 hwaddr *plen_out,
481 hwaddr *page_mask_out,
482 bool is_write,
483 bool is_mmio,
484 AddressSpace **target_as)
485 {
486 IOMMUTLBEntry iotlb;
487 MemoryRegionSection *section;
488 IOMMUMemoryRegion *iommu_mr;
489 IOMMUMemoryRegionClass *imrc;
490 hwaddr page_mask = (hwaddr)(-1);
491 hwaddr plen = (hwaddr)(-1);
492
493 if (plen_out) {
494 plen = *plen_out;
495 }
496
497 for (;;) {
498 section = address_space_translate_internal(
499 flatview_to_dispatch(fv), addr, &addr,
500 &plen, is_mmio);
501
502 iommu_mr = memory_region_get_iommu(section->mr);
503 if (!iommu_mr) {
504 break;
505 }
506 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
507
508 iotlb = imrc->translate(iommu_mr, addr, is_write ?
509 IOMMU_WO : IOMMU_RO);
510 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
511 | (addr & iotlb.addr_mask));
512 page_mask &= iotlb.addr_mask;
513 plen = MIN(plen, (addr | iotlb.addr_mask) - addr + 1);
514 if (!(iotlb.perm & (1 << is_write))) {
515 goto translate_fail;
516 }
517
518 fv = address_space_to_flatview(iotlb.target_as);
519 *target_as = iotlb.target_as;
520 }
521
522 *xlat = addr;
523
524 if (page_mask == (hwaddr)(-1)) {
525 /* Not behind an IOMMU, use default page size. */
526 page_mask = ~TARGET_PAGE_MASK;
527 }
528
529 if (page_mask_out) {
530 *page_mask_out = page_mask;
531 }
532
533 if (plen_out) {
534 *plen_out = plen;
535 }
536
537 return *section;
538
539 translate_fail:
540 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
541 }
542
543 /* Called from RCU critical section */
544 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
545 bool is_write)
546 {
547 MemoryRegionSection section;
548 hwaddr xlat, page_mask;
549
550 /*
551 * This can never be MMIO, and we don't really care about plen,
552 * but page mask.
553 */
554 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
555 NULL, &page_mask, is_write, false, &as);
556
557 /* Illegal translation */
558 if (section.mr == &io_mem_unassigned) {
559 goto iotlb_fail;
560 }
561
562 /* Convert memory region offset into address space offset */
563 xlat += section.offset_within_address_space -
564 section.offset_within_region;
565
566 return (IOMMUTLBEntry) {
567 .target_as = as,
568 .iova = addr & ~page_mask,
569 .translated_addr = xlat & ~page_mask,
570 .addr_mask = page_mask,
571 /* IOTLBs are for DMAs, and DMA only allows on RAMs. */
572 .perm = IOMMU_RW,
573 };
574
575 iotlb_fail:
576 return (IOMMUTLBEntry) {0};
577 }
578
579 /* Called from RCU critical section */
580 MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
581 hwaddr *plen, bool is_write)
582 {
583 MemoryRegion *mr;
584 MemoryRegionSection section;
585 AddressSpace *as = NULL;
586
587 /* This can be MMIO, so setup MMIO bit. */
588 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
589 is_write, true, &as);
590 mr = section.mr;
591
592 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
593 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
594 *plen = MIN(page, *plen);
595 }
596
597 return mr;
598 }
599
600 /* Called from RCU critical section */
601 MemoryRegionSection *
602 address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
603 hwaddr *xlat, hwaddr *plen)
604 {
605 MemoryRegionSection *section;
606 AddressSpaceDispatch *d = atomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
607
608 section = address_space_translate_internal(d, addr, xlat, plen, false);
609
610 assert(!memory_region_is_iommu(section->mr));
611 return section;
612 }
613 #endif
614
615 #if !defined(CONFIG_USER_ONLY)
616
617 static int cpu_common_post_load(void *opaque, int version_id)
618 {
619 CPUState *cpu = opaque;
620
621 /* 0x01 was CPU_INTERRUPT_EXIT. This line can be removed when the
622 version_id is increased. */
623 cpu->interrupt_request &= ~0x01;
624 tlb_flush(cpu);
625
626 /* 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 char *mem_path;
1487 long *hpsize_min = opaque;
1488
1489 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1490 mem_path = object_property_get_str(obj, "mem-path", NULL);
1491 if (mem_path) {
1492 long hpsize = qemu_mempath_getpagesize(mem_path);
1493 if (hpsize < *hpsize_min) {
1494 *hpsize_min = hpsize;
1495 }
1496 } else {
1497 *hpsize_min = getpagesize();
1498 }
1499 }
1500
1501 return 0;
1502 }
1503
1504 long qemu_getrampagesize(void)
1505 {
1506 long hpsize = LONG_MAX;
1507 long mainrampagesize;
1508 Object *memdev_root;
1509
1510 if (mem_path) {
1511 mainrampagesize = qemu_mempath_getpagesize(mem_path);
1512 } else {
1513 mainrampagesize = getpagesize();
1514 }
1515
1516 /* it's possible we have memory-backend objects with
1517 * hugepage-backed RAM. these may get mapped into system
1518 * address space via -numa parameters or memory hotplug
1519 * hooks. we want to take these into account, but we
1520 * also want to make sure these supported hugepage
1521 * sizes are applicable across the entire range of memory
1522 * we may boot from, so we take the min across all
1523 * backends, and assume normal pages in cases where a
1524 * backend isn't backed by hugepages.
1525 */
1526 memdev_root = object_resolve_path("/objects", NULL);
1527 if (memdev_root) {
1528 object_child_foreach(memdev_root, find_max_supported_pagesize, &hpsize);
1529 }
1530 if (hpsize == LONG_MAX) {
1531 /* No additional memory regions found ==> Report main RAM page size */
1532 return mainrampagesize;
1533 }
1534
1535 /* If NUMA is disabled or the NUMA nodes are not backed with a
1536 * memory-backend, then there is at least one node using "normal" RAM,
1537 * so if its page size is smaller we have got to report that size instead.
1538 */
1539 if (hpsize > mainrampagesize &&
1540 (nb_numa_nodes == 0 || numa_info[0].node_memdev == NULL)) {
1541 static bool warned;
1542 if (!warned) {
1543 error_report("Huge page support disabled (n/a for main memory).");
1544 warned = true;
1545 }
1546 return mainrampagesize;
1547 }
1548
1549 return hpsize;
1550 }
1551 #else
1552 long qemu_getrampagesize(void)
1553 {
1554 return getpagesize();
1555 }
1556 #endif
1557
1558 #ifdef __linux__
1559 static int64_t get_file_size(int fd)
1560 {
1561 int64_t size = lseek(fd, 0, SEEK_END);
1562 if (size < 0) {
1563 return -errno;
1564 }
1565 return size;
1566 }
1567
1568 static int file_ram_open(const char *path,
1569 const char *region_name,
1570 bool *created,
1571 Error **errp)
1572 {
1573 char *filename;
1574 char *sanitized_name;
1575 char *c;
1576 int fd = -1;
1577
1578 *created = false;
1579 for (;;) {
1580 fd = open(path, O_RDWR);
1581 if (fd >= 0) {
1582 /* @path names an existing file, use it */
1583 break;
1584 }
1585 if (errno == ENOENT) {
1586 /* @path names a file that doesn't exist, create it */
1587 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1588 if (fd >= 0) {
1589 *created = true;
1590 break;
1591 }
1592 } else if (errno == EISDIR) {
1593 /* @path names a directory, create a file there */
1594 /* Make name safe to use with mkstemp by replacing '/' with '_'. */
1595 sanitized_name = g_strdup(region_name);
1596 for (c = sanitized_name; *c != '\0'; c++) {
1597 if (*c == '/') {
1598 *c = '_';
1599 }
1600 }
1601
1602 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1603 sanitized_name);
1604 g_free(sanitized_name);
1605
1606 fd = mkstemp(filename);
1607 if (fd >= 0) {
1608 unlink(filename);
1609 g_free(filename);
1610 break;
1611 }
1612 g_free(filename);
1613 }
1614 if (errno != EEXIST && errno != EINTR) {
1615 error_setg_errno(errp, errno,
1616 "can't open backing store %s for guest RAM",
1617 path);
1618 return -1;
1619 }
1620 /*
1621 * Try again on EINTR and EEXIST. The latter happens when
1622 * something else creates the file between our two open().
1623 */
1624 }
1625
1626 return fd;
1627 }
1628
1629 static void *file_ram_alloc(RAMBlock *block,
1630 ram_addr_t memory,
1631 int fd,
1632 bool truncate,
1633 Error **errp)
1634 {
1635 void *area;
1636
1637 block->page_size = qemu_fd_getpagesize(fd);
1638 if (block->mr->align % block->page_size) {
1639 error_setg(errp, "alignment 0x%" PRIx64
1640 " must be multiples of page size 0x%zx",
1641 block->mr->align, block->page_size);
1642 return NULL;
1643 }
1644 block->mr->align = MAX(block->page_size, block->mr->align);
1645 #if defined(__s390x__)
1646 if (kvm_enabled()) {
1647 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1648 }
1649 #endif
1650
1651 if (memory < block->page_size) {
1652 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1653 "or larger than page size 0x%zx",
1654 memory, block->page_size);
1655 return NULL;
1656 }
1657
1658 memory = ROUND_UP(memory, block->page_size);
1659
1660 /*
1661 * ftruncate is not supported by hugetlbfs in older
1662 * hosts, so don't bother bailing out on errors.
1663 * If anything goes wrong with it under other filesystems,
1664 * mmap will fail.
1665 *
1666 * Do not truncate the non-empty backend file to avoid corrupting
1667 * the existing data in the file. Disabling shrinking is not
1668 * enough. For example, the current vNVDIMM implementation stores
1669 * the guest NVDIMM labels at the end of the backend file. If the
1670 * backend file is later extended, QEMU will not be able to find
1671 * those labels. Therefore, extending the non-empty backend file
1672 * is disabled as well.
1673 */
1674 if (truncate && ftruncate(fd, memory)) {
1675 perror("ftruncate");
1676 }
1677
1678 area = qemu_ram_mmap(fd, memory, block->mr->align,
1679 block->flags & RAM_SHARED);
1680 if (area == MAP_FAILED) {
1681 error_setg_errno(errp, errno,
1682 "unable to map backing store for guest RAM");
1683 return NULL;
1684 }
1685
1686 if (mem_prealloc) {
1687 os_mem_prealloc(fd, area, memory, smp_cpus, errp);
1688 if (errp && *errp) {
1689 qemu_ram_munmap(area, memory);
1690 return NULL;
1691 }
1692 }
1693
1694 block->fd = fd;
1695 return area;
1696 }
1697 #endif
1698
1699 /* Allocate space within the ram_addr_t space that governs the
1700 * dirty bitmaps.
1701 * Called with the ramlist lock held.
1702 */
1703 static ram_addr_t find_ram_offset(ram_addr_t size)
1704 {
1705 RAMBlock *block, *next_block;
1706 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1707
1708 assert(size != 0); /* it would hand out same offset multiple times */
1709
1710 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1711 return 0;
1712 }
1713
1714 RAMBLOCK_FOREACH(block) {
1715 ram_addr_t candidate, next = RAM_ADDR_MAX;
1716
1717 /* Align blocks to start on a 'long' in the bitmap
1718 * which makes the bitmap sync'ing take the fast path.
1719 */
1720 candidate = block->offset + block->max_length;
1721 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1722
1723 /* Search for the closest following block
1724 * and find the gap.
1725 */
1726 RAMBLOCK_FOREACH(next_block) {
1727 if (next_block->offset >= candidate) {
1728 next = MIN(next, next_block->offset);
1729 }
1730 }
1731
1732 /* If it fits remember our place and remember the size
1733 * of gap, but keep going so that we might find a smaller
1734 * gap to fill so avoiding fragmentation.
1735 */
1736 if (next - candidate >= size && next - candidate < mingap) {
1737 offset = candidate;
1738 mingap = next - candidate;
1739 }
1740
1741 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1742 }
1743
1744 if (offset == RAM_ADDR_MAX) {
1745 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1746 (uint64_t)size);
1747 abort();
1748 }
1749
1750 trace_find_ram_offset(size, offset);
1751
1752 return offset;
1753 }
1754
1755 unsigned long last_ram_page(void)
1756 {
1757 RAMBlock *block;
1758 ram_addr_t last = 0;
1759
1760 rcu_read_lock();
1761 RAMBLOCK_FOREACH(block) {
1762 last = MAX(last, block->offset + block->max_length);
1763 }
1764 rcu_read_unlock();
1765 return last >> TARGET_PAGE_BITS;
1766 }
1767
1768 static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1769 {
1770 int ret;
1771
1772 /* Use MADV_DONTDUMP, if user doesn't want the guest memory in the core */
1773 if (!machine_dump_guest_core(current_machine)) {
1774 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1775 if (ret) {
1776 perror("qemu_madvise");
1777 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1778 "but dump_guest_core=off specified\n");
1779 }
1780 }
1781 }
1782
1783 const char *qemu_ram_get_idstr(RAMBlock *rb)
1784 {
1785 return rb->idstr;
1786 }
1787
1788 bool qemu_ram_is_shared(RAMBlock *rb)
1789 {
1790 return rb->flags & RAM_SHARED;
1791 }
1792
1793 /* Called with iothread lock held. */
1794 void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1795 {
1796 RAMBlock *block;
1797
1798 assert(new_block);
1799 assert(!new_block->idstr[0]);
1800
1801 if (dev) {
1802 char *id = qdev_get_dev_path(dev);
1803 if (id) {
1804 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1805 g_free(id);
1806 }
1807 }
1808 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1809
1810 rcu_read_lock();
1811 RAMBLOCK_FOREACH(block) {
1812 if (block != new_block &&
1813 !strcmp(block->idstr, new_block->idstr)) {
1814 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1815 new_block->idstr);
1816 abort();
1817 }
1818 }
1819 rcu_read_unlock();
1820 }
1821
1822 /* Called with iothread lock held. */
1823 void qemu_ram_unset_idstr(RAMBlock *block)
1824 {
1825 /* FIXME: arch_init.c assumes that this is not called throughout
1826 * migration. Ignore the problem since hot-unplug during migration
1827 * does not work anyway.
1828 */
1829 if (block) {
1830 memset(block->idstr, 0, sizeof(block->idstr));
1831 }
1832 }
1833
1834 size_t qemu_ram_pagesize(RAMBlock *rb)
1835 {
1836 return rb->page_size;
1837 }
1838
1839 /* Returns the largest size of page in use */
1840 size_t qemu_ram_pagesize_largest(void)
1841 {
1842 RAMBlock *block;
1843 size_t largest = 0;
1844
1845 RAMBLOCK_FOREACH(block) {
1846 largest = MAX(largest, qemu_ram_pagesize(block));
1847 }
1848
1849 return largest;
1850 }
1851
1852 static int memory_try_enable_merging(void *addr, size_t len)
1853 {
1854 if (!machine_mem_merge(current_machine)) {
1855 /* disabled by the user */
1856 return 0;
1857 }
1858
1859 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1860 }
1861
1862 /* Only legal before guest might have detected the memory size: e.g. on
1863 * incoming migration, or right after reset.
1864 *
1865 * As memory core doesn't know how is memory accessed, it is up to
1866 * resize callback to update device state and/or add assertions to detect
1867 * misuse, if necessary.
1868 */
1869 int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1870 {
1871 assert(block);
1872
1873 newsize = HOST_PAGE_ALIGN(newsize);
1874
1875 if (block->used_length == newsize) {
1876 return 0;
1877 }
1878
1879 if (!(block->flags & RAM_RESIZEABLE)) {
1880 error_setg_errno(errp, EINVAL,
1881 "Length mismatch: %s: 0x" RAM_ADDR_FMT
1882 " in != 0x" RAM_ADDR_FMT, block->idstr,
1883 newsize, block->used_length);
1884 return -EINVAL;
1885 }
1886
1887 if (block->max_length < newsize) {
1888 error_setg_errno(errp, EINVAL,
1889 "Length too large: %s: 0x" RAM_ADDR_FMT
1890 " > 0x" RAM_ADDR_FMT, block->idstr,
1891 newsize, block->max_length);
1892 return -EINVAL;
1893 }
1894
1895 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1896 block->used_length = newsize;
1897 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1898 DIRTY_CLIENTS_ALL);
1899 memory_region_set_size(block->mr, newsize);
1900 if (block->resized) {
1901 block->resized(block->idstr, newsize, block->host);
1902 }
1903 return 0;
1904 }
1905
1906 /* Called with ram_list.mutex held */
1907 static void dirty_memory_extend(ram_addr_t old_ram_size,
1908 ram_addr_t new_ram_size)
1909 {
1910 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1911 DIRTY_MEMORY_BLOCK_SIZE);
1912 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1913 DIRTY_MEMORY_BLOCK_SIZE);
1914 int i;
1915
1916 /* Only need to extend if block count increased */
1917 if (new_num_blocks <= old_num_blocks) {
1918 return;
1919 }
1920
1921 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1922 DirtyMemoryBlocks *old_blocks;
1923 DirtyMemoryBlocks *new_blocks;
1924 int j;
1925
1926 old_blocks = atomic_rcu_read(&ram_list.dirty_memory[i]);
1927 new_blocks = g_malloc(sizeof(*new_blocks) +
1928 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1929
1930 if (old_num_blocks) {
1931 memcpy(new_blocks->blocks, old_blocks->blocks,
1932 old_num_blocks * sizeof(old_blocks->blocks[0]));
1933 }
1934
1935 for (j = old_num_blocks; j < new_num_blocks; j++) {
1936 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1937 }
1938
1939 atomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1940
1941 if (old_blocks) {
1942 g_free_rcu(old_blocks, rcu);
1943 }
1944 }
1945 }
1946
1947 static void ram_block_add(RAMBlock *new_block, Error **errp, bool shared)
1948 {
1949 RAMBlock *block;
1950 RAMBlock *last_block = NULL;
1951 ram_addr_t old_ram_size, new_ram_size;
1952 Error *err = NULL;
1953
1954 old_ram_size = last_ram_page();
1955
1956 qemu_mutex_lock_ramlist();
1957 new_block->offset = find_ram_offset(new_block->max_length);
1958
1959 if (!new_block->host) {
1960 if (xen_enabled()) {
1961 xen_ram_alloc(new_block->offset, new_block->max_length,
1962 new_block->mr, &err);
1963 if (err) {
1964 error_propagate(errp, err);
1965 qemu_mutex_unlock_ramlist();
1966 return;
1967 }
1968 } else {
1969 new_block->host = phys_mem_alloc(new_block->max_length,
1970 &new_block->mr->align, shared);
1971 if (!new_block->host) {
1972 error_setg_errno(errp, errno,
1973 "cannot set up guest memory '%s'",
1974 memory_region_name(new_block->mr));
1975 qemu_mutex_unlock_ramlist();
1976 return;
1977 }
1978 memory_try_enable_merging(new_block->host, new_block->max_length);
1979 }
1980 }
1981
1982 new_ram_size = MAX(old_ram_size,
1983 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1984 if (new_ram_size > old_ram_size) {
1985 dirty_memory_extend(old_ram_size, new_ram_size);
1986 }
1987 /* Keep the list sorted from biggest to smallest block. Unlike QTAILQ,
1988 * QLIST (which has an RCU-friendly variant) does not have insertion at
1989 * tail, so save the last element in last_block.
1990 */
1991 RAMBLOCK_FOREACH(block) {
1992 last_block = block;
1993 if (block->max_length < new_block->max_length) {
1994 break;
1995 }
1996 }
1997 if (block) {
1998 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
1999 } else if (last_block) {
2000 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
2001 } else { /* list is empty */
2002 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
2003 }
2004 ram_list.mru_block = NULL;
2005
2006 /* Write list before version */
2007 smp_wmb();
2008 ram_list.version++;
2009 qemu_mutex_unlock_ramlist();
2010
2011 cpu_physical_memory_set_dirty_range(new_block->offset,
2012 new_block->used_length,
2013 DIRTY_CLIENTS_ALL);
2014
2015 if (new_block->host) {
2016 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2017 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2018 /* MADV_DONTFORK is also needed by KVM in absence of synchronous MMU */
2019 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);
2020 ram_block_notify_add(new_block->host, new_block->max_length);
2021 }
2022 }
2023
2024 #ifdef __linux__
2025 RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2026 bool share, int fd,
2027 Error **errp)
2028 {
2029 RAMBlock *new_block;
2030 Error *local_err = NULL;
2031 int64_t file_size;
2032
2033 if (xen_enabled()) {
2034 error_setg(errp, "-mem-path not supported with Xen");
2035 return NULL;
2036 }
2037
2038 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2039 error_setg(errp,
2040 "host lacks kvm mmu notifiers, -mem-path unsupported");
2041 return NULL;
2042 }
2043
2044 if (phys_mem_alloc != qemu_anon_ram_alloc) {
2045 /*
2046 * file_ram_alloc() needs to allocate just like
2047 * phys_mem_alloc, but we haven't bothered to provide
2048 * a hook there.
2049 */
2050 error_setg(errp,
2051 "-mem-path not supported with this accelerator");
2052 return NULL;
2053 }
2054
2055 size = HOST_PAGE_ALIGN(size);
2056 file_size = get_file_size(fd);
2057 if (file_size > 0 && file_size < size) {
2058 error_setg(errp, "backing store %s size 0x%" PRIx64
2059 " does not match 'size' option 0x" RAM_ADDR_FMT,
2060 mem_path, file_size, size);
2061 return NULL;
2062 }
2063
2064 new_block = g_malloc0(sizeof(*new_block));
2065 new_block->mr = mr;
2066 new_block->used_length = size;
2067 new_block->max_length = size;
2068 new_block->flags = share ? RAM_SHARED : 0;
2069 new_block->host = file_ram_alloc(new_block, size, fd, !file_size, errp);
2070 if (!new_block->host) {
2071 g_free(new_block);
2072 return NULL;
2073 }
2074
2075 ram_block_add(new_block, &local_err, share);
2076 if (local_err) {
2077 g_free(new_block);
2078 error_propagate(errp, local_err);
2079 return NULL;
2080 }
2081 return new_block;
2082
2083 }
2084
2085
2086 RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2087 bool share, const char *mem_path,
2088 Error **errp)
2089 {
2090 int fd;
2091 bool created;
2092 RAMBlock *block;
2093
2094 fd = file_ram_open(mem_path, memory_region_name(mr), &created, errp);
2095 if (fd < 0) {
2096 return NULL;
2097 }
2098
2099 block = qemu_ram_alloc_from_fd(size, mr, share, fd, errp);
2100 if (!block) {
2101 if (created) {
2102 unlink(mem_path);
2103 }
2104 close(fd);
2105 return NULL;
2106 }
2107
2108 return block;
2109 }
2110 #endif
2111
2112 static
2113 RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2114 void (*resized)(const char*,
2115 uint64_t length,
2116 void *host),
2117 void *host, bool resizeable, bool share,
2118 MemoryRegion *mr, Error **errp)
2119 {
2120 RAMBlock *new_block;
2121 Error *local_err = NULL;
2122
2123 size = HOST_PAGE_ALIGN(size);
2124 max_size = HOST_PAGE_ALIGN(max_size);
2125 new_block = g_malloc0(sizeof(*new_block));
2126 new_block->mr = mr;
2127 new_block->resized = resized;
2128 new_block->used_length = size;
2129 new_block->max_length = max_size;
2130 assert(max_size >= size);
2131 new_block->fd = -1;
2132 new_block->page_size = getpagesize();
2133 new_block->host = host;
2134 if (host) {
2135 new_block->flags |= RAM_PREALLOC;
2136 }
2137 if (resizeable) {
2138 new_block->flags |= RAM_RESIZEABLE;
2139 }
2140 ram_block_add(new_block, &local_err, share);
2141 if (local_err) {
2142 g_free(new_block);
2143 error_propagate(errp, local_err);
2144 return NULL;
2145 }
2146 return new_block;
2147 }
2148
2149 RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2150 MemoryRegion *mr, Error **errp)
2151 {
2152 return qemu_ram_alloc_internal(size, size, NULL, host, false,
2153 false, mr, errp);
2154 }
2155
2156 RAMBlock *qemu_ram_alloc(ram_addr_t size, bool share,
2157 MemoryRegion *mr, Error **errp)
2158 {
2159 return qemu_ram_alloc_internal(size, size, NULL, NULL, false,
2160 share, mr, errp);
2161 }
2162
2163 RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2164 void (*resized)(const char*,
2165 uint64_t length,
2166 void *host),
2167 MemoryRegion *mr, Error **errp)
2168 {
2169 return qemu_ram_alloc_internal(size, maxsz, resized, NULL, true,
2170 false, mr, errp);
2171 }
2172
2173 static void reclaim_ramblock(RAMBlock *block)
2174 {
2175 if (block->flags & RAM_PREALLOC) {
2176 ;
2177 } else if (xen_enabled()) {
2178 xen_invalidate_map_cache_entry(block->host);
2179 #ifndef _WIN32
2180 } else if (block->fd >= 0) {
2181 qemu_ram_munmap(block->host, block->max_length);
2182 close(block->fd);
2183 #endif
2184 } else {
2185 qemu_anon_ram_free(block->host, block->max_length);
2186 }
2187 g_free(block);
2188 }
2189
2190 void qemu_ram_free(RAMBlock *block)
2191 {
2192 if (!block) {
2193 return;
2194 }
2195
2196 if (block->host) {
2197 ram_block_notify_remove(block->host, block->max_length);
2198 }
2199
2200 qemu_mutex_lock_ramlist();
2201 QLIST_REMOVE_RCU(block, next);
2202 ram_list.mru_block = NULL;
2203 /* Write list before version */
2204 smp_wmb();
2205 ram_list.version++;
2206 call_rcu(block, reclaim_ramblock, rcu);
2207 qemu_mutex_unlock_ramlist();
2208 }
2209
2210 #ifndef _WIN32
2211 void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2212 {
2213 RAMBlock *block;
2214 ram_addr_t offset;
2215 int flags;
2216 void *area, *vaddr;
2217
2218 RAMBLOCK_FOREACH(block) {
2219 offset = addr - block->offset;
2220 if (offset < block->max_length) {
2221 vaddr = ramblock_ptr(block, offset);
2222 if (block->flags & RAM_PREALLOC) {
2223 ;
2224 } else if (xen_enabled()) {
2225 abort();
2226 } else {
2227 flags = MAP_FIXED;
2228 if (block->fd >= 0) {
2229 flags |= (block->flags & RAM_SHARED ?
2230 MAP_SHARED : MAP_PRIVATE);
2231 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2232 flags, block->fd, offset);
2233 } else {
2234 /*
2235 * Remap needs to match alloc. Accelerators that
2236 * set phys_mem_alloc never remap. If they did,
2237 * we'd need a remap hook here.
2238 */
2239 assert(phys_mem_alloc == qemu_anon_ram_alloc);
2240
2241 flags |= MAP_PRIVATE | MAP_ANONYMOUS;
2242 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2243 flags, -1, 0);
2244 }
2245 if (area != vaddr) {
2246 error_report("Could not remap addr: "
2247 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2248 length, addr);
2249 exit(1);
2250 }
2251 memory_try_enable_merging(vaddr, length);
2252 qemu_ram_setup_dump(vaddr, length);
2253 }
2254 }
2255 }
2256 }
2257 #endif /* !_WIN32 */
2258
2259 /* Return a host pointer to ram allocated with qemu_ram_alloc.
2260 * This should not be used for general purpose DMA. Use address_space_map
2261 * or address_space_rw instead. For local memory (e.g. video ram) that the
2262 * device owns, use memory_region_get_ram_ptr.
2263 *
2264 * Called within RCU critical section.
2265 */
2266 void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2267 {
2268 RAMBlock *block = ram_block;
2269
2270 if (block == NULL) {
2271 block = qemu_get_ram_block(addr);
2272 addr -= block->offset;
2273 }
2274
2275 if (xen_enabled() && block->host == NULL) {
2276 /* We need to check if the requested address is in the RAM
2277 * because we don't want to map the entire memory in QEMU.
2278 * In that case just map until the end of the page.
2279 */
2280 if (block->offset == 0) {
2281 return xen_map_cache(addr, 0, 0, false);
2282 }
2283
2284 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2285 }
2286 return ramblock_ptr(block, addr);
2287 }
2288
2289 /* Return a host pointer to guest's ram. Similar to qemu_map_ram_ptr
2290 * but takes a size argument.
2291 *
2292 * Called within RCU critical section.
2293 */
2294 static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2295 hwaddr *size, bool lock)
2296 {
2297 RAMBlock *block = ram_block;
2298 if (*size == 0) {
2299 return NULL;
2300 }
2301
2302 if (block == NULL) {
2303 block = qemu_get_ram_block(addr);
2304 addr -= block->offset;
2305 }
2306 *size = MIN(*size, block->max_length - addr);
2307
2308 if (xen_enabled() && block->host == NULL) {
2309 /* We need to check if the requested address is in the RAM
2310 * because we don't want to map the entire memory in QEMU.
2311 * In that case just map the requested area.
2312 */
2313 if (block->offset == 0) {
2314 return xen_map_cache(addr, *size, lock, lock);
2315 }
2316
2317 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2318 }
2319
2320 return ramblock_ptr(block, addr);
2321 }
2322
2323 /*
2324 * Translates a host ptr back to a RAMBlock, a ram_addr and an offset
2325 * in that RAMBlock.
2326 *
2327 * ptr: Host pointer to look up
2328 * round_offset: If true round the result offset down to a page boundary
2329 * *ram_addr: set to result ram_addr
2330 * *offset: set to result offset within the RAMBlock
2331 *
2332 * Returns: RAMBlock (or NULL if not found)
2333 *
2334 * By the time this function returns, the returned pointer is not protected
2335 * by RCU anymore. If the caller is not within an RCU critical section and
2336 * does not hold the iothread lock, it must have other means of protecting the
2337 * pointer, such as a reference to the region that includes the incoming
2338 * ram_addr_t.
2339 */
2340 RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2341 ram_addr_t *offset)
2342 {
2343 RAMBlock *block;
2344 uint8_t *host = ptr;
2345
2346 if (xen_enabled()) {
2347 ram_addr_t ram_addr;
2348 rcu_read_lock();
2349 ram_addr = xen_ram_addr_from_mapcache(ptr);
2350 block = qemu_get_ram_block(ram_addr);
2351 if (block) {
2352 *offset = ram_addr - block->offset;
2353 }
2354 rcu_read_unlock();
2355 return block;
2356 }
2357
2358 rcu_read_lock();
2359 block = atomic_rcu_read(&ram_list.mru_block);
2360 if (block && block->host && host - block->host < block->max_length) {
2361 goto found;
2362 }
2363
2364 RAMBLOCK_FOREACH(block) {
2365 /* This case append when the block is not mapped. */
2366 if (block->host == NULL) {
2367 continue;
2368 }
2369 if (host - block->host < block->max_length) {
2370 goto found;
2371 }
2372 }
2373
2374 rcu_read_unlock();
2375 return NULL;
2376
2377 found:
2378 *offset = (host - block->host);
2379 if (round_offset) {
2380 *offset &= TARGET_PAGE_MASK;
2381 }
2382 rcu_read_unlock();
2383 return block;
2384 }
2385
2386 /*
2387 * Finds the named RAMBlock
2388 *
2389 * name: The name of RAMBlock to find
2390 *
2391 * Returns: RAMBlock (or NULL if not found)
2392 */
2393 RAMBlock *qemu_ram_block_by_name(const char *name)
2394 {
2395 RAMBlock *block;
2396
2397 RAMBLOCK_FOREACH(block) {
2398 if (!strcmp(name, block->idstr)) {
2399 return block;
2400 }
2401 }
2402
2403 return NULL;
2404 }
2405
2406 /* Some of the softmmu routines need to translate from a host pointer
2407 (typically a TLB entry) back to a ram offset. */
2408 ram_addr_t qemu_ram_addr_from_host(void *ptr)
2409 {
2410 RAMBlock *block;
2411 ram_addr_t offset;
2412
2413 block = qemu_ram_block_from_host(ptr, false, &offset);
2414 if (!block) {
2415 return RAM_ADDR_INVALID;
2416 }
2417
2418 return block->offset + offset;
2419 }
2420
2421 /* Called within RCU critical section. */
2422 void memory_notdirty_write_prepare(NotDirtyInfo *ndi,
2423 CPUState *cpu,
2424 vaddr mem_vaddr,
2425 ram_addr_t ram_addr,
2426 unsigned size)
2427 {
2428 ndi->cpu = cpu;
2429 ndi->ram_addr = ram_addr;
2430 ndi->mem_vaddr = mem_vaddr;
2431 ndi->size = size;
2432 ndi->locked = false;
2433
2434 assert(tcg_enabled());
2435 if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
2436 ndi->locked = true;
2437 tb_lock();
2438 tb_invalidate_phys_page_fast(ram_addr, size);
2439 }
2440 }
2441
2442 /* Called within RCU critical section. */
2443 void memory_notdirty_write_complete(NotDirtyInfo *ndi)
2444 {
2445 if (ndi->locked) {
2446 tb_unlock();
2447 }
2448
2449 /* Set both VGA and migration bits for simplicity and to remove
2450 * the notdirty callback faster.
2451 */
2452 cpu_physical_memory_set_dirty_range(ndi->ram_addr, ndi->size,
2453 DIRTY_CLIENTS_NOCODE);
2454 /* we remove the notdirty callback only if the code has been
2455 flushed */
2456 if (!cpu_physical_memory_is_clean(ndi->ram_addr)) {
2457 tlb_set_dirty(ndi->cpu, ndi->mem_vaddr);
2458 }
2459 }
2460
2461 /* Called within RCU critical section. */
2462 static void notdirty_mem_write(void *opaque, hwaddr ram_addr,
2463 uint64_t val, unsigned size)
2464 {
2465 NotDirtyInfo ndi;
2466
2467 memory_notdirty_write_prepare(&ndi, current_cpu, current_cpu->mem_io_vaddr,
2468 ram_addr, size);
2469
2470 switch (size) {
2471 case 1:
2472 stb_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2473 break;
2474 case 2:
2475 stw_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2476 break;
2477 case 4:
2478 stl_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2479 break;
2480 case 8:
2481 stq_p(qemu_map_ram_ptr(NULL, ram_addr), val);
2482 break;
2483 default:
2484 abort();
2485 }
2486 memory_notdirty_write_complete(&ndi);
2487 }
2488
2489 static bool notdirty_mem_accepts(void *opaque, hwaddr addr,
2490 unsigned size, bool is_write)
2491 {
2492 return is_write;
2493 }
2494
2495 static const MemoryRegionOps notdirty_mem_ops = {
2496 .write = notdirty_mem_write,
2497 .valid.accepts = notdirty_mem_accepts,
2498 .endianness = DEVICE_NATIVE_ENDIAN,
2499 .valid = {
2500 .min_access_size = 1,
2501 .max_access_size = 8,
2502 .unaligned = false,
2503 },
2504 .impl = {
2505 .min_access_size = 1,
2506 .max_access_size = 8,
2507 .unaligned = false,
2508 },
2509 };
2510
2511 /* Generate a debug exception if a watchpoint has been hit. */
2512 static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)
2513 {
2514 CPUState *cpu = current_cpu;
2515 CPUClass *cc = CPU_GET_CLASS(cpu);
2516 target_ulong vaddr;
2517 CPUWatchpoint *wp;
2518
2519 assert(tcg_enabled());
2520 if (cpu->watchpoint_hit) {
2521 /* We re-entered the check after replacing the TB. Now raise
2522 * the debug interrupt so that is will trigger after the
2523 * current instruction. */
2524 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
2525 return;
2526 }
2527 vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;
2528 vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);
2529 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
2530 if (cpu_watchpoint_address_matches(wp, vaddr, len)
2531 && (wp->flags & flags)) {
2532 if (flags == BP_MEM_READ) {
2533 wp->flags |= BP_WATCHPOINT_HIT_READ;
2534 } else {
2535 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
2536 }
2537 wp->hitaddr = vaddr;
2538 wp->hitattrs = attrs;
2539 if (!cpu->watchpoint_hit) {
2540 if (wp->flags & BP_CPU &&
2541 !cc->debug_check_watchpoint(cpu, wp)) {
2542 wp->flags &= ~BP_WATCHPOINT_HIT;
2543 continue;
2544 }
2545 cpu->watchpoint_hit = wp;
2546
2547 /* Both tb_lock and iothread_mutex will be reset when
2548 * cpu_loop_exit or cpu_loop_exit_noexc longjmp
2549 * back into the cpu_exec main loop.
2550 */
2551 tb_lock();
2552 tb_check_watchpoint(cpu);
2553 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
2554 cpu->exception_index = EXCP_DEBUG;
2555 cpu_loop_exit(cpu);
2556 } else {
2557 /* Force execution of one insn next time. */
2558 cpu->cflags_next_tb = 1 | curr_cflags();
2559 cpu_loop_exit_noexc(cpu);
2560 }
2561 }
2562 } else {
2563 wp->flags &= ~BP_WATCHPOINT_HIT;
2564 }
2565 }
2566 }
2567
2568 /* Watchpoint access routines. Watchpoints are inserted using TLB tricks,
2569 so these check for a hit then pass through to the normal out-of-line
2570 phys routines. */
2571 static MemTxResult watch_mem_read(void *opaque, hwaddr addr, uint64_t *pdata,
2572 unsigned size, MemTxAttrs attrs)
2573 {
2574 MemTxResult res;
2575 uint64_t data;
2576 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2577 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2578
2579 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_READ);
2580 switch (size) {
2581 case 1:
2582 data = address_space_ldub(as, addr, attrs, &res);
2583 break;
2584 case 2:
2585 data = address_space_lduw(as, addr, attrs, &res);
2586 break;
2587 case 4:
2588 data = address_space_ldl(as, addr, attrs, &res);
2589 break;
2590 case 8:
2591 data = address_space_ldq(as, addr, attrs, &res);
2592 break;
2593 default: abort();
2594 }
2595 *pdata = data;
2596 return res;
2597 }
2598
2599 static MemTxResult watch_mem_write(void *opaque, hwaddr addr,
2600 uint64_t val, unsigned size,
2601 MemTxAttrs attrs)
2602 {
2603 MemTxResult res;
2604 int asidx = cpu_asidx_from_attrs(current_cpu, attrs);
2605 AddressSpace *as = current_cpu->cpu_ases[asidx].as;
2606
2607 check_watchpoint(addr & ~TARGET_PAGE_MASK, size, attrs, BP_MEM_WRITE);
2608 switch (size) {
2609 case 1:
2610 address_space_stb(as, addr, val, attrs, &res);
2611 break;
2612 case 2:
2613 address_space_stw(as, addr, val, attrs, &res);
2614 break;
2615 case 4:
2616 address_space_stl(as, addr, val, attrs, &res);
2617 break;
2618 case 8:
2619 address_space_stq(as, addr, val, attrs, &res);
2620 break;
2621 default: abort();
2622 }
2623 return res;
2624 }
2625
2626 static const MemoryRegionOps watch_mem_ops = {
2627 .read_with_attrs = watch_mem_read,
2628 .write_with_attrs = watch_mem_write,
2629 .endianness = DEVICE_NATIVE_ENDIAN,
2630 .valid = {
2631 .min_access_size = 1,
2632 .max_access_size = 8,
2633 .unaligned = false,
2634 },
2635 .impl = {
2636 .min_access_size = 1,
2637 .max_access_size = 8,
2638 .unaligned = false,
2639 },
2640 };
2641
2642 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2643 MemTxAttrs attrs, uint8_t *buf, int len);
2644 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2645 const uint8_t *buf, int len);
2646 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
2647 bool is_write);
2648
2649 static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2650 unsigned len, MemTxAttrs attrs)
2651 {
2652 subpage_t *subpage = opaque;
2653 uint8_t buf[8];
2654 MemTxResult res;
2655
2656 #if defined(DEBUG_SUBPAGE)
2657 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2658 subpage, len, addr);
2659 #endif
2660 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2661 if (res) {
2662 return res;
2663 }
2664 switch (len) {
2665 case 1:
2666 *data = ldub_p(buf);
2667 return MEMTX_OK;
2668 case 2:
2669 *data = lduw_p(buf);
2670 return MEMTX_OK;
2671 case 4:
2672 *data = ldl_p(buf);
2673 return MEMTX_OK;
2674 case 8:
2675 *data = ldq_p(buf);
2676 return MEMTX_OK;
2677 default:
2678 abort();
2679 }
2680 }
2681
2682 static MemTxResult subpage_write(void *opaque, hwaddr addr,
2683 uint64_t value, unsigned len, MemTxAttrs attrs)
2684 {
2685 subpage_t *subpage = opaque;
2686 uint8_t buf[8];
2687
2688 #if defined(DEBUG_SUBPAGE)
2689 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2690 " value %"PRIx64"\n",
2691 __func__, subpage, len, addr, value);
2692 #endif
2693 switch (len) {
2694 case 1:
2695 stb_p(buf, value);
2696 break;
2697 case 2:
2698 stw_p(buf, value);
2699 break;
2700 case 4:
2701 stl_p(buf, value);
2702 break;
2703 case 8:
2704 stq_p(buf, value);
2705 break;
2706 default:
2707 abort();
2708 }
2709 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2710 }
2711
2712 static bool subpage_accepts(void *opaque, hwaddr addr,
2713 unsigned len, bool is_write)
2714 {
2715 subpage_t *subpage = opaque;
2716 #if defined(DEBUG_SUBPAGE)
2717 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2718 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2719 #endif
2720
2721 return flatview_access_valid(subpage->fv, addr + subpage->base,
2722 len, is_write);
2723 }
2724
2725 static const MemoryRegionOps subpage_ops = {
2726 .read_with_attrs = subpage_read,
2727 .write_with_attrs = subpage_write,
2728 .impl.min_access_size = 1,
2729 .impl.max_access_size = 8,
2730 .valid.min_access_size = 1,
2731 .valid.max_access_size = 8,
2732 .valid.accepts = subpage_accepts,
2733 .endianness = DEVICE_NATIVE_ENDIAN,
2734 };
2735
2736 static int subpage_register (subpage_t *mmio, uint32_t start, uint32_t end,
2737 uint16_t section)
2738 {
2739 int idx, eidx;
2740
2741 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2742 return -1;
2743 idx = SUBPAGE_IDX(start);
2744 eidx = SUBPAGE_IDX(end);
2745 #if defined(DEBUG_SUBPAGE)
2746 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2747 __func__, mmio, start, end, idx, eidx, section);
2748 #endif
2749 for (; idx <= eidx; idx++) {
2750 mmio->sub_section[idx] = section;
2751 }
2752
2753 return 0;
2754 }
2755
2756 static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2757 {
2758 subpage_t *mmio;
2759
2760 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2761 mmio->fv = fv;
2762 mmio->base = base;
2763 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2764 NULL, TARGET_PAGE_SIZE);
2765 mmio->iomem.subpage = true;
2766 #if defined(DEBUG_SUBPAGE)
2767 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2768 mmio, base, TARGET_PAGE_SIZE);
2769 #endif
2770 subpage_register(mmio, 0, TARGET_PAGE_SIZE-1, PHYS_SECTION_UNASSIGNED);
2771
2772 return mmio;
2773 }
2774
2775 static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2776 {
2777 assert(fv);
2778 MemoryRegionSection section = {
2779 .fv = fv,
2780 .mr = mr,
2781 .offset_within_address_space = 0,
2782 .offset_within_region = 0,
2783 .size = int128_2_64(),
2784 };
2785
2786 return phys_section_add(map, &section);
2787 }
2788
2789 static void readonly_mem_write(void *opaque, hwaddr addr,
2790 uint64_t val, unsigned size)
2791 {
2792 /* Ignore any write to ROM. */
2793 }
2794
2795 static bool readonly_mem_accepts(void *opaque, hwaddr addr,
2796 unsigned size, bool is_write)
2797 {
2798 return is_write;
2799 }
2800
2801 /* This will only be used for writes, because reads are special cased
2802 * to directly access the underlying host ram.
2803 */
2804 static const MemoryRegionOps readonly_mem_ops = {
2805 .write = readonly_mem_write,
2806 .valid.accepts = readonly_mem_accepts,
2807 .endianness = DEVICE_NATIVE_ENDIAN,
2808 .valid = {
2809 .min_access_size = 1,
2810 .max_access_size = 8,
2811 .unaligned = false,
2812 },
2813 .impl = {
2814 .min_access_size = 1,
2815 .max_access_size = 8,
2816 .unaligned = false,
2817 },
2818 };
2819
2820 MemoryRegion *iotlb_to_region(CPUState *cpu, hwaddr index, MemTxAttrs attrs)
2821 {
2822 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2823 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2824 AddressSpaceDispatch *d = atomic_rcu_read(&cpuas->memory_dispatch);
2825 MemoryRegionSection *sections = d->map.sections;
2826
2827 return sections[index & ~TARGET_PAGE_MASK].mr;
2828 }
2829
2830 static void io_mem_init(void)
2831 {
2832 memory_region_init_io(&io_mem_rom, NULL, &readonly_mem_ops,
2833 NULL, NULL, UINT64_MAX);
2834 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2835 NULL, UINT64_MAX);
2836
2837 /* io_mem_notdirty calls tb_invalidate_phys_page_fast,
2838 * which can be called without the iothread mutex.
2839 */
2840 memory_region_init_io(&io_mem_notdirty, NULL, &notdirty_mem_ops, NULL,
2841 NULL, UINT64_MAX);
2842 memory_region_clear_global_locking(&io_mem_notdirty);
2843
2844 memory_region_init_io(&io_mem_watch, NULL, &watch_mem_ops, NULL,
2845 NULL, UINT64_MAX);
2846 }
2847
2848 AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2849 {
2850 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2851 uint16_t n;
2852
2853 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2854 assert(n == PHYS_SECTION_UNASSIGNED);
2855 n = dummy_section(&d->map, fv, &io_mem_notdirty);
2856 assert(n == PHYS_SECTION_NOTDIRTY);
2857 n = dummy_section(&d->map, fv, &io_mem_rom);
2858 assert(n == PHYS_SECTION_ROM);
2859 n = dummy_section(&d->map, fv, &io_mem_watch);
2860 assert(n == PHYS_SECTION_WATCH);
2861
2862 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2863
2864 return d;
2865 }
2866
2867 void address_space_dispatch_free(AddressSpaceDispatch *d)
2868 {
2869 phys_sections_free(&d->map);
2870 g_free(d);
2871 }
2872
2873 static void tcg_commit(MemoryListener *listener)
2874 {
2875 CPUAddressSpace *cpuas;
2876 AddressSpaceDispatch *d;
2877
2878 /* since each CPU stores ram addresses in its TLB cache, we must
2879 reset the modified entries */
2880 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2881 cpu_reloading_memory_map();
2882 /* The CPU and TLB are protected by the iothread lock.
2883 * We reload the dispatch pointer now because cpu_reloading_memory_map()
2884 * may have split the RCU critical section.
2885 */
2886 d = address_space_to_dispatch(cpuas->as);
2887 atomic_rcu_set(&cpuas->memory_dispatch, d);
2888 tlb_flush(cpuas->cpu);
2889 }
2890
2891 static void memory_map_init(void)
2892 {
2893 system_memory = g_malloc(sizeof(*system_memory));
2894
2895 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2896 address_space_init(&address_space_memory, system_memory, "memory");
2897
2898 system_io = g_malloc(sizeof(*system_io));
2899 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2900 65536);
2901 address_space_init(&address_space_io, system_io, "I/O");
2902 }
2903
2904 MemoryRegion *get_system_memory(void)
2905 {
2906 return system_memory;
2907 }
2908
2909 MemoryRegion *get_system_io(void)
2910 {
2911 return system_io;
2912 }
2913
2914 #endif /* !defined(CONFIG_USER_ONLY) */
2915
2916 /* physical memory access (slow version, mainly for debug) */
2917 #if defined(CONFIG_USER_ONLY)
2918 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
2919 uint8_t *buf, int len, int is_write)
2920 {
2921 int l, flags;
2922 target_ulong page;
2923 void * p;
2924
2925 while (len > 0) {
2926 page = addr & TARGET_PAGE_MASK;
2927 l = (page + TARGET_PAGE_SIZE) - addr;
2928 if (l > len)
2929 l = len;
2930 flags = page_get_flags(page);
2931 if (!(flags & PAGE_VALID))
2932 return -1;
2933 if (is_write) {
2934 if (!(flags & PAGE_WRITE))
2935 return -1;
2936 /* XXX: this code should not depend on lock_user */
2937 if (!(p = lock_user(VERIFY_WRITE, addr, l, 0)))
2938 return -1;
2939 memcpy(p, buf, l);
2940 unlock_user(p, addr, l);
2941 } else {
2942 if (!(flags & PAGE_READ))
2943 return -1;
2944 /* XXX: this code should not depend on lock_user */
2945 if (!(p = lock_user(VERIFY_READ, addr, l, 1)))
2946 return -1;
2947 memcpy(buf, p, l);
2948 unlock_user(p, addr, 0);
2949 }
2950 len -= l;
2951 buf += l;
2952 addr += l;
2953 }
2954 return 0;
2955 }
2956
2957 #else
2958
2959 static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2960 hwaddr length)
2961 {
2962 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2963 addr += memory_region_get_ram_addr(mr);
2964
2965 /* No early return if dirty_log_mask is or becomes 0, because
2966 * cpu_physical_memory_set_dirty_range will still call
2967 * xen_modified_memory.
2968 */
2969 if (dirty_log_mask) {
2970 dirty_log_mask =
2971 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2972 }
2973 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2974 assert(tcg_enabled());
2975 tb_lock();
2976 tb_invalidate_phys_range(addr, addr + length);
2977 tb_unlock();
2978 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2979 }
2980 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2981 }
2982
2983 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2984 {
2985 unsigned access_size_max = mr->ops->valid.max_access_size;
2986
2987 /* Regions are assumed to support 1-4 byte accesses unless
2988 otherwise specified. */
2989 if (access_size_max == 0) {
2990 access_size_max = 4;
2991 }
2992
2993 /* Bound the maximum access by the alignment of the address. */
2994 if (!mr->ops->impl.unaligned) {
2995 unsigned align_size_max = addr & -addr;
2996 if (align_size_max != 0 && align_size_max < access_size_max) {
2997 access_size_max = align_size_max;
2998 }
2999 }
3000
3001 /* Don't attempt accesses larger than the maximum. */
3002 if (l > access_size_max) {
3003 l = access_size_max;
3004 }
3005 l = pow2floor(l);
3006
3007 return l;
3008 }
3009
3010 static bool prepare_mmio_access(MemoryRegion *mr)
3011 {
3012 bool unlocked = !qemu_mutex_iothread_locked();
3013 bool release_lock = false;
3014
3015 if (unlocked && mr->global_locking) {
3016 qemu_mutex_lock_iothread();
3017 unlocked = false;
3018 release_lock = true;
3019 }
3020 if (mr->flush_coalesced_mmio) {
3021 if (unlocked) {
3022 qemu_mutex_lock_iothread();
3023 }
3024 qemu_flush_coalesced_mmio_buffer();
3025 if (unlocked) {
3026 qemu_mutex_unlock_iothread();
3027 }
3028 }
3029
3030 return release_lock;
3031 }
3032
3033 /* Called within RCU critical section. */
3034 static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
3035 MemTxAttrs attrs,
3036 const uint8_t *buf,
3037 int len, hwaddr addr1,
3038 hwaddr l, MemoryRegion *mr)
3039 {
3040 uint8_t *ptr;
3041 uint64_t val;
3042 MemTxResult result = MEMTX_OK;
3043 bool release_lock = false;
3044
3045 for (;;) {
3046 if (!memory_access_is_direct(mr, true)) {
3047 release_lock |= prepare_mmio_access(mr);
3048 l = memory_access_size(mr, l, addr1);
3049 /* XXX: could force current_cpu to NULL to avoid
3050 potential bugs */
3051 switch (l) {
3052 case 8:
3053 /* 64 bit write access */
3054 val = ldq_p(buf);
3055 result |= memory_region_dispatch_write(mr, addr1, val, 8,
3056 attrs);
3057 break;
3058 case 4:
3059 /* 32 bit write access */
3060 val = (uint32_t)ldl_p(buf);
3061 result |= memory_region_dispatch_write(mr, addr1, val, 4,
3062 attrs);
3063 break;
3064 case 2:
3065 /* 16 bit write access */
3066 val = lduw_p(buf);
3067 result |= memory_region_dispatch_write(mr, addr1, val, 2,
3068 attrs);
3069 break;
3070 case 1:
3071 /* 8 bit write access */
3072 val = ldub_p(buf);
3073 result |= memory_region_dispatch_write(mr, addr1, val, 1,
3074 attrs);
3075 break;
3076 default:
3077 abort();
3078 }
3079 } else {
3080 /* RAM case */
3081 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3082 memcpy(ptr, buf, l);
3083 invalidate_and_set_dirty(mr, addr1, l);
3084 }
3085
3086 if (release_lock) {
3087 qemu_mutex_unlock_iothread();
3088 release_lock = false;
3089 }
3090
3091 len -= l;
3092 buf += l;
3093 addr += l;
3094
3095 if (!len) {
3096 break;
3097 }
3098
3099 l = len;
3100 mr = flatview_translate(fv, addr, &addr1, &l, true);
3101 }
3102
3103 return result;
3104 }
3105
3106 /* Called from RCU critical section. */
3107 static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
3108 const uint8_t *buf, int len)
3109 {
3110 hwaddr l;
3111 hwaddr addr1;
3112 MemoryRegion *mr;
3113 MemTxResult result = MEMTX_OK;
3114
3115 l = len;
3116 mr = flatview_translate(fv, addr, &addr1, &l, true);
3117 result = flatview_write_continue(fv, addr, attrs, buf, len,
3118 addr1, l, mr);
3119
3120 return result;
3121 }
3122
3123 /* Called within RCU critical section. */
3124 MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
3125 MemTxAttrs attrs, uint8_t *buf,
3126 int len, hwaddr addr1, hwaddr l,
3127 MemoryRegion *mr)
3128 {
3129 uint8_t *ptr;
3130 uint64_t val;
3131 MemTxResult result = MEMTX_OK;
3132 bool release_lock = false;
3133
3134 for (;;) {
3135 if (!memory_access_is_direct(mr, false)) {
3136 /* I/O case */
3137 release_lock |= prepare_mmio_access(mr);
3138 l = memory_access_size(mr, l, addr1);
3139 switch (l) {
3140 case 8:
3141 /* 64 bit read access */
3142 result |= memory_region_dispatch_read(mr, addr1, &val, 8,
3143 attrs);
3144 stq_p(buf, val);
3145 break;
3146 case 4:
3147 /* 32 bit read access */
3148 result |= memory_region_dispatch_read(mr, addr1, &val, 4,
3149 attrs);
3150 stl_p(buf, val);
3151 break;
3152 case 2:
3153 /* 16 bit read access */
3154 result |= memory_region_dispatch_read(mr, addr1, &val, 2,
3155 attrs);
3156 stw_p(buf, val);
3157 break;
3158 case 1:
3159 /* 8 bit read access */
3160 result |= memory_region_dispatch_read(mr, addr1, &val, 1,
3161 attrs);
3162 stb_p(buf, val);
3163 break;
3164 default:
3165 abort();
3166 }
3167 } else {
3168 /* RAM case */
3169 ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
3170 memcpy(buf, ptr, l);
3171 }
3172
3173 if (release_lock) {
3174 qemu_mutex_unlock_iothread();
3175 release_lock = false;
3176 }
3177
3178 len -= l;
3179 buf += l;
3180 addr += l;
3181
3182 if (!len) {
3183 break;
3184 }
3185
3186 l = len;
3187 mr = flatview_translate(fv, addr, &addr1, &l, false);
3188 }
3189
3190 return result;
3191 }
3192
3193 /* Called from RCU critical section. */
3194 static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
3195 MemTxAttrs attrs, uint8_t *buf, int len)
3196 {
3197 hwaddr l;
3198 hwaddr addr1;
3199 MemoryRegion *mr;
3200
3201 l = len;
3202 mr = flatview_translate(fv, addr, &addr1, &l, false);
3203 return flatview_read_continue(fv, addr, attrs, buf, len,
3204 addr1, l, mr);
3205 }
3206
3207 MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
3208 MemTxAttrs attrs, uint8_t *buf, int len)
3209 {
3210 MemTxResult result = MEMTX_OK;
3211 FlatView *fv;
3212
3213 if (len > 0) {
3214 rcu_read_lock();
3215 fv = address_space_to_flatview(as);
3216 result = flatview_read(fv, addr, attrs, buf, len);
3217 rcu_read_unlock();
3218 }
3219
3220 return result;
3221 }
3222
3223 MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
3224 MemTxAttrs attrs,
3225 const uint8_t *buf, int len)
3226 {
3227 MemTxResult result = MEMTX_OK;
3228 FlatView *fv;
3229
3230 if (len > 0) {
3231 rcu_read_lock();
3232 fv = address_space_to_flatview(as);
3233 result = flatview_write(fv, addr, attrs, buf, len);
3234 rcu_read_unlock();
3235 }
3236
3237 return result;
3238 }
3239
3240 MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
3241 uint8_t *buf, int len, bool is_write)
3242 {
3243 if (is_write) {
3244 return address_space_write(as, addr, attrs, buf, len);
3245 } else {
3246 return address_space_read_full(as, addr, attrs, buf, len);
3247 }
3248 }
3249
3250 void cpu_physical_memory_rw(hwaddr addr, uint8_t *buf,
3251 int len, int is_write)
3252 {
3253 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
3254 buf, len, is_write);
3255 }
3256
3257 enum write_rom_type {
3258 WRITE_DATA,
3259 FLUSH_CACHE,
3260 };
3261
3262 static inline void cpu_physical_memory_write_rom_internal(AddressSpace *as,
3263 hwaddr addr, const uint8_t *buf, int len, enum write_rom_type type)
3264 {
3265 hwaddr l;
3266 uint8_t *ptr;
3267 hwaddr addr1;
3268 MemoryRegion *mr;
3269
3270 rcu_read_lock();
3271 while (len > 0) {
3272 l = len;
3273 mr = address_space_translate(as, addr, &addr1, &l, true);
3274
3275 if (!(memory_region_is_ram(mr) ||
3276 memory_region_is_romd(mr))) {
3277 l = memory_access_size(mr, l, addr1);
3278 } else {
3279 /* ROM/RAM case */
3280 ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
3281 switch (type) {
3282 case WRITE_DATA:
3283 memcpy(ptr, buf, l);
3284 invalidate_and_set_dirty(mr, addr1, l);
3285 break;
3286 case FLUSH_CACHE:
3287 flush_icache_range((uintptr_t)ptr, (uintptr_t)ptr + l);
3288 break;
3289 }
3290 }
3291 len -= l;
3292 buf += l;
3293 addr += l;
3294 }
3295 rcu_read_unlock();
3296 }
3297
3298 /* used for ROM loading : can write in RAM and ROM */
3299 void cpu_physical_memory_write_rom(AddressSpace *as, hwaddr addr,
3300 const uint8_t *buf, int len)
3301 {
3302 cpu_physical_memory_write_rom_internal(as, addr, buf, len, WRITE_DATA);
3303 }
3304
3305 void cpu_flush_icache_range(hwaddr start, int len)
3306 {
3307 /*
3308 * This function should do the same thing as an icache flush that was
3309 * triggered from within the guest. For TCG we are always cache coherent,
3310 * so there is no need to flush anything. For KVM / Xen we need to flush
3311 * the host's instruction cache at least.
3312 */
3313 if (tcg_enabled()) {
3314 return;
3315 }
3316
3317 cpu_physical_memory_write_rom_internal(&address_space_memory,
3318 start, NULL, len, FLUSH_CACHE);
3319 }
3320
3321 typedef struct {
3322 MemoryRegion *mr;
3323 void *buffer;
3324 hwaddr addr;
3325 hwaddr len;
3326 bool in_use;
3327 } BounceBuffer;
3328
3329 static BounceBuffer bounce;
3330
3331 typedef struct MapClient {
3332 QEMUBH *bh;
3333 QLIST_ENTRY(MapClient) link;
3334 } MapClient;
3335
3336 QemuMutex map_client_list_lock;
3337 static QLIST_HEAD(map_client_list, MapClient) map_client_list
3338 = QLIST_HEAD_INITIALIZER(map_client_list);
3339
3340 static void cpu_unregister_map_client_do(MapClient *client)
3341 {
3342 QLIST_REMOVE(client, link);
3343 g_free(client);
3344 }
3345
3346 static void cpu_notify_map_clients_locked(void)
3347 {
3348 MapClient *client;
3349
3350 while (!QLIST_EMPTY(&map_client_list)) {
3351 client = QLIST_FIRST(&map_client_list);
3352 qemu_bh_schedule(client->bh);
3353 cpu_unregister_map_client_do(client);
3354 }
3355 }
3356
3357 void cpu_register_map_client(QEMUBH *bh)
3358 {
3359 MapClient *client = g_malloc(sizeof(*client));
3360
3361 qemu_mutex_lock(&map_client_list_lock);
3362 client->bh = bh;
3363 QLIST_INSERT_HEAD(&map_client_list, client, link);
3364 if (!atomic_read(&bounce.in_use)) {
3365 cpu_notify_map_clients_locked();
3366 }
3367 qemu_mutex_unlock(&map_client_list_lock);
3368 }
3369
3370 void cpu_exec_init_all(void)
3371 {
3372 qemu_mutex_init(&ram_list.mutex);
3373 /* The data structures we set up here depend on knowing the page size,
3374 * so no more changes can be made after this point.
3375 * In an ideal world, nothing we did before we had finished the
3376 * machine setup would care about the target page size, and we could
3377 * do this much later, rather than requiring board models to state
3378 * up front what their requirements are.
3379 */
3380 finalize_target_page_bits();
3381 io_mem_init();
3382 memory_map_init();
3383 qemu_mutex_init(&map_client_list_lock);
3384 }
3385
3386 void cpu_unregister_map_client(QEMUBH *bh)
3387 {
3388 MapClient *client;
3389
3390 qemu_mutex_lock(&map_client_list_lock);
3391 QLIST_FOREACH(client, &map_client_list, link) {
3392 if (client->bh == bh) {
3393 cpu_unregister_map_client_do(client);
3394 break;
3395 }
3396 }
3397 qemu_mutex_unlock(&map_client_list_lock);
3398 }
3399
3400 static void cpu_notify_map_clients(void)
3401 {
3402 qemu_mutex_lock(&map_client_list_lock);
3403 cpu_notify_map_clients_locked();
3404 qemu_mutex_unlock(&map_client_list_lock);
3405 }
3406
3407 static bool flatview_access_valid(FlatView *fv, hwaddr addr, int len,
3408 bool is_write)
3409 {
3410 MemoryRegion *mr;
3411 hwaddr l, xlat;
3412
3413 while (len > 0) {
3414 l = len;
3415 mr = flatview_translate(fv, addr, &xlat, &l, is_write);
3416 if (!memory_access_is_direct(mr, is_write)) {
3417 l = memory_access_size(mr, l, addr);
3418 if (!memory_region_access_valid(mr, xlat, l, is_write)) {
3419 return false;
3420 }
3421 }
3422
3423 len -= l;
3424 addr += l;
3425 }
3426 return true;
3427 }
3428
3429 bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3430 int len, bool is_write)
3431 {
3432 FlatView *fv;
3433 bool result;
3434
3435 rcu_read_lock();
3436 fv = address_space_to_flatview(as);
3437 result = flatview_access_valid(fv, addr, len, is_write);
3438 rcu_read_unlock();
3439 return result;
3440 }
3441
3442 static hwaddr
3443 flatview_extend_translation(FlatView *fv, hwaddr addr,
3444 hwaddr target_len,
3445 MemoryRegion *mr, hwaddr base, hwaddr len,
3446 bool is_write)
3447 {
3448 hwaddr done = 0;
3449 hwaddr xlat;
3450 MemoryRegion *this_mr;
3451
3452 for (;;) {
3453 target_len -= len;
3454 addr += len;
3455 done += len;
3456 if (target_len == 0) {
3457 return done;
3458 }
3459
3460 len = target_len;
3461 this_mr = flatview_translate(fv, addr, &xlat,
3462 &len, is_write);
3463 if (this_mr != mr || xlat != base + done) {
3464 return done;
3465 }
3466 }
3467 }
3468
3469 /* Map a physical memory region into a host virtual address.
3470 * May map a subset of the requested range, given by and returned in *plen.
3471 * May return NULL if resources needed to perform the mapping are exhausted.
3472 * Use only for reads OR writes - not for read-modify-write operations.
3473 * Use cpu_register_map_client() to know when retrying the map operation is
3474 * likely to succeed.
3475 */
3476 void *address_space_map(AddressSpace *as,
3477 hwaddr addr,
3478 hwaddr *plen,
3479 bool is_write)
3480 {
3481 hwaddr len = *plen;
3482 hwaddr l, xlat;
3483 MemoryRegion *mr;
3484 void *ptr;
3485 FlatView *fv;
3486
3487 if (len == 0) {
3488 return NULL;
3489 }
3490
3491 l = len;
3492 rcu_read_lock();
3493 fv = address_space_to_flatview(as);
3494 mr = flatview_translate(fv, addr, &xlat, &l, is_write);
3495
3496 if (!memory_access_is_direct(mr, is_write)) {
3497 if (atomic_xchg(&bounce.in_use, true)) {
3498 rcu_read_unlock();
3499 return NULL;
3500 }
3501 /* Avoid unbounded allocations */
3502 l = MIN(l, TARGET_PAGE_SIZE);
3503 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3504 bounce.addr = addr;
3505 bounce.len = l;
3506
3507 memory_region_ref(mr);
3508 bounce.mr = mr;
3509 if (!is_write) {
3510 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3511 bounce.buffer, l);
3512 }
3513
3514 rcu_read_unlock();
3515 *plen = l;
3516 return bounce.buffer;
3517 }
3518
3519
3520 memory_region_ref(mr);
3521 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3522 l, is_write);
3523 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3524 rcu_read_unlock();
3525
3526 return ptr;
3527 }
3528
3529 /* Unmaps a memory region previously mapped by address_space_map().
3530 * Will also mark the memory as dirty if is_write == 1. access_len gives
3531 * the amount of memory that was actually read or written by the caller.
3532 */
3533 void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3534 int is_write, hwaddr access_len)
3535 {
3536 if (buffer != bounce.buffer) {
3537 MemoryRegion *mr;
3538 ram_addr_t addr1;
3539
3540 mr = memory_region_from_host(buffer, &addr1);
3541 assert(mr != NULL);
3542 if (is_write) {
3543 invalidate_and_set_dirty(mr, addr1, access_len);
3544 }
3545 if (xen_enabled()) {
3546 xen_invalidate_map_cache_entry(buffer);
3547 }
3548 memory_region_unref(mr);
3549 return;
3550 }
3551 if (is_write) {
3552 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3553 bounce.buffer, access_len);
3554 }
3555 qemu_vfree(bounce.buffer);
3556 bounce.buffer = NULL;
3557 memory_region_unref(bounce.mr);
3558 atomic_mb_set(&bounce.in_use, false);
3559 cpu_notify_map_clients();
3560 }
3561
3562 void *cpu_physical_memory_map(hwaddr addr,
3563 hwaddr *plen,
3564 int is_write)
3565 {
3566 return address_space_map(&address_space_memory, addr, plen, is_write);
3567 }
3568
3569 void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3570 int is_write, hwaddr access_len)
3571 {
3572 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3573 }
3574
3575 #define ARG1_DECL AddressSpace *as
3576 #define ARG1 as
3577 #define SUFFIX
3578 #define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3579 #define IS_DIRECT(mr, is_write) memory_access_is_direct(mr, is_write)
3580 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3581 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3582 #define RCU_READ_LOCK(...) rcu_read_lock()
3583 #define RCU_READ_UNLOCK(...) rcu_read_unlock()
3584 #include "memory_ldst.inc.c"
3585
3586 int64_t address_space_cache_init(MemoryRegionCache *cache,
3587 AddressSpace *as,
3588 hwaddr addr,
3589 hwaddr len,
3590 bool is_write)
3591 {
3592 cache->len = len;
3593 cache->as = as;
3594 cache->xlat = addr;
3595 return len;
3596 }
3597
3598 void address_space_cache_invalidate(MemoryRegionCache *cache,
3599 hwaddr addr,
3600 hwaddr access_len)
3601 {
3602 }
3603
3604 void address_space_cache_destroy(MemoryRegionCache *cache)
3605 {
3606 cache->as = NULL;
3607 }
3608
3609 #define ARG1_DECL MemoryRegionCache *cache
3610 #define ARG1 cache
3611 #define SUFFIX _cached
3612 #define TRANSLATE(addr, ...) \
3613 address_space_translate(cache->as, cache->xlat + (addr), __VA_ARGS__)
3614 #define IS_DIRECT(mr, is_write) true
3615 #define MAP_RAM(mr, ofs) qemu_map_ram_ptr((mr)->ram_block, ofs)
3616 #define INVALIDATE(mr, ofs, len) invalidate_and_set_dirty(mr, ofs, len)
3617 #define RCU_READ_LOCK() rcu_read_lock()
3618 #define RCU_READ_UNLOCK() rcu_read_unlock()
3619 #include "memory_ldst.inc.c"
3620
3621 /* virtual memory access for debug (includes writing to ROM) */
3622 int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3623 uint8_t *buf, int len, int is_write)
3624 {
3625 int l;
3626 hwaddr phys_addr;
3627 target_ulong page;
3628
3629 cpu_synchronize_state(cpu);
3630 while (len > 0) {
3631 int asidx;
3632 MemTxAttrs attrs;
3633
3634 page = addr & TARGET_PAGE_MASK;
3635 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3636 asidx = cpu_asidx_from_attrs(cpu, attrs);
3637 /* if no physical page mapped, return an error */
3638 if (phys_addr == -1)
3639 return -1;
3640 l = (page + TARGET_PAGE_SIZE) - addr;
3641 if (l > len)
3642 l = len;
3643 phys_addr += (addr & ~TARGET_PAGE_MASK);
3644 if (is_write) {
3645 cpu_physical_memory_write_rom(cpu->cpu_ases[asidx].as,
3646 phys_addr, buf, l);
3647 } else {
3648 address_space_rw(cpu->cpu_ases[asidx].as, phys_addr,
3649 MEMTXATTRS_UNSPECIFIED,
3650 buf, l, 0);
3651 }
3652 len -= l;
3653 buf += l;
3654 addr += l;
3655 }
3656 return 0;
3657 }
3658
3659 /*
3660 * Allows code that needs to deal with migration bitmaps etc to still be built
3661 * target independent.
3662 */
3663 size_t qemu_target_page_size(void)
3664 {
3665 return TARGET_PAGE_SIZE;
3666 }
3667
3668 int qemu_target_page_bits(void)
3669 {
3670 return TARGET_PAGE_BITS;
3671 }
3672
3673 int qemu_target_page_bits_min(void)
3674 {
3675 return TARGET_PAGE_BITS_MIN;
3676 }
3677 #endif
3678
3679 /*
3680 * A helper function for the _utterly broken_ virtio device model to find out if
3681 * it's running on a big endian machine. Don't do this at home kids!
3682 */
3683 bool target_words_bigendian(void);
3684 bool target_words_bigendian(void)
3685 {
3686 #if defined(TARGET_WORDS_BIGENDIAN)
3687 return true;
3688 #else
3689 return false;
3690 #endif
3691 }
3692
3693 #ifndef CONFIG_USER_ONLY
3694 bool cpu_physical_memory_is_io(hwaddr phys_addr)
3695 {
3696 MemoryRegion*mr;
3697 hwaddr l = 1;
3698 bool res;
3699
3700 rcu_read_lock();
3701 mr = address_space_translate(&address_space_memory,
3702 phys_addr, &phys_addr, &l, false);
3703
3704 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3705 rcu_read_unlock();
3706 return res;
3707 }
3708
3709 int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3710 {
3711 RAMBlock *block;
3712 int ret = 0;
3713
3714 rcu_read_lock();
3715 RAMBLOCK_FOREACH(block) {
3716 ret = func(block->idstr, block->host, block->offset,
3717 block->used_length, opaque);
3718 if (ret) {
3719 break;
3720 }
3721 }
3722 rcu_read_unlock();
3723 return ret;
3724 }
3725
3726 /*
3727 * Unmap pages of memory from start to start+length such that
3728 * they a) read as 0, b) Trigger whatever fault mechanism
3729 * the OS provides for postcopy.
3730 * The pages must be unmapped by the end of the function.
3731 * Returns: 0 on success, none-0 on failure
3732 *
3733 */
3734 int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3735 {
3736 int ret = -1;
3737
3738 uint8_t *host_startaddr = rb->host + start;
3739
3740 if ((uintptr_t)host_startaddr & (rb->page_size - 1)) {
3741 error_report("ram_block_discard_range: Unaligned start address: %p",
3742 host_startaddr);
3743 goto err;
3744 }
3745
3746 if ((start + length) <= rb->used_length) {
3747 uint8_t *host_endaddr = host_startaddr + length;
3748 if ((uintptr_t)host_endaddr & (rb->page_size - 1)) {
3749 error_report("ram_block_discard_range: Unaligned end address: %p",
3750 host_endaddr);
3751 goto err;
3752 }
3753
3754 errno = ENOTSUP; /* If we are missing MADVISE etc */
3755
3756 if (rb->page_size == qemu_host_page_size) {
3757 #if defined(CONFIG_MADVISE)
3758 /* Note: We need the madvise MADV_DONTNEED behaviour of definitely
3759 * freeing the page.
3760 */
3761 ret = madvise(host_startaddr, length, MADV_DONTNEED);
3762 #endif
3763 } else {
3764 /* Huge page case - unfortunately it can't do DONTNEED, but
3765 * it can do the equivalent by FALLOC_FL_PUNCH_HOLE in the
3766 * huge page file.
3767 */
3768 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3769 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3770 start, length);
3771 #endif
3772 }
3773 if (ret) {
3774 ret = -errno;
3775 error_report("ram_block_discard_range: Failed to discard range "
3776 "%s:%" PRIx64 " +%zx (%d)",
3777 rb->idstr, start, length, ret);
3778 }
3779 } else {
3780 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3781 "/%zx/" RAM_ADDR_FMT")",
3782 rb->idstr, start, length, rb->used_length);
3783 }
3784
3785 err:
3786 return ret;
3787 }
3788
3789 #endif
3790
3791 void page_size_init(void)
3792 {
3793 /* NOTE: we can always suppose that qemu_host_page_size >=
3794 TARGET_PAGE_SIZE */
3795 if (qemu_host_page_size == 0) {
3796 qemu_host_page_size = qemu_real_host_page_size;
3797 }
3798 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
3799 qemu_host_page_size = TARGET_PAGE_SIZE;
3800 }
3801 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;
3802 }
3803
3804 #if !defined(CONFIG_USER_ONLY)
3805
3806 static void mtree_print_phys_entries(fprintf_function mon, void *f,
3807 int start, int end, int skip, int ptr)
3808 {
3809 if (start == end - 1) {
3810 mon(f, "\t%3d ", start);
3811 } else {
3812 mon(f, "\t%3d..%-3d ", start, end - 1);
3813 }
3814 mon(f, " skip=%d ", skip);
3815 if (ptr == PHYS_MAP_NODE_NIL) {
3816 mon(f, " ptr=NIL");
3817 } else if (!skip) {
3818 mon(f, " ptr=#%d", ptr);
3819 } else {
3820 mon(f, " ptr=[%d]", ptr);
3821 }
3822 mon(f, "\n");
3823 }
3824
3825 #define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3826 int128_sub((size), int128_one())) : 0)
3827
3828 void mtree_print_dispatch(fprintf_function mon, void *f,
3829 AddressSpaceDispatch *d, MemoryRegion *root)
3830 {
3831 int i;
3832
3833 mon(f, " Dispatch\n");
3834 mon(f, " Physical sections\n");
3835
3836 for (i = 0; i < d->map.sections_nb; ++i) {
3837 MemoryRegionSection *s = d->map.sections + i;
3838 const char *names[] = { " [unassigned]", " [not dirty]",
3839 " [ROM]", " [watch]" };
3840
3841 mon(f, " #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx " %s%s%s%s%s",
3842 i,
3843 s->offset_within_address_space,
3844 s->offset_within_address_space + MR_SIZE(s->mr->size),
3845 s->mr->name ? s->mr->name : "(noname)",
3846 i < ARRAY_SIZE(names) ? names[i] : "",
3847 s->mr == root ? " [ROOT]" : "",
3848 s == d->mru_section ? " [MRU]" : "",
3849 s->mr->is_iommu ? " [iommu]" : "");
3850
3851 if (s->mr->alias) {
3852 mon(f, " alias=%s", s->mr->alias->name ?
3853 s->mr->alias->name : "noname");
3854 }
3855 mon(f, "\n");
3856 }
3857
3858 mon(f, " Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3859 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3860 for (i = 0; i < d->map.nodes_nb; ++i) {
3861 int j, jprev;
3862 PhysPageEntry prev;
3863 Node *n = d->map.nodes + i;
3864
3865 mon(f, " [%d]\n", i);
3866
3867 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3868 PhysPageEntry *pe = *n + j;
3869
3870 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3871 continue;
3872 }
3873
3874 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
3875
3876 jprev = j;
3877 prev = *pe;
3878 }
3879
3880 if (jprev != ARRAY_SIZE(*n)) {
3881 mtree_print_phys_entries(mon, f, jprev, j, prev.skip, prev.ptr);
3882 }
3883 }
3884 }
3885
3886 #endif