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