1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20#include "qemu/osdep.h"
21#include "qemu-common.h"
22#include "qapi/error.h"
23
24#include "qemu/cutils.h"
25#include "qemu/cacheflush.h"
26
27#ifdef CONFIG_TCG
28#include "hw/core/tcg-cpu-ops.h"
29#endif
30
31#include "exec/exec-all.h"
32#include "exec/target_page.h"
33#include "hw/qdev-core.h"
34#include "hw/qdev-properties.h"
35#include "hw/boards.h"
36#include "hw/xen/xen.h"
37#include "sysemu/kvm.h"
38#include "sysemu/tcg.h"
39#include "sysemu/qtest.h"
40#include "qemu/timer.h"
41#include "qemu/config-file.h"
42#include "qemu/error-report.h"
43#include "qemu/qemu-print.h"
44#include "exec/memory.h"
45#include "exec/ioport.h"
46#include "sysemu/dma.h"
47#include "sysemu/hostmem.h"
48#include "sysemu/hw_accel.h"
49#include "sysemu/xen-mapcache.h"
50#include "trace/trace-root.h"
51
52#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
53#include <linux/falloc.h>
54#endif
55
56#include "qemu/rcu_queue.h"
57#include "qemu/main-loop.h"
58#include "exec/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 "qemu/pmem.h"
66
67#include "migration/vmstate.h"
68
69#include "qemu/range.h"
70#ifndef _WIN32
71#include "qemu/mmap-alloc.h"
72#endif
73
74#include "monitor/monitor.h"
75
76#ifdef CONFIG_LIBDAXCTL
77#include <daxctl/libdaxctl.h>
78#endif
79
80
81
82
83
84
85RAMList ram_list = { .blocks = QLIST_HEAD_INITIALIZER(ram_list.blocks) };
86
87static MemoryRegion *system_memory;
88static MemoryRegion *system_io;
89
90AddressSpace address_space_io;
91AddressSpace address_space_memory;
92
93static MemoryRegion io_mem_unassigned;
94
95typedef struct PhysPageEntry PhysPageEntry;
96
97struct PhysPageEntry {
98
99 uint32_t skip : 6;
100
101 uint32_t ptr : 26;
102};
103
104#define PHYS_MAP_NODE_NIL (((uint32_t)~0) >> 6)
105
106
107#define ADDR_SPACE_BITS 64
108
109#define P_L2_BITS 9
110#define P_L2_SIZE (1 << P_L2_BITS)
111
112#define P_L2_LEVELS (((ADDR_SPACE_BITS - TARGET_PAGE_BITS - 1) / P_L2_BITS) + 1)
113
114typedef PhysPageEntry Node[P_L2_SIZE];
115
116typedef struct PhysPageMap {
117 struct rcu_head rcu;
118
119 unsigned sections_nb;
120 unsigned sections_nb_alloc;
121 unsigned nodes_nb;
122 unsigned nodes_nb_alloc;
123 Node *nodes;
124 MemoryRegionSection *sections;
125} PhysPageMap;
126
127struct AddressSpaceDispatch {
128 MemoryRegionSection *mru_section;
129
130
131
132 PhysPageEntry phys_map;
133 PhysPageMap map;
134};
135
136#define SUBPAGE_IDX(addr) ((addr) & ~TARGET_PAGE_MASK)
137typedef struct subpage_t {
138 MemoryRegion iomem;
139 FlatView *fv;
140 hwaddr base;
141 uint16_t sub_section[];
142} subpage_t;
143
144#define PHYS_SECTION_UNASSIGNED 0
145
146static void io_mem_init(void);
147static void memory_map_init(void);
148static void tcg_log_global_after_sync(MemoryListener *listener);
149static void tcg_commit(MemoryListener *listener);
150
151
152
153
154
155
156
157
158struct CPUAddressSpace {
159 CPUState *cpu;
160 AddressSpace *as;
161 struct AddressSpaceDispatch *memory_dispatch;
162 MemoryListener tcg_as_listener;
163};
164
165struct DirtyBitmapSnapshot {
166 ram_addr_t start;
167 ram_addr_t end;
168 unsigned long dirty[];
169};
170
171static void phys_map_node_reserve(PhysPageMap *map, unsigned nodes)
172{
173 static unsigned alloc_hint = 16;
174 if (map->nodes_nb + nodes > map->nodes_nb_alloc) {
175 map->nodes_nb_alloc = MAX(alloc_hint, map->nodes_nb + nodes);
176 map->nodes = g_renew(Node, map->nodes, map->nodes_nb_alloc);
177 alloc_hint = map->nodes_nb_alloc;
178 }
179}
180
181static uint32_t phys_map_node_alloc(PhysPageMap *map, bool leaf)
182{
183 unsigned i;
184 uint32_t ret;
185 PhysPageEntry e;
186 PhysPageEntry *p;
187
188 ret = map->nodes_nb++;
189 p = map->nodes[ret];
190 assert(ret != PHYS_MAP_NODE_NIL);
191 assert(ret != map->nodes_nb_alloc);
192
193 e.skip = leaf ? 0 : 1;
194 e.ptr = leaf ? PHYS_SECTION_UNASSIGNED : PHYS_MAP_NODE_NIL;
195 for (i = 0; i < P_L2_SIZE; ++i) {
196 memcpy(&p[i], &e, sizeof(e));
197 }
198 return ret;
199}
200
201static void phys_page_set_level(PhysPageMap *map, PhysPageEntry *lp,
202 hwaddr *index, uint64_t *nb, uint16_t leaf,
203 int level)
204{
205 PhysPageEntry *p;
206 hwaddr step = (hwaddr)1 << (level * P_L2_BITS);
207
208 if (lp->skip && lp->ptr == PHYS_MAP_NODE_NIL) {
209 lp->ptr = phys_map_node_alloc(map, level == 0);
210 }
211 p = map->nodes[lp->ptr];
212 lp = &p[(*index >> (level * P_L2_BITS)) & (P_L2_SIZE - 1)];
213
214 while (*nb && lp < &p[P_L2_SIZE]) {
215 if ((*index & (step - 1)) == 0 && *nb >= step) {
216 lp->skip = 0;
217 lp->ptr = leaf;
218 *index += step;
219 *nb -= step;
220 } else {
221 phys_page_set_level(map, lp, index, nb, leaf, level - 1);
222 }
223 ++lp;
224 }
225}
226
227static void phys_page_set(AddressSpaceDispatch *d,
228 hwaddr index, uint64_t nb,
229 uint16_t leaf)
230{
231
232 phys_map_node_reserve(&d->map, 3 * P_L2_LEVELS);
233
234 phys_page_set_level(&d->map, &d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);
235}
236
237
238
239
240static void phys_page_compact(PhysPageEntry *lp, Node *nodes)
241{
242 unsigned valid_ptr = P_L2_SIZE;
243 int valid = 0;
244 PhysPageEntry *p;
245 int i;
246
247 if (lp->ptr == PHYS_MAP_NODE_NIL) {
248 return;
249 }
250
251 p = nodes[lp->ptr];
252 for (i = 0; i < P_L2_SIZE; i++) {
253 if (p[i].ptr == PHYS_MAP_NODE_NIL) {
254 continue;
255 }
256
257 valid_ptr = i;
258 valid++;
259 if (p[i].skip) {
260 phys_page_compact(&p[i], nodes);
261 }
262 }
263
264
265 if (valid != 1) {
266 return;
267 }
268
269 assert(valid_ptr < P_L2_SIZE);
270
271
272 if (P_L2_LEVELS >= (1 << 6) &&
273 lp->skip + p[valid_ptr].skip >= (1 << 6)) {
274 return;
275 }
276
277 lp->ptr = p[valid_ptr].ptr;
278 if (!p[valid_ptr].skip) {
279
280
281
282
283
284
285 lp->skip = 0;
286 } else {
287 lp->skip += p[valid_ptr].skip;
288 }
289}
290
291void address_space_dispatch_compact(AddressSpaceDispatch *d)
292{
293 if (d->phys_map.skip) {
294 phys_page_compact(&d->phys_map, d->map.nodes);
295 }
296}
297
298static inline bool section_covers_addr(const MemoryRegionSection *section,
299 hwaddr addr)
300{
301
302
303
304 return int128_gethi(section->size) ||
305 range_covers_byte(section->offset_within_address_space,
306 int128_getlo(section->size), addr);
307}
308
309static MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr addr)
310{
311 PhysPageEntry lp = d->phys_map, *p;
312 Node *nodes = d->map.nodes;
313 MemoryRegionSection *sections = d->map.sections;
314 hwaddr index = addr >> TARGET_PAGE_BITS;
315 int i;
316
317 for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {
318 if (lp.ptr == PHYS_MAP_NODE_NIL) {
319 return §ions[PHYS_SECTION_UNASSIGNED];
320 }
321 p = nodes[lp.ptr];
322 lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];
323 }
324
325 if (section_covers_addr(§ions[lp.ptr], addr)) {
326 return §ions[lp.ptr];
327 } else {
328 return §ions[PHYS_SECTION_UNASSIGNED];
329 }
330}
331
332
333static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,
334 hwaddr addr,
335 bool resolve_subpage)
336{
337 MemoryRegionSection *section = qatomic_read(&d->mru_section);
338 subpage_t *subpage;
339
340 if (!section || section == &d->map.sections[PHYS_SECTION_UNASSIGNED] ||
341 !section_covers_addr(section, addr)) {
342 section = phys_page_find(d, addr);
343 qatomic_set(&d->mru_section, section);
344 }
345 if (resolve_subpage && section->mr->subpage) {
346 subpage = container_of(section->mr, subpage_t, iomem);
347 section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];
348 }
349 return section;
350}
351
352
353static MemoryRegionSection *
354address_space_translate_internal(AddressSpaceDispatch *d, hwaddr addr, hwaddr *xlat,
355 hwaddr *plen, bool resolve_subpage)
356{
357 MemoryRegionSection *section;
358 MemoryRegion *mr;
359 Int128 diff;
360
361 section = address_space_lookup_region(d, addr, resolve_subpage);
362
363 addr -= section->offset_within_address_space;
364
365
366 *xlat = addr + section->offset_within_region;
367
368 mr = section->mr;
369
370
371
372
373
374
375
376
377
378
379
380
381 if (memory_region_is_ram(mr)) {
382 diff = int128_sub(section->size, int128_make64(addr));
383 *plen = int128_get64(int128_min(diff, int128_make64(*plen)));
384 }
385 return section;
386}
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410static MemoryRegionSection address_space_translate_iommu(IOMMUMemoryRegion *iommu_mr,
411 hwaddr *xlat,
412 hwaddr *plen_out,
413 hwaddr *page_mask_out,
414 bool is_write,
415 bool is_mmio,
416 AddressSpace **target_as,
417 MemTxAttrs attrs)
418{
419 MemoryRegionSection *section;
420 hwaddr page_mask = (hwaddr)-1;
421
422 do {
423 hwaddr addr = *xlat;
424 IOMMUMemoryRegionClass *imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
425 int iommu_idx = 0;
426 IOMMUTLBEntry iotlb;
427
428 if (imrc->attrs_to_index) {
429 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
430 }
431
432 iotlb = imrc->translate(iommu_mr, addr, is_write ?
433 IOMMU_WO : IOMMU_RO, iommu_idx);
434
435 if (!(iotlb.perm & (1 << is_write))) {
436 goto unassigned;
437 }
438
439 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
440 | (addr & iotlb.addr_mask));
441 page_mask &= iotlb.addr_mask;
442 *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
443 *target_as = iotlb.target_as;
444
445 section = address_space_translate_internal(
446 address_space_to_dispatch(iotlb.target_as), addr, xlat,
447 plen_out, is_mmio);
448
449 iommu_mr = memory_region_get_iommu(section->mr);
450 } while (unlikely(iommu_mr));
451
452 if (page_mask_out) {
453 *page_mask_out = page_mask;
454 }
455 return *section;
456
457unassigned:
458 return (MemoryRegionSection) { .mr = &io_mem_unassigned };
459}
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481static MemoryRegionSection flatview_do_translate(FlatView *fv,
482 hwaddr addr,
483 hwaddr *xlat,
484 hwaddr *plen_out,
485 hwaddr *page_mask_out,
486 bool is_write,
487 bool is_mmio,
488 AddressSpace **target_as,
489 MemTxAttrs attrs)
490{
491 MemoryRegionSection *section;
492 IOMMUMemoryRegion *iommu_mr;
493 hwaddr plen = (hwaddr)(-1);
494
495 if (!plen_out) {
496 plen_out = &plen;
497 }
498
499 section = address_space_translate_internal(
500 flatview_to_dispatch(fv), addr, xlat,
501 plen_out, is_mmio);
502
503 iommu_mr = memory_region_get_iommu(section->mr);
504 if (unlikely(iommu_mr)) {
505 return address_space_translate_iommu(iommu_mr, xlat,
506 plen_out, page_mask_out,
507 is_write, is_mmio,
508 target_as, attrs);
509 }
510 if (page_mask_out) {
511
512 *page_mask_out = ~TARGET_PAGE_MASK;
513 }
514
515 return *section;
516}
517
518
519IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
520 bool is_write, MemTxAttrs attrs)
521{
522 MemoryRegionSection section;
523 hwaddr xlat, page_mask;
524
525
526
527
528
529 section = flatview_do_translate(address_space_to_flatview(as), addr, &xlat,
530 NULL, &page_mask, is_write, false, &as,
531 attrs);
532
533
534 if (section.mr == &io_mem_unassigned) {
535 goto iotlb_fail;
536 }
537
538
539 xlat += section.offset_within_address_space -
540 section.offset_within_region;
541
542 return (IOMMUTLBEntry) {
543 .target_as = as,
544 .iova = addr & ~page_mask,
545 .translated_addr = xlat & ~page_mask,
546 .addr_mask = page_mask,
547
548 .perm = IOMMU_RW,
549 };
550
551iotlb_fail:
552 return (IOMMUTLBEntry) {0};
553}
554
555
556MemoryRegion *flatview_translate(FlatView *fv, hwaddr addr, hwaddr *xlat,
557 hwaddr *plen, bool is_write,
558 MemTxAttrs attrs)
559{
560 MemoryRegion *mr;
561 MemoryRegionSection section;
562 AddressSpace *as = NULL;
563
564
565 section = flatview_do_translate(fv, addr, xlat, plen, NULL,
566 is_write, true, &as, attrs);
567 mr = section.mr;
568
569 if (xen_enabled() && memory_access_is_direct(mr, is_write)) {
570 hwaddr page = ((addr & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE) - addr;
571 *plen = MIN(page, *plen);
572 }
573
574 return mr;
575}
576
577typedef struct TCGIOMMUNotifier {
578 IOMMUNotifier n;
579 MemoryRegion *mr;
580 CPUState *cpu;
581 int iommu_idx;
582 bool active;
583} TCGIOMMUNotifier;
584
585static void tcg_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
586{
587 TCGIOMMUNotifier *notifier = container_of(n, TCGIOMMUNotifier, n);
588
589 if (!notifier->active) {
590 return;
591 }
592 tlb_flush(notifier->cpu);
593 notifier->active = false;
594
595
596
597
598
599}
600
601static void tcg_register_iommu_notifier(CPUState *cpu,
602 IOMMUMemoryRegion *iommu_mr,
603 int iommu_idx)
604{
605
606
607
608
609 MemoryRegion *mr = MEMORY_REGION(iommu_mr);
610 TCGIOMMUNotifier *notifier = NULL;
611 int i;
612
613 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
614 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
615 if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
616 break;
617 }
618 }
619 if (i == cpu->iommu_notifiers->len) {
620
621 cpu->iommu_notifiers = g_array_set_size(cpu->iommu_notifiers, i + 1);
622 notifier = g_new0(TCGIOMMUNotifier, 1);
623 g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i) = notifier;
624
625 notifier->mr = mr;
626 notifier->iommu_idx = iommu_idx;
627 notifier->cpu = cpu;
628
629
630
631
632
633
634 iommu_notifier_init(¬ifier->n,
635 tcg_iommu_unmap_notify,
636 IOMMU_NOTIFIER_UNMAP,
637 0,
638 HWADDR_MAX,
639 iommu_idx);
640 memory_region_register_iommu_notifier(notifier->mr, ¬ifier->n,
641 &error_fatal);
642 }
643
644 if (!notifier->active) {
645 notifier->active = true;
646 }
647}
648
649void tcg_iommu_free_notifier_list(CPUState *cpu)
650{
651
652 int i;
653 TCGIOMMUNotifier *notifier;
654
655 for (i = 0; i < cpu->iommu_notifiers->len; i++) {
656 notifier = g_array_index(cpu->iommu_notifiers, TCGIOMMUNotifier *, i);
657 memory_region_unregister_iommu_notifier(notifier->mr, ¬ifier->n);
658 g_free(notifier);
659 }
660 g_array_free(cpu->iommu_notifiers, true);
661}
662
663void tcg_iommu_init_notifier_list(CPUState *cpu)
664{
665 cpu->iommu_notifiers = g_array_new(false, true, sizeof(TCGIOMMUNotifier *));
666}
667
668
669MemoryRegionSection *
670address_space_translate_for_iotlb(CPUState *cpu, int asidx, hwaddr addr,
671 hwaddr *xlat, hwaddr *plen,
672 MemTxAttrs attrs, int *prot)
673{
674 MemoryRegionSection *section;
675 IOMMUMemoryRegion *iommu_mr;
676 IOMMUMemoryRegionClass *imrc;
677 IOMMUTLBEntry iotlb;
678 int iommu_idx;
679 AddressSpaceDispatch *d =
680 qatomic_rcu_read(&cpu->cpu_ases[asidx].memory_dispatch);
681
682 for (;;) {
683 section = address_space_translate_internal(d, addr, &addr, plen, false);
684
685 iommu_mr = memory_region_get_iommu(section->mr);
686 if (!iommu_mr) {
687 break;
688 }
689
690 imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
691
692 iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
693 tcg_register_iommu_notifier(cpu, iommu_mr, iommu_idx);
694
695
696
697 iotlb = imrc->translate(iommu_mr, addr, IOMMU_NONE, iommu_idx);
698 addr = ((iotlb.translated_addr & ~iotlb.addr_mask)
699 | (addr & iotlb.addr_mask));
700
701
702
703
704 if (!(iotlb.perm & IOMMU_RO)) {
705 *prot &= ~(PAGE_READ | PAGE_EXEC);
706 }
707 if (!(iotlb.perm & IOMMU_WO)) {
708 *prot &= ~PAGE_WRITE;
709 }
710
711 if (!*prot) {
712 goto translate_fail;
713 }
714
715 d = flatview_to_dispatch(address_space_to_flatview(iotlb.target_as));
716 }
717
718 assert(!memory_region_is_iommu(section->mr));
719 *xlat = addr;
720 return section;
721
722translate_fail:
723 return &d->map.sections[PHYS_SECTION_UNASSIGNED];
724}
725
726void cpu_address_space_init(CPUState *cpu, int asidx,
727 const char *prefix, MemoryRegion *mr)
728{
729 CPUAddressSpace *newas;
730 AddressSpace *as = g_new0(AddressSpace, 1);
731 char *as_name;
732
733 assert(mr);
734 as_name = g_strdup_printf("%s-%d", prefix, cpu->cpu_index);
735 address_space_init(as, mr, as_name);
736 g_free(as_name);
737
738
739 assert(asidx < cpu->num_ases);
740
741 if (asidx == 0) {
742
743 cpu->as = as;
744 }
745
746
747 assert(asidx == 0 || !kvm_enabled());
748
749 if (!cpu->cpu_ases) {
750 cpu->cpu_ases = g_new0(CPUAddressSpace, cpu->num_ases);
751 }
752
753 newas = &cpu->cpu_ases[asidx];
754 newas->cpu = cpu;
755 newas->as = as;
756 if (tcg_enabled()) {
757 newas->tcg_as_listener.log_global_after_sync = tcg_log_global_after_sync;
758 newas->tcg_as_listener.commit = tcg_commit;
759 memory_listener_register(&newas->tcg_as_listener, as);
760 }
761}
762
763AddressSpace *cpu_get_address_space(CPUState *cpu, int asidx)
764{
765
766 return cpu->cpu_ases[asidx].as;
767}
768
769
770int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,
771 int flags, CPUWatchpoint **watchpoint)
772{
773 CPUWatchpoint *wp;
774 vaddr in_page;
775
776
777 if (len == 0 || (addr + len - 1) < addr) {
778 error_report("tried to set invalid watchpoint at %"
779 VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);
780 return -EINVAL;
781 }
782 wp = g_malloc(sizeof(*wp));
783
784 wp->vaddr = addr;
785 wp->len = len;
786 wp->flags = flags;
787
788
789 if (flags & BP_GDB) {
790 QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);
791 } else {
792 QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);
793 }
794
795 in_page = -(addr | TARGET_PAGE_MASK);
796 if (len <= in_page) {
797 tlb_flush_page(cpu, addr);
798 } else {
799 tlb_flush(cpu);
800 }
801
802 if (watchpoint)
803 *watchpoint = wp;
804 return 0;
805}
806
807
808int cpu_watchpoint_remove(CPUState *cpu, vaddr addr, vaddr len,
809 int flags)
810{
811 CPUWatchpoint *wp;
812
813 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
814 if (addr == wp->vaddr && len == wp->len
815 && flags == (wp->flags & ~BP_WATCHPOINT_HIT)) {
816 cpu_watchpoint_remove_by_ref(cpu, wp);
817 return 0;
818 }
819 }
820 return -ENOENT;
821}
822
823
824void cpu_watchpoint_remove_by_ref(CPUState *cpu, CPUWatchpoint *watchpoint)
825{
826 QTAILQ_REMOVE(&cpu->watchpoints, watchpoint, entry);
827
828 tlb_flush_page(cpu, watchpoint->vaddr);
829
830 g_free(watchpoint);
831}
832
833
834void cpu_watchpoint_remove_all(CPUState *cpu, int mask)
835{
836 CPUWatchpoint *wp, *next;
837
838 QTAILQ_FOREACH_SAFE(wp, &cpu->watchpoints, entry, next) {
839 if (wp->flags & mask) {
840 cpu_watchpoint_remove_by_ref(cpu, wp);
841 }
842 }
843}
844
845#ifdef CONFIG_TCG
846
847
848
849
850
851static inline bool watchpoint_address_matches(CPUWatchpoint *wp,
852 vaddr addr, vaddr len)
853{
854
855
856
857
858
859 vaddr wpend = wp->vaddr + wp->len - 1;
860 vaddr addrend = addr + len - 1;
861
862 return !(addr > wpend || wp->vaddr > addrend);
863}
864
865
866int cpu_watchpoint_address_matches(CPUState *cpu, vaddr addr, vaddr len)
867{
868 CPUWatchpoint *wp;
869 int ret = 0;
870
871 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
872 if (watchpoint_address_matches(wp, addr, len)) {
873 ret |= wp->flags;
874 }
875 }
876 return ret;
877}
878
879
880void cpu_check_watchpoint(CPUState *cpu, vaddr addr, vaddr len,
881 MemTxAttrs attrs, int flags, uintptr_t ra)
882{
883 CPUClass *cc = CPU_GET_CLASS(cpu);
884 CPUWatchpoint *wp;
885
886 assert(tcg_enabled());
887 if (cpu->watchpoint_hit) {
888
889
890
891
892
893 qemu_mutex_lock_iothread();
894 cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);
895 qemu_mutex_unlock_iothread();
896 return;
897 }
898
899 if (cc->tcg_ops->adjust_watchpoint_address) {
900
901 addr = cc->tcg_ops->adjust_watchpoint_address(cpu, addr, len);
902 }
903 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
904 if (watchpoint_address_matches(wp, addr, len)
905 && (wp->flags & flags)) {
906 if (replay_running_debug()) {
907
908
909
910
911
912 if (!cpu->can_do_io) {
913
914 cpu->cflags_next_tb = 1 | CF_LAST_IO | curr_cflags(cpu);
915 cpu_loop_exit_restore(cpu, ra);
916 }
917
918
919
920
921 replay_breakpoint();
922 return;
923 }
924 if (flags == BP_MEM_READ) {
925 wp->flags |= BP_WATCHPOINT_HIT_READ;
926 } else {
927 wp->flags |= BP_WATCHPOINT_HIT_WRITE;
928 }
929 wp->hitaddr = MAX(addr, wp->vaddr);
930 wp->hitattrs = attrs;
931 if (!cpu->watchpoint_hit) {
932 if (wp->flags & BP_CPU && cc->tcg_ops->debug_check_watchpoint &&
933 !cc->tcg_ops->debug_check_watchpoint(cpu, wp)) {
934 wp->flags &= ~BP_WATCHPOINT_HIT;
935 continue;
936 }
937 cpu->watchpoint_hit = wp;
938
939 mmap_lock();
940 tb_check_watchpoint(cpu, ra);
941 if (wp->flags & BP_STOP_BEFORE_ACCESS) {
942 cpu->exception_index = EXCP_DEBUG;
943 mmap_unlock();
944 cpu_loop_exit_restore(cpu, ra);
945 } else {
946
947 cpu->cflags_next_tb = 1 | curr_cflags(cpu);
948 mmap_unlock();
949 if (ra) {
950 cpu_restore_state(cpu, ra, true);
951 }
952 cpu_loop_exit_noexc(cpu);
953 }
954 }
955 } else {
956 wp->flags &= ~BP_WATCHPOINT_HIT;
957 }
958 }
959}
960
961#endif
962
963
964static RAMBlock *qemu_get_ram_block(ram_addr_t addr)
965{
966 RAMBlock *block;
967
968 block = qatomic_rcu_read(&ram_list.mru_block);
969 if (block && addr - block->offset < block->max_length) {
970 return block;
971 }
972 RAMBLOCK_FOREACH(block) {
973 if (addr - block->offset < block->max_length) {
974 goto found;
975 }
976 }
977
978 fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);
979 abort();
980
981found:
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998 ram_list.mru_block = block;
999 return block;
1000}
1001
1002static void tlb_reset_dirty_range_all(ram_addr_t start, ram_addr_t length)
1003{
1004 CPUState *cpu;
1005 ram_addr_t start1;
1006 RAMBlock *block;
1007 ram_addr_t end;
1008
1009 assert(tcg_enabled());
1010 end = TARGET_PAGE_ALIGN(start + length);
1011 start &= TARGET_PAGE_MASK;
1012
1013 RCU_READ_LOCK_GUARD();
1014 block = qemu_get_ram_block(start);
1015 assert(block == qemu_get_ram_block(end - 1));
1016 start1 = (uintptr_t)ramblock_ptr(block, start - block->offset);
1017 CPU_FOREACH(cpu) {
1018 tlb_reset_dirty(cpu, start1, length);
1019 }
1020}
1021
1022
1023bool cpu_physical_memory_test_and_clear_dirty(ram_addr_t start,
1024 ram_addr_t length,
1025 unsigned client)
1026{
1027 DirtyMemoryBlocks *blocks;
1028 unsigned long end, page, start_page;
1029 bool dirty = false;
1030 RAMBlock *ramblock;
1031 uint64_t mr_offset, mr_size;
1032
1033 if (length == 0) {
1034 return false;
1035 }
1036
1037 end = TARGET_PAGE_ALIGN(start + length) >> TARGET_PAGE_BITS;
1038 start_page = start >> TARGET_PAGE_BITS;
1039 page = start_page;
1040
1041 WITH_RCU_READ_LOCK_GUARD() {
1042 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1043 ramblock = qemu_get_ram_block(start);
1044
1045 assert(start >= ramblock->offset &&
1046 start + length <= ramblock->offset + ramblock->used_length);
1047
1048 while (page < end) {
1049 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1050 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1051 unsigned long num = MIN(end - page,
1052 DIRTY_MEMORY_BLOCK_SIZE - offset);
1053
1054 dirty |= bitmap_test_and_clear_atomic(blocks->blocks[idx],
1055 offset, num);
1056 page += num;
1057 }
1058
1059 mr_offset = (ram_addr_t)(start_page << TARGET_PAGE_BITS) - ramblock->offset;
1060 mr_size = (end - start_page) << TARGET_PAGE_BITS;
1061 memory_region_clear_dirty_bitmap(ramblock->mr, mr_offset, mr_size);
1062 }
1063
1064 if (dirty && tcg_enabled()) {
1065 tlb_reset_dirty_range_all(start, length);
1066 }
1067
1068 return dirty;
1069}
1070
1071DirtyBitmapSnapshot *cpu_physical_memory_snapshot_and_clear_dirty
1072 (MemoryRegion *mr, hwaddr offset, hwaddr length, unsigned client)
1073{
1074 DirtyMemoryBlocks *blocks;
1075 ram_addr_t start = memory_region_get_ram_addr(mr) + offset;
1076 unsigned long align = 1UL << (TARGET_PAGE_BITS + BITS_PER_LEVEL);
1077 ram_addr_t first = QEMU_ALIGN_DOWN(start, align);
1078 ram_addr_t last = QEMU_ALIGN_UP(start + length, align);
1079 DirtyBitmapSnapshot *snap;
1080 unsigned long page, end, dest;
1081
1082 snap = g_malloc0(sizeof(*snap) +
1083 ((last - first) >> (TARGET_PAGE_BITS + 3)));
1084 snap->start = first;
1085 snap->end = last;
1086
1087 page = first >> TARGET_PAGE_BITS;
1088 end = last >> TARGET_PAGE_BITS;
1089 dest = 0;
1090
1091 WITH_RCU_READ_LOCK_GUARD() {
1092 blocks = qatomic_rcu_read(&ram_list.dirty_memory[client]);
1093
1094 while (page < end) {
1095 unsigned long idx = page / DIRTY_MEMORY_BLOCK_SIZE;
1096 unsigned long offset = page % DIRTY_MEMORY_BLOCK_SIZE;
1097 unsigned long num = MIN(end - page,
1098 DIRTY_MEMORY_BLOCK_SIZE - offset);
1099
1100 assert(QEMU_IS_ALIGNED(offset, (1 << BITS_PER_LEVEL)));
1101 assert(QEMU_IS_ALIGNED(num, (1 << BITS_PER_LEVEL)));
1102 offset >>= BITS_PER_LEVEL;
1103
1104 bitmap_copy_and_clear_atomic(snap->dirty + dest,
1105 blocks->blocks[idx] + offset,
1106 num);
1107 page += num;
1108 dest += num >> BITS_PER_LEVEL;
1109 }
1110 }
1111
1112 if (tcg_enabled()) {
1113 tlb_reset_dirty_range_all(start, length);
1114 }
1115
1116 memory_region_clear_dirty_bitmap(mr, offset, length);
1117
1118 return snap;
1119}
1120
1121bool cpu_physical_memory_snapshot_get_dirty(DirtyBitmapSnapshot *snap,
1122 ram_addr_t start,
1123 ram_addr_t length)
1124{
1125 unsigned long page, end;
1126
1127 assert(start >= snap->start);
1128 assert(start + length <= snap->end);
1129
1130 end = TARGET_PAGE_ALIGN(start + length - snap->start) >> TARGET_PAGE_BITS;
1131 page = (start - snap->start) >> TARGET_PAGE_BITS;
1132
1133 while (page < end) {
1134 if (test_bit(page, snap->dirty)) {
1135 return true;
1136 }
1137 page++;
1138 }
1139 return false;
1140}
1141
1142
1143hwaddr memory_region_section_get_iotlb(CPUState *cpu,
1144 MemoryRegionSection *section)
1145{
1146 AddressSpaceDispatch *d = flatview_to_dispatch(section->fv);
1147 return section - d->map.sections;
1148}
1149
1150static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
1151 uint16_t section);
1152static subpage_t *subpage_init(FlatView *fv, hwaddr base);
1153
1154static uint16_t phys_section_add(PhysPageMap *map,
1155 MemoryRegionSection *section)
1156{
1157
1158
1159
1160
1161 assert(map->sections_nb < TARGET_PAGE_SIZE);
1162
1163 if (map->sections_nb == map->sections_nb_alloc) {
1164 map->sections_nb_alloc = MAX(map->sections_nb_alloc * 2, 16);
1165 map->sections = g_renew(MemoryRegionSection, map->sections,
1166 map->sections_nb_alloc);
1167 }
1168 map->sections[map->sections_nb] = *section;
1169 memory_region_ref(section->mr);
1170 return map->sections_nb++;
1171}
1172
1173static void phys_section_destroy(MemoryRegion *mr)
1174{
1175 bool have_sub_page = mr->subpage;
1176
1177 memory_region_unref(mr);
1178
1179 if (have_sub_page) {
1180 subpage_t *subpage = container_of(mr, subpage_t, iomem);
1181 object_unref(OBJECT(&subpage->iomem));
1182 g_free(subpage);
1183 }
1184}
1185
1186static void phys_sections_free(PhysPageMap *map)
1187{
1188 while (map->sections_nb > 0) {
1189 MemoryRegionSection *section = &map->sections[--map->sections_nb];
1190 phys_section_destroy(section->mr);
1191 }
1192 g_free(map->sections);
1193 g_free(map->nodes);
1194}
1195
1196static void register_subpage(FlatView *fv, MemoryRegionSection *section)
1197{
1198 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1199 subpage_t *subpage;
1200 hwaddr base = section->offset_within_address_space
1201 & TARGET_PAGE_MASK;
1202 MemoryRegionSection *existing = phys_page_find(d, base);
1203 MemoryRegionSection subsection = {
1204 .offset_within_address_space = base,
1205 .size = int128_make64(TARGET_PAGE_SIZE),
1206 };
1207 hwaddr start, end;
1208
1209 assert(existing->mr->subpage || existing->mr == &io_mem_unassigned);
1210
1211 if (!(existing->mr->subpage)) {
1212 subpage = subpage_init(fv, base);
1213 subsection.fv = fv;
1214 subsection.mr = &subpage->iomem;
1215 phys_page_set(d, base >> TARGET_PAGE_BITS, 1,
1216 phys_section_add(&d->map, &subsection));
1217 } else {
1218 subpage = container_of(existing->mr, subpage_t, iomem);
1219 }
1220 start = section->offset_within_address_space & ~TARGET_PAGE_MASK;
1221 end = start + int128_get64(section->size) - 1;
1222 subpage_register(subpage, start, end,
1223 phys_section_add(&d->map, section));
1224}
1225
1226
1227static void register_multipage(FlatView *fv,
1228 MemoryRegionSection *section)
1229{
1230 AddressSpaceDispatch *d = flatview_to_dispatch(fv);
1231 hwaddr start_addr = section->offset_within_address_space;
1232 uint16_t section_index = phys_section_add(&d->map, section);
1233 uint64_t num_pages = int128_get64(int128_rshift(section->size,
1234 TARGET_PAGE_BITS));
1235
1236 assert(num_pages);
1237 phys_page_set(d, start_addr >> TARGET_PAGE_BITS, num_pages, section_index);
1238}
1239
1240
1241
1242
1243
1244
1245
1246
1247void flatview_add_to_dispatch(FlatView *fv, MemoryRegionSection *section)
1248{
1249 MemoryRegionSection remain = *section;
1250 Int128 page_size = int128_make64(TARGET_PAGE_SIZE);
1251
1252
1253 if (remain.offset_within_address_space & ~TARGET_PAGE_MASK) {
1254 uint64_t left = TARGET_PAGE_ALIGN(remain.offset_within_address_space)
1255 - remain.offset_within_address_space;
1256
1257 MemoryRegionSection now = remain;
1258 now.size = int128_min(int128_make64(left), now.size);
1259 register_subpage(fv, &now);
1260 if (int128_eq(remain.size, now.size)) {
1261 return;
1262 }
1263 remain.size = int128_sub(remain.size, now.size);
1264 remain.offset_within_address_space += int128_get64(now.size);
1265 remain.offset_within_region += int128_get64(now.size);
1266 }
1267
1268
1269 if (int128_ge(remain.size, page_size)) {
1270 MemoryRegionSection now = remain;
1271 now.size = int128_and(now.size, int128_neg(page_size));
1272 register_multipage(fv, &now);
1273 if (int128_eq(remain.size, now.size)) {
1274 return;
1275 }
1276 remain.size = int128_sub(remain.size, now.size);
1277 remain.offset_within_address_space += int128_get64(now.size);
1278 remain.offset_within_region += int128_get64(now.size);
1279 }
1280
1281
1282 register_subpage(fv, &remain);
1283}
1284
1285void qemu_flush_coalesced_mmio_buffer(void)
1286{
1287 if (kvm_enabled())
1288 kvm_flush_coalesced_mmio_buffer();
1289}
1290
1291void qemu_mutex_lock_ramlist(void)
1292{
1293 qemu_mutex_lock(&ram_list.mutex);
1294}
1295
1296void qemu_mutex_unlock_ramlist(void)
1297{
1298 qemu_mutex_unlock(&ram_list.mutex);
1299}
1300
1301void ram_block_dump(Monitor *mon)
1302{
1303 RAMBlock *block;
1304 char *psize;
1305
1306 RCU_READ_LOCK_GUARD();
1307 monitor_printf(mon, "%24s %8s %18s %18s %18s\n",
1308 "Block Name", "PSize", "Offset", "Used", "Total");
1309 RAMBLOCK_FOREACH(block) {
1310 psize = size_to_str(block->page_size);
1311 monitor_printf(mon, "%24s %8s 0x%016" PRIx64 " 0x%016" PRIx64
1312 " 0x%016" PRIx64 "\n", block->idstr, psize,
1313 (uint64_t)block->offset,
1314 (uint64_t)block->used_length,
1315 (uint64_t)block->max_length);
1316 g_free(psize);
1317 }
1318}
1319
1320#ifdef __linux__
1321
1322
1323
1324
1325
1326
1327static int find_min_backend_pagesize(Object *obj, void *opaque)
1328{
1329 long *hpsize_min = opaque;
1330
1331 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1332 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1333 long hpsize = host_memory_backend_pagesize(backend);
1334
1335 if (host_memory_backend_is_mapped(backend) && (hpsize < *hpsize_min)) {
1336 *hpsize_min = hpsize;
1337 }
1338 }
1339
1340 return 0;
1341}
1342
1343static int find_max_backend_pagesize(Object *obj, void *opaque)
1344{
1345 long *hpsize_max = opaque;
1346
1347 if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {
1348 HostMemoryBackend *backend = MEMORY_BACKEND(obj);
1349 long hpsize = host_memory_backend_pagesize(backend);
1350
1351 if (host_memory_backend_is_mapped(backend) && (hpsize > *hpsize_max)) {
1352 *hpsize_max = hpsize;
1353 }
1354 }
1355
1356 return 0;
1357}
1358
1359
1360
1361
1362
1363long qemu_minrampagesize(void)
1364{
1365 long hpsize = LONG_MAX;
1366 Object *memdev_root = object_resolve_path("/objects", NULL);
1367
1368 object_child_foreach(memdev_root, find_min_backend_pagesize, &hpsize);
1369 return hpsize;
1370}
1371
1372long qemu_maxrampagesize(void)
1373{
1374 long pagesize = 0;
1375 Object *memdev_root = object_resolve_path("/objects", NULL);
1376
1377 object_child_foreach(memdev_root, find_max_backend_pagesize, &pagesize);
1378 return pagesize;
1379}
1380#else
1381long qemu_minrampagesize(void)
1382{
1383 return qemu_real_host_page_size;
1384}
1385long qemu_maxrampagesize(void)
1386{
1387 return qemu_real_host_page_size;
1388}
1389#endif
1390
1391#ifdef CONFIG_POSIX
1392static int64_t get_file_size(int fd)
1393{
1394 int64_t size;
1395#if defined(__linux__)
1396 struct stat st;
1397
1398 if (fstat(fd, &st) < 0) {
1399 return -errno;
1400 }
1401
1402
1403 if (S_ISCHR(st.st_mode)) {
1404 g_autofree char *subsystem_path = NULL;
1405 g_autofree char *subsystem = NULL;
1406
1407 subsystem_path = g_strdup_printf("/sys/dev/char/%d:%d/subsystem",
1408 major(st.st_rdev), minor(st.st_rdev));
1409 subsystem = g_file_read_link(subsystem_path, NULL);
1410
1411 if (subsystem && g_str_has_suffix(subsystem, "/dax")) {
1412 g_autofree char *size_path = NULL;
1413 g_autofree char *size_str = NULL;
1414
1415 size_path = g_strdup_printf("/sys/dev/char/%d:%d/size",
1416 major(st.st_rdev), minor(st.st_rdev));
1417
1418 if (g_file_get_contents(size_path, &size_str, NULL, NULL)) {
1419 return g_ascii_strtoll(size_str, NULL, 0);
1420 }
1421 }
1422 }
1423#endif
1424
1425
1426 size = lseek(fd, 0, SEEK_END);
1427 if (size < 0) {
1428 return -errno;
1429 }
1430 return size;
1431}
1432
1433static int64_t get_file_align(int fd)
1434{
1435 int64_t align = -1;
1436#if defined(__linux__) && defined(CONFIG_LIBDAXCTL)
1437 struct stat st;
1438
1439 if (fstat(fd, &st) < 0) {
1440 return -errno;
1441 }
1442
1443
1444 if (S_ISCHR(st.st_mode)) {
1445 g_autofree char *path = NULL;
1446 g_autofree char *rpath = NULL;
1447 struct daxctl_ctx *ctx;
1448 struct daxctl_region *region;
1449 int rc = 0;
1450
1451 path = g_strdup_printf("/sys/dev/char/%d:%d",
1452 major(st.st_rdev), minor(st.st_rdev));
1453 rpath = realpath(path, NULL);
1454
1455 rc = daxctl_new(&ctx);
1456 if (rc) {
1457 return -1;
1458 }
1459
1460 daxctl_region_foreach(ctx, region) {
1461 if (strstr(rpath, daxctl_region_get_path(region))) {
1462 align = daxctl_region_get_align(region);
1463 break;
1464 }
1465 }
1466 daxctl_unref(ctx);
1467 }
1468#endif
1469
1470 return align;
1471}
1472
1473static int file_ram_open(const char *path,
1474 const char *region_name,
1475 bool readonly,
1476 bool *created,
1477 Error **errp)
1478{
1479 char *filename;
1480 char *sanitized_name;
1481 char *c;
1482 int fd = -1;
1483
1484 *created = false;
1485 for (;;) {
1486 fd = open(path, readonly ? O_RDONLY : O_RDWR);
1487 if (fd >= 0) {
1488
1489 break;
1490 }
1491 if (errno == ENOENT) {
1492
1493 fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);
1494 if (fd >= 0) {
1495 *created = true;
1496 break;
1497 }
1498 } else if (errno == EISDIR) {
1499
1500
1501 sanitized_name = g_strdup(region_name);
1502 for (c = sanitized_name; *c != '\0'; c++) {
1503 if (*c == '/') {
1504 *c = '_';
1505 }
1506 }
1507
1508 filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,
1509 sanitized_name);
1510 g_free(sanitized_name);
1511
1512 fd = mkstemp(filename);
1513 if (fd >= 0) {
1514 unlink(filename);
1515 g_free(filename);
1516 break;
1517 }
1518 g_free(filename);
1519 }
1520 if (errno != EEXIST && errno != EINTR) {
1521 error_setg_errno(errp, errno,
1522 "can't open backing store %s for guest RAM",
1523 path);
1524 return -1;
1525 }
1526
1527
1528
1529
1530 }
1531
1532 return fd;
1533}
1534
1535static void *file_ram_alloc(RAMBlock *block,
1536 ram_addr_t memory,
1537 int fd,
1538 bool readonly,
1539 bool truncate,
1540 off_t offset,
1541 Error **errp)
1542{
1543 uint32_t qemu_map_flags;
1544 void *area;
1545
1546 block->page_size = qemu_fd_getpagesize(fd);
1547 if (block->mr->align % block->page_size) {
1548 error_setg(errp, "alignment 0x%" PRIx64
1549 " must be multiples of page size 0x%zx",
1550 block->mr->align, block->page_size);
1551 return NULL;
1552 } else if (block->mr->align && !is_power_of_2(block->mr->align)) {
1553 error_setg(errp, "alignment 0x%" PRIx64
1554 " must be a power of two", block->mr->align);
1555 return NULL;
1556 }
1557 block->mr->align = MAX(block->page_size, block->mr->align);
1558#if defined(__s390x__)
1559 if (kvm_enabled()) {
1560 block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);
1561 }
1562#endif
1563
1564 if (memory < block->page_size) {
1565 error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "
1566 "or larger than page size 0x%zx",
1567 memory, block->page_size);
1568 return NULL;
1569 }
1570
1571 memory = ROUND_UP(memory, block->page_size);
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587 if (truncate && ftruncate(fd, memory)) {
1588 perror("ftruncate");
1589 }
1590
1591 qemu_map_flags = readonly ? QEMU_MAP_READONLY : 0;
1592 qemu_map_flags |= (block->flags & RAM_SHARED) ? QEMU_MAP_SHARED : 0;
1593 qemu_map_flags |= (block->flags & RAM_PMEM) ? QEMU_MAP_SYNC : 0;
1594 qemu_map_flags |= (block->flags & RAM_NORESERVE) ? QEMU_MAP_NORESERVE : 0;
1595 area = qemu_ram_mmap(fd, memory, block->mr->align, qemu_map_flags, offset);
1596 if (area == MAP_FAILED) {
1597 error_setg_errno(errp, errno,
1598 "unable to map backing store for guest RAM");
1599 return NULL;
1600 }
1601
1602 block->fd = fd;
1603 return area;
1604}
1605#endif
1606
1607
1608
1609
1610
1611static ram_addr_t find_ram_offset(ram_addr_t size)
1612{
1613 RAMBlock *block, *next_block;
1614 ram_addr_t offset = RAM_ADDR_MAX, mingap = RAM_ADDR_MAX;
1615
1616 assert(size != 0);
1617
1618 if (QLIST_EMPTY_RCU(&ram_list.blocks)) {
1619 return 0;
1620 }
1621
1622 RAMBLOCK_FOREACH(block) {
1623 ram_addr_t candidate, next = RAM_ADDR_MAX;
1624
1625
1626
1627
1628 candidate = block->offset + block->max_length;
1629 candidate = ROUND_UP(candidate, BITS_PER_LONG << TARGET_PAGE_BITS);
1630
1631
1632
1633
1634 RAMBLOCK_FOREACH(next_block) {
1635 if (next_block->offset >= candidate) {
1636 next = MIN(next, next_block->offset);
1637 }
1638 }
1639
1640
1641
1642
1643
1644 if (next - candidate >= size && next - candidate < mingap) {
1645 offset = candidate;
1646 mingap = next - candidate;
1647 }
1648
1649 trace_find_ram_offset_loop(size, candidate, offset, next, mingap);
1650 }
1651
1652 if (offset == RAM_ADDR_MAX) {
1653 fprintf(stderr, "Failed to find gap of requested size: %" PRIu64 "\n",
1654 (uint64_t)size);
1655 abort();
1656 }
1657
1658 trace_find_ram_offset(size, offset);
1659
1660 return offset;
1661}
1662
1663static unsigned long last_ram_page(void)
1664{
1665 RAMBlock *block;
1666 ram_addr_t last = 0;
1667
1668 RCU_READ_LOCK_GUARD();
1669 RAMBLOCK_FOREACH(block) {
1670 last = MAX(last, block->offset + block->max_length);
1671 }
1672 return last >> TARGET_PAGE_BITS;
1673}
1674
1675static void qemu_ram_setup_dump(void *addr, ram_addr_t size)
1676{
1677 int ret;
1678
1679
1680 if (!machine_dump_guest_core(current_machine)) {
1681 ret = qemu_madvise(addr, size, QEMU_MADV_DONTDUMP);
1682 if (ret) {
1683 perror("qemu_madvise");
1684 fprintf(stderr, "madvise doesn't support MADV_DONTDUMP, "
1685 "but dump_guest_core=off specified\n");
1686 }
1687 }
1688}
1689
1690const char *qemu_ram_get_idstr(RAMBlock *rb)
1691{
1692 return rb->idstr;
1693}
1694
1695void *qemu_ram_get_host_addr(RAMBlock *rb)
1696{
1697 return rb->host;
1698}
1699
1700ram_addr_t qemu_ram_get_offset(RAMBlock *rb)
1701{
1702 return rb->offset;
1703}
1704
1705ram_addr_t qemu_ram_get_used_length(RAMBlock *rb)
1706{
1707 return rb->used_length;
1708}
1709
1710ram_addr_t qemu_ram_get_max_length(RAMBlock *rb)
1711{
1712 return rb->max_length;
1713}
1714
1715bool qemu_ram_is_shared(RAMBlock *rb)
1716{
1717 return rb->flags & RAM_SHARED;
1718}
1719
1720bool qemu_ram_is_noreserve(RAMBlock *rb)
1721{
1722 return rb->flags & RAM_NORESERVE;
1723}
1724
1725
1726bool qemu_ram_is_uf_zeroable(RAMBlock *rb)
1727{
1728 return rb->flags & RAM_UF_ZEROPAGE;
1729}
1730
1731void qemu_ram_set_uf_zeroable(RAMBlock *rb)
1732{
1733 rb->flags |= RAM_UF_ZEROPAGE;
1734}
1735
1736bool qemu_ram_is_migratable(RAMBlock *rb)
1737{
1738 return rb->flags & RAM_MIGRATABLE;
1739}
1740
1741void qemu_ram_set_migratable(RAMBlock *rb)
1742{
1743 rb->flags |= RAM_MIGRATABLE;
1744}
1745
1746void qemu_ram_unset_migratable(RAMBlock *rb)
1747{
1748 rb->flags &= ~RAM_MIGRATABLE;
1749}
1750
1751
1752void qemu_ram_set_idstr(RAMBlock *new_block, const char *name, DeviceState *dev)
1753{
1754 RAMBlock *block;
1755
1756 assert(new_block);
1757 assert(!new_block->idstr[0]);
1758
1759 if (dev) {
1760 char *id = qdev_get_dev_path(dev);
1761 if (id) {
1762 snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);
1763 g_free(id);
1764 }
1765 }
1766 pstrcat(new_block->idstr, sizeof(new_block->idstr), name);
1767
1768 RCU_READ_LOCK_GUARD();
1769 RAMBLOCK_FOREACH(block) {
1770 if (block != new_block &&
1771 !strcmp(block->idstr, new_block->idstr)) {
1772 fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",
1773 new_block->idstr);
1774 abort();
1775 }
1776 }
1777}
1778
1779
1780void qemu_ram_unset_idstr(RAMBlock *block)
1781{
1782
1783
1784
1785
1786 if (block) {
1787 memset(block->idstr, 0, sizeof(block->idstr));
1788 }
1789}
1790
1791size_t qemu_ram_pagesize(RAMBlock *rb)
1792{
1793 return rb->page_size;
1794}
1795
1796
1797size_t qemu_ram_pagesize_largest(void)
1798{
1799 RAMBlock *block;
1800 size_t largest = 0;
1801
1802 RAMBLOCK_FOREACH(block) {
1803 largest = MAX(largest, qemu_ram_pagesize(block));
1804 }
1805
1806 return largest;
1807}
1808
1809static int memory_try_enable_merging(void *addr, size_t len)
1810{
1811 if (!machine_mem_merge(current_machine)) {
1812
1813 return 0;
1814 }
1815
1816 return qemu_madvise(addr, len, QEMU_MADV_MERGEABLE);
1817}
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827int qemu_ram_resize(RAMBlock *block, ram_addr_t newsize, Error **errp)
1828{
1829 const ram_addr_t oldsize = block->used_length;
1830 const ram_addr_t unaligned_size = newsize;
1831
1832 assert(block);
1833
1834 newsize = HOST_PAGE_ALIGN(newsize);
1835
1836 if (block->used_length == newsize) {
1837
1838
1839
1840
1841 if (unaligned_size != memory_region_size(block->mr)) {
1842 memory_region_set_size(block->mr, unaligned_size);
1843 if (block->resized) {
1844 block->resized(block->idstr, unaligned_size, block->host);
1845 }
1846 }
1847 return 0;
1848 }
1849
1850 if (!(block->flags & RAM_RESIZEABLE)) {
1851 error_setg_errno(errp, EINVAL,
1852 "Size mismatch: %s: 0x" RAM_ADDR_FMT
1853 " != 0x" RAM_ADDR_FMT, block->idstr,
1854 newsize, block->used_length);
1855 return -EINVAL;
1856 }
1857
1858 if (block->max_length < newsize) {
1859 error_setg_errno(errp, EINVAL,
1860 "Size too large: %s: 0x" RAM_ADDR_FMT
1861 " > 0x" RAM_ADDR_FMT, block->idstr,
1862 newsize, block->max_length);
1863 return -EINVAL;
1864 }
1865
1866
1867 if (block->host) {
1868 ram_block_notify_resize(block->host, oldsize, newsize);
1869 }
1870
1871 cpu_physical_memory_clear_dirty_range(block->offset, block->used_length);
1872 block->used_length = newsize;
1873 cpu_physical_memory_set_dirty_range(block->offset, block->used_length,
1874 DIRTY_CLIENTS_ALL);
1875 memory_region_set_size(block->mr, unaligned_size);
1876 if (block->resized) {
1877 block->resized(block->idstr, unaligned_size, block->host);
1878 }
1879 return 0;
1880}
1881
1882
1883
1884
1885
1886
1887
1888void qemu_ram_msync(RAMBlock *block, ram_addr_t start, ram_addr_t length)
1889{
1890
1891 g_assert((start + length) <= block->used_length);
1892
1893#ifdef CONFIG_LIBPMEM
1894
1895 if (ramblock_is_pmem(block)) {
1896 void *addr = ramblock_ptr(block, start);
1897 pmem_persist(addr, length);
1898 return;
1899 }
1900#endif
1901 if (block->fd >= 0) {
1902
1903
1904
1905
1906
1907 void *addr = ramblock_ptr(block, start);
1908 if (qemu_msync(addr, length, block->fd)) {
1909 warn_report("%s: failed to sync memory range: start: "
1910 RAM_ADDR_FMT " length: " RAM_ADDR_FMT,
1911 __func__, start, length);
1912 }
1913 }
1914}
1915
1916
1917static void dirty_memory_extend(ram_addr_t old_ram_size,
1918 ram_addr_t new_ram_size)
1919{
1920 ram_addr_t old_num_blocks = DIV_ROUND_UP(old_ram_size,
1921 DIRTY_MEMORY_BLOCK_SIZE);
1922 ram_addr_t new_num_blocks = DIV_ROUND_UP(new_ram_size,
1923 DIRTY_MEMORY_BLOCK_SIZE);
1924 int i;
1925
1926
1927 if (new_num_blocks <= old_num_blocks) {
1928 return;
1929 }
1930
1931 for (i = 0; i < DIRTY_MEMORY_NUM; i++) {
1932 DirtyMemoryBlocks *old_blocks;
1933 DirtyMemoryBlocks *new_blocks;
1934 int j;
1935
1936 old_blocks = qatomic_rcu_read(&ram_list.dirty_memory[i]);
1937 new_blocks = g_malloc(sizeof(*new_blocks) +
1938 sizeof(new_blocks->blocks[0]) * new_num_blocks);
1939
1940 if (old_num_blocks) {
1941 memcpy(new_blocks->blocks, old_blocks->blocks,
1942 old_num_blocks * sizeof(old_blocks->blocks[0]));
1943 }
1944
1945 for (j = old_num_blocks; j < new_num_blocks; j++) {
1946 new_blocks->blocks[j] = bitmap_new(DIRTY_MEMORY_BLOCK_SIZE);
1947 }
1948
1949 qatomic_rcu_set(&ram_list.dirty_memory[i], new_blocks);
1950
1951 if (old_blocks) {
1952 g_free_rcu(old_blocks, rcu);
1953 }
1954 }
1955}
1956
1957static void ram_block_add(RAMBlock *new_block, Error **errp)
1958{
1959 const bool noreserve = qemu_ram_is_noreserve(new_block);
1960 const bool shared = qemu_ram_is_shared(new_block);
1961 RAMBlock *block;
1962 RAMBlock *last_block = NULL;
1963 ram_addr_t old_ram_size, new_ram_size;
1964 Error *err = NULL;
1965
1966 old_ram_size = last_ram_page();
1967
1968 qemu_mutex_lock_ramlist();
1969 new_block->offset = find_ram_offset(new_block->max_length);
1970
1971 if (!new_block->host) {
1972 if (xen_enabled()) {
1973 xen_ram_alloc(new_block->offset, new_block->max_length,
1974 new_block->mr, &err);
1975 if (err) {
1976 error_propagate(errp, err);
1977 qemu_mutex_unlock_ramlist();
1978 return;
1979 }
1980 } else {
1981 new_block->host = qemu_anon_ram_alloc(new_block->max_length,
1982 &new_block->mr->align,
1983 shared, noreserve);
1984 if (!new_block->host) {
1985 error_setg_errno(errp, errno,
1986 "cannot set up guest memory '%s'",
1987 memory_region_name(new_block->mr));
1988 qemu_mutex_unlock_ramlist();
1989 return;
1990 }
1991 memory_try_enable_merging(new_block->host, new_block->max_length);
1992 }
1993 }
1994
1995 new_ram_size = MAX(old_ram_size,
1996 (new_block->offset + new_block->max_length) >> TARGET_PAGE_BITS);
1997 if (new_ram_size > old_ram_size) {
1998 dirty_memory_extend(old_ram_size, new_ram_size);
1999 }
2000
2001
2002
2003
2004 RAMBLOCK_FOREACH(block) {
2005 last_block = block;
2006 if (block->max_length < new_block->max_length) {
2007 break;
2008 }
2009 }
2010 if (block) {
2011 QLIST_INSERT_BEFORE_RCU(block, new_block, next);
2012 } else if (last_block) {
2013 QLIST_INSERT_AFTER_RCU(last_block, new_block, next);
2014 } else {
2015 QLIST_INSERT_HEAD_RCU(&ram_list.blocks, new_block, next);
2016 }
2017 ram_list.mru_block = NULL;
2018
2019
2020 smp_wmb();
2021 ram_list.version++;
2022 qemu_mutex_unlock_ramlist();
2023
2024 cpu_physical_memory_set_dirty_range(new_block->offset,
2025 new_block->used_length,
2026 DIRTY_CLIENTS_ALL);
2027
2028 if (new_block->host) {
2029 qemu_ram_setup_dump(new_block->host, new_block->max_length);
2030 qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);
2031
2032
2033
2034
2035
2036 if (!qtest_enabled()) {
2037 qemu_madvise(new_block->host, new_block->max_length,
2038 QEMU_MADV_DONTFORK);
2039 }
2040 ram_block_notify_add(new_block->host, new_block->used_length,
2041 new_block->max_length);
2042 }
2043}
2044
2045#ifdef CONFIG_POSIX
2046RAMBlock *qemu_ram_alloc_from_fd(ram_addr_t size, MemoryRegion *mr,
2047 uint32_t ram_flags, int fd, off_t offset,
2048 bool readonly, Error **errp)
2049{
2050 RAMBlock *new_block;
2051 Error *local_err = NULL;
2052 int64_t file_size, file_align;
2053
2054
2055 assert((ram_flags & ~(RAM_SHARED | RAM_PMEM | RAM_NORESERVE)) == 0);
2056
2057 if (xen_enabled()) {
2058 error_setg(errp, "-mem-path not supported with Xen");
2059 return NULL;
2060 }
2061
2062 if (kvm_enabled() && !kvm_has_sync_mmu()) {
2063 error_setg(errp,
2064 "host lacks kvm mmu notifiers, -mem-path unsupported");
2065 return NULL;
2066 }
2067
2068 size = HOST_PAGE_ALIGN(size);
2069 file_size = get_file_size(fd);
2070 if (file_size > 0 && file_size < size) {
2071 error_setg(errp, "backing store size 0x%" PRIx64
2072 " does not match 'size' option 0x" RAM_ADDR_FMT,
2073 file_size, size);
2074 return NULL;
2075 }
2076
2077 file_align = get_file_align(fd);
2078 if (file_align > 0 && mr && file_align > mr->align) {
2079 error_setg(errp, "backing store align 0x%" PRIx64
2080 " is larger than 'align' option 0x%" PRIx64,
2081 file_align, mr->align);
2082 return NULL;
2083 }
2084
2085 new_block = g_malloc0(sizeof(*new_block));
2086 new_block->mr = mr;
2087 new_block->used_length = size;
2088 new_block->max_length = size;
2089 new_block->flags = ram_flags;
2090 new_block->host = file_ram_alloc(new_block, size, fd, readonly,
2091 !file_size, offset, errp);
2092 if (!new_block->host) {
2093 g_free(new_block);
2094 return NULL;
2095 }
2096
2097 ram_block_add(new_block, &local_err);
2098 if (local_err) {
2099 g_free(new_block);
2100 error_propagate(errp, local_err);
2101 return NULL;
2102 }
2103 return new_block;
2104
2105}
2106
2107
2108RAMBlock *qemu_ram_alloc_from_file(ram_addr_t size, MemoryRegion *mr,
2109 uint32_t ram_flags, const char *mem_path,
2110 bool readonly, Error **errp)
2111{
2112 int fd;
2113 bool created;
2114 RAMBlock *block;
2115
2116 fd = file_ram_open(mem_path, memory_region_name(mr), readonly, &created,
2117 errp);
2118 if (fd < 0) {
2119 return NULL;
2120 }
2121
2122 block = qemu_ram_alloc_from_fd(size, mr, ram_flags, fd, 0, readonly, errp);
2123 if (!block) {
2124 if (created) {
2125 unlink(mem_path);
2126 }
2127 close(fd);
2128 return NULL;
2129 }
2130
2131 return block;
2132}
2133#endif
2134
2135static
2136RAMBlock *qemu_ram_alloc_internal(ram_addr_t size, ram_addr_t max_size,
2137 void (*resized)(const char*,
2138 uint64_t length,
2139 void *host),
2140 void *host, uint32_t ram_flags,
2141 MemoryRegion *mr, Error **errp)
2142{
2143 RAMBlock *new_block;
2144 Error *local_err = NULL;
2145
2146 assert((ram_flags & ~(RAM_SHARED | RAM_RESIZEABLE | RAM_PREALLOC |
2147 RAM_NORESERVE)) == 0);
2148 assert(!host ^ (ram_flags & RAM_PREALLOC));
2149
2150 size = HOST_PAGE_ALIGN(size);
2151 max_size = HOST_PAGE_ALIGN(max_size);
2152 new_block = g_malloc0(sizeof(*new_block));
2153 new_block->mr = mr;
2154 new_block->resized = resized;
2155 new_block->used_length = size;
2156 new_block->max_length = max_size;
2157 assert(max_size >= size);
2158 new_block->fd = -1;
2159 new_block->page_size = qemu_real_host_page_size;
2160 new_block->host = host;
2161 new_block->flags = ram_flags;
2162 ram_block_add(new_block, &local_err);
2163 if (local_err) {
2164 g_free(new_block);
2165 error_propagate(errp, local_err);
2166 return NULL;
2167 }
2168 return new_block;
2169}
2170
2171RAMBlock *qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,
2172 MemoryRegion *mr, Error **errp)
2173{
2174 return qemu_ram_alloc_internal(size, size, NULL, host, RAM_PREALLOC, mr,
2175 errp);
2176}
2177
2178RAMBlock *qemu_ram_alloc(ram_addr_t size, uint32_t ram_flags,
2179 MemoryRegion *mr, Error **errp)
2180{
2181 assert((ram_flags & ~(RAM_SHARED | RAM_NORESERVE)) == 0);
2182 return qemu_ram_alloc_internal(size, size, NULL, NULL, ram_flags, mr, errp);
2183}
2184
2185RAMBlock *qemu_ram_alloc_resizeable(ram_addr_t size, ram_addr_t maxsz,
2186 void (*resized)(const char*,
2187 uint64_t length,
2188 void *host),
2189 MemoryRegion *mr, Error **errp)
2190{
2191 return qemu_ram_alloc_internal(size, maxsz, resized, NULL,
2192 RAM_RESIZEABLE, mr, errp);
2193}
2194
2195static void reclaim_ramblock(RAMBlock *block)
2196{
2197 if (block->flags & RAM_PREALLOC) {
2198 ;
2199 } else if (xen_enabled()) {
2200 xen_invalidate_map_cache_entry(block->host);
2201#ifndef _WIN32
2202 } else if (block->fd >= 0) {
2203 qemu_ram_munmap(block->fd, block->host, block->max_length);
2204 close(block->fd);
2205#endif
2206 } else {
2207 qemu_anon_ram_free(block->host, block->max_length);
2208 }
2209 g_free(block);
2210}
2211
2212void qemu_ram_free(RAMBlock *block)
2213{
2214 if (!block) {
2215 return;
2216 }
2217
2218 if (block->host) {
2219 ram_block_notify_remove(block->host, block->used_length,
2220 block->max_length);
2221 }
2222
2223 qemu_mutex_lock_ramlist();
2224 QLIST_REMOVE_RCU(block, next);
2225 ram_list.mru_block = NULL;
2226
2227 smp_wmb();
2228 ram_list.version++;
2229 call_rcu(block, reclaim_ramblock, rcu);
2230 qemu_mutex_unlock_ramlist();
2231}
2232
2233#ifndef _WIN32
2234void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)
2235{
2236 RAMBlock *block;
2237 ram_addr_t offset;
2238 int flags;
2239 void *area, *vaddr;
2240
2241 RAMBLOCK_FOREACH(block) {
2242 offset = addr - block->offset;
2243 if (offset < block->max_length) {
2244 vaddr = ramblock_ptr(block, offset);
2245 if (block->flags & RAM_PREALLOC) {
2246 ;
2247 } else if (xen_enabled()) {
2248 abort();
2249 } else {
2250 flags = MAP_FIXED;
2251 flags |= block->flags & RAM_SHARED ?
2252 MAP_SHARED : MAP_PRIVATE;
2253 flags |= block->flags & RAM_NORESERVE ? MAP_NORESERVE : 0;
2254 if (block->fd >= 0) {
2255 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2256 flags, block->fd, offset);
2257 } else {
2258 flags |= MAP_ANONYMOUS;
2259 area = mmap(vaddr, length, PROT_READ | PROT_WRITE,
2260 flags, -1, 0);
2261 }
2262 if (area != vaddr) {
2263 error_report("Could not remap addr: "
2264 RAM_ADDR_FMT "@" RAM_ADDR_FMT "",
2265 length, addr);
2266 exit(1);
2267 }
2268 memory_try_enable_merging(vaddr, length);
2269 qemu_ram_setup_dump(vaddr, length);
2270 }
2271 }
2272 }
2273}
2274#endif
2275
2276
2277
2278
2279
2280
2281
2282
2283void *qemu_map_ram_ptr(RAMBlock *ram_block, ram_addr_t addr)
2284{
2285 RAMBlock *block = ram_block;
2286
2287 if (block == NULL) {
2288 block = qemu_get_ram_block(addr);
2289 addr -= block->offset;
2290 }
2291
2292 if (xen_enabled() && block->host == NULL) {
2293
2294
2295
2296
2297 if (block->offset == 0) {
2298 return xen_map_cache(addr, 0, 0, false);
2299 }
2300
2301 block->host = xen_map_cache(block->offset, block->max_length, 1, false);
2302 }
2303 return ramblock_ptr(block, addr);
2304}
2305
2306
2307
2308
2309
2310
2311static void *qemu_ram_ptr_length(RAMBlock *ram_block, ram_addr_t addr,
2312 hwaddr *size, bool lock)
2313{
2314 RAMBlock *block = ram_block;
2315 if (*size == 0) {
2316 return NULL;
2317 }
2318
2319 if (block == NULL) {
2320 block = qemu_get_ram_block(addr);
2321 addr -= block->offset;
2322 }
2323 *size = MIN(*size, block->max_length - addr);
2324
2325 if (xen_enabled() && block->host == NULL) {
2326
2327
2328
2329
2330 if (block->offset == 0) {
2331 return xen_map_cache(addr, *size, lock, lock);
2332 }
2333
2334 block->host = xen_map_cache(block->offset, block->max_length, 1, lock);
2335 }
2336
2337 return ramblock_ptr(block, addr);
2338}
2339
2340
2341ram_addr_t qemu_ram_block_host_offset(RAMBlock *rb, void *host)
2342{
2343 ram_addr_t res = (uint8_t *)host - (uint8_t *)rb->host;
2344 assert((uintptr_t)host >= (uintptr_t)rb->host);
2345 assert(res < rb->max_length);
2346
2347 return res;
2348}
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367RAMBlock *qemu_ram_block_from_host(void *ptr, bool round_offset,
2368 ram_addr_t *offset)
2369{
2370 RAMBlock *block;
2371 uint8_t *host = ptr;
2372
2373 if (xen_enabled()) {
2374 ram_addr_t ram_addr;
2375 RCU_READ_LOCK_GUARD();
2376 ram_addr = xen_ram_addr_from_mapcache(ptr);
2377 block = qemu_get_ram_block(ram_addr);
2378 if (block) {
2379 *offset = ram_addr - block->offset;
2380 }
2381 return block;
2382 }
2383
2384 RCU_READ_LOCK_GUARD();
2385 block = qatomic_rcu_read(&ram_list.mru_block);
2386 if (block && block->host && host - block->host < block->max_length) {
2387 goto found;
2388 }
2389
2390 RAMBLOCK_FOREACH(block) {
2391
2392 if (block->host == NULL) {
2393 continue;
2394 }
2395 if (host - block->host < block->max_length) {
2396 goto found;
2397 }
2398 }
2399
2400 return NULL;
2401
2402found:
2403 *offset = (host - block->host);
2404 if (round_offset) {
2405 *offset &= TARGET_PAGE_MASK;
2406 }
2407 return block;
2408}
2409
2410
2411
2412
2413
2414
2415
2416
2417RAMBlock *qemu_ram_block_by_name(const char *name)
2418{
2419 RAMBlock *block;
2420
2421 RAMBLOCK_FOREACH(block) {
2422 if (!strcmp(name, block->idstr)) {
2423 return block;
2424 }
2425 }
2426
2427 return NULL;
2428}
2429
2430
2431
2432ram_addr_t qemu_ram_addr_from_host(void *ptr)
2433{
2434 RAMBlock *block;
2435 ram_addr_t offset;
2436
2437 block = qemu_ram_block_from_host(ptr, false, &offset);
2438 if (!block) {
2439 return RAM_ADDR_INVALID;
2440 }
2441
2442 return block->offset + offset;
2443}
2444
2445static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2446 MemTxAttrs attrs, void *buf, hwaddr len);
2447static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2448 const void *buf, hwaddr len);
2449static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
2450 bool is_write, MemTxAttrs attrs);
2451
2452static MemTxResult subpage_read(void *opaque, hwaddr addr, uint64_t *data,
2453 unsigned len, MemTxAttrs attrs)
2454{
2455 subpage_t *subpage = opaque;
2456 uint8_t buf[8];
2457 MemTxResult res;
2458
2459#if defined(DEBUG_SUBPAGE)
2460 printf("%s: subpage %p len %u addr " TARGET_FMT_plx "\n", __func__,
2461 subpage, len, addr);
2462#endif
2463 res = flatview_read(subpage->fv, addr + subpage->base, attrs, buf, len);
2464 if (res) {
2465 return res;
2466 }
2467 *data = ldn_p(buf, len);
2468 return MEMTX_OK;
2469}
2470
2471static MemTxResult subpage_write(void *opaque, hwaddr addr,
2472 uint64_t value, unsigned len, MemTxAttrs attrs)
2473{
2474 subpage_t *subpage = opaque;
2475 uint8_t buf[8];
2476
2477#if defined(DEBUG_SUBPAGE)
2478 printf("%s: subpage %p len %u addr " TARGET_FMT_plx
2479 " value %"PRIx64"\n",
2480 __func__, subpage, len, addr, value);
2481#endif
2482 stn_p(buf, len, value);
2483 return flatview_write(subpage->fv, addr + subpage->base, attrs, buf, len);
2484}
2485
2486static bool subpage_accepts(void *opaque, hwaddr addr,
2487 unsigned len, bool is_write,
2488 MemTxAttrs attrs)
2489{
2490 subpage_t *subpage = opaque;
2491#if defined(DEBUG_SUBPAGE)
2492 printf("%s: subpage %p %c len %u addr " TARGET_FMT_plx "\n",
2493 __func__, subpage, is_write ? 'w' : 'r', len, addr);
2494#endif
2495
2496 return flatview_access_valid(subpage->fv, addr + subpage->base,
2497 len, is_write, attrs);
2498}
2499
2500static const MemoryRegionOps subpage_ops = {
2501 .read_with_attrs = subpage_read,
2502 .write_with_attrs = subpage_write,
2503 .impl.min_access_size = 1,
2504 .impl.max_access_size = 8,
2505 .valid.min_access_size = 1,
2506 .valid.max_access_size = 8,
2507 .valid.accepts = subpage_accepts,
2508 .endianness = DEVICE_NATIVE_ENDIAN,
2509};
2510
2511static int subpage_register(subpage_t *mmio, uint32_t start, uint32_t end,
2512 uint16_t section)
2513{
2514 int idx, eidx;
2515
2516 if (start >= TARGET_PAGE_SIZE || end >= TARGET_PAGE_SIZE)
2517 return -1;
2518 idx = SUBPAGE_IDX(start);
2519 eidx = SUBPAGE_IDX(end);
2520#if defined(DEBUG_SUBPAGE)
2521 printf("%s: %p start %08x end %08x idx %08x eidx %08x section %d\n",
2522 __func__, mmio, start, end, idx, eidx, section);
2523#endif
2524 for (; idx <= eidx; idx++) {
2525 mmio->sub_section[idx] = section;
2526 }
2527
2528 return 0;
2529}
2530
2531static subpage_t *subpage_init(FlatView *fv, hwaddr base)
2532{
2533 subpage_t *mmio;
2534
2535
2536 mmio = g_malloc0(sizeof(subpage_t) + TARGET_PAGE_SIZE * sizeof(uint16_t));
2537 mmio->fv = fv;
2538 mmio->base = base;
2539 memory_region_init_io(&mmio->iomem, NULL, &subpage_ops, mmio,
2540 NULL, TARGET_PAGE_SIZE);
2541 mmio->iomem.subpage = true;
2542#if defined(DEBUG_SUBPAGE)
2543 printf("%s: %p base " TARGET_FMT_plx " len %08x\n", __func__,
2544 mmio, base, TARGET_PAGE_SIZE);
2545#endif
2546
2547 return mmio;
2548}
2549
2550static uint16_t dummy_section(PhysPageMap *map, FlatView *fv, MemoryRegion *mr)
2551{
2552 assert(fv);
2553 MemoryRegionSection section = {
2554 .fv = fv,
2555 .mr = mr,
2556 .offset_within_address_space = 0,
2557 .offset_within_region = 0,
2558 .size = int128_2_64(),
2559 };
2560
2561 return phys_section_add(map, §ion);
2562}
2563
2564MemoryRegionSection *iotlb_to_section(CPUState *cpu,
2565 hwaddr index, MemTxAttrs attrs)
2566{
2567 int asidx = cpu_asidx_from_attrs(cpu, attrs);
2568 CPUAddressSpace *cpuas = &cpu->cpu_ases[asidx];
2569 AddressSpaceDispatch *d = qatomic_rcu_read(&cpuas->memory_dispatch);
2570 MemoryRegionSection *sections = d->map.sections;
2571
2572 return §ions[index & ~TARGET_PAGE_MASK];
2573}
2574
2575static void io_mem_init(void)
2576{
2577 memory_region_init_io(&io_mem_unassigned, NULL, &unassigned_mem_ops, NULL,
2578 NULL, UINT64_MAX);
2579}
2580
2581AddressSpaceDispatch *address_space_dispatch_new(FlatView *fv)
2582{
2583 AddressSpaceDispatch *d = g_new0(AddressSpaceDispatch, 1);
2584 uint16_t n;
2585
2586 n = dummy_section(&d->map, fv, &io_mem_unassigned);
2587 assert(n == PHYS_SECTION_UNASSIGNED);
2588
2589 d->phys_map = (PhysPageEntry) { .ptr = PHYS_MAP_NODE_NIL, .skip = 1 };
2590
2591 return d;
2592}
2593
2594void address_space_dispatch_free(AddressSpaceDispatch *d)
2595{
2596 phys_sections_free(&d->map);
2597 g_free(d);
2598}
2599
2600static void do_nothing(CPUState *cpu, run_on_cpu_data d)
2601{
2602}
2603
2604static void tcg_log_global_after_sync(MemoryListener *listener)
2605{
2606 CPUAddressSpace *cpuas;
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625 if (replay_mode == REPLAY_MODE_NONE) {
2626
2627
2628
2629
2630
2631
2632
2633 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2634 run_on_cpu(cpuas->cpu, do_nothing, RUN_ON_CPU_NULL);
2635 }
2636}
2637
2638static void tcg_commit(MemoryListener *listener)
2639{
2640 CPUAddressSpace *cpuas;
2641 AddressSpaceDispatch *d;
2642
2643 assert(tcg_enabled());
2644
2645
2646 cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);
2647 cpu_reloading_memory_map();
2648
2649
2650
2651
2652 d = address_space_to_dispatch(cpuas->as);
2653 qatomic_rcu_set(&cpuas->memory_dispatch, d);
2654 tlb_flush(cpuas->cpu);
2655}
2656
2657static void memory_map_init(void)
2658{
2659 system_memory = g_malloc(sizeof(*system_memory));
2660
2661 memory_region_init(system_memory, NULL, "system", UINT64_MAX);
2662 address_space_init(&address_space_memory, system_memory, "memory");
2663
2664 system_io = g_malloc(sizeof(*system_io));
2665 memory_region_init_io(system_io, NULL, &unassigned_io_ops, NULL, "io",
2666 65536);
2667 address_space_init(&address_space_io, system_io, "I/O");
2668}
2669
2670MemoryRegion *get_system_memory(void)
2671{
2672 return system_memory;
2673}
2674
2675MemoryRegion *get_system_io(void)
2676{
2677 return system_io;
2678}
2679
2680static void invalidate_and_set_dirty(MemoryRegion *mr, hwaddr addr,
2681 hwaddr length)
2682{
2683 uint8_t dirty_log_mask = memory_region_get_dirty_log_mask(mr);
2684 addr += memory_region_get_ram_addr(mr);
2685
2686
2687
2688
2689
2690 if (dirty_log_mask) {
2691 dirty_log_mask =
2692 cpu_physical_memory_range_includes_clean(addr, length, dirty_log_mask);
2693 }
2694 if (dirty_log_mask & (1 << DIRTY_MEMORY_CODE)) {
2695 assert(tcg_enabled());
2696 tb_invalidate_phys_range(addr, addr + length);
2697 dirty_log_mask &= ~(1 << DIRTY_MEMORY_CODE);
2698 }
2699 cpu_physical_memory_set_dirty_range(addr, length, dirty_log_mask);
2700}
2701
2702void memory_region_flush_rom_device(MemoryRegion *mr, hwaddr addr, hwaddr size)
2703{
2704
2705
2706
2707
2708
2709
2710 assert(memory_region_is_romd(mr));
2711
2712 invalidate_and_set_dirty(mr, addr, size);
2713}
2714
2715static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
2716{
2717 unsigned access_size_max = mr->ops->valid.max_access_size;
2718
2719
2720
2721 if (access_size_max == 0) {
2722 access_size_max = 4;
2723 }
2724
2725
2726 if (!mr->ops->impl.unaligned) {
2727 unsigned align_size_max = addr & -addr;
2728 if (align_size_max != 0 && align_size_max < access_size_max) {
2729 access_size_max = align_size_max;
2730 }
2731 }
2732
2733
2734 if (l > access_size_max) {
2735 l = access_size_max;
2736 }
2737 l = pow2floor(l);
2738
2739 return l;
2740}
2741
2742static bool prepare_mmio_access(MemoryRegion *mr)
2743{
2744 bool release_lock = false;
2745
2746 if (!qemu_mutex_iothread_locked()) {
2747 qemu_mutex_lock_iothread();
2748 release_lock = true;
2749 }
2750 if (mr->flush_coalesced_mmio) {
2751 qemu_flush_coalesced_mmio_buffer();
2752 }
2753
2754 return release_lock;
2755}
2756
2757
2758static MemTxResult flatview_write_continue(FlatView *fv, hwaddr addr,
2759 MemTxAttrs attrs,
2760 const void *ptr,
2761 hwaddr len, hwaddr addr1,
2762 hwaddr l, MemoryRegion *mr)
2763{
2764 uint8_t *ram_ptr;
2765 uint64_t val;
2766 MemTxResult result = MEMTX_OK;
2767 bool release_lock = false;
2768 const uint8_t *buf = ptr;
2769
2770 for (;;) {
2771 if (!memory_access_is_direct(mr, true)) {
2772 release_lock |= prepare_mmio_access(mr);
2773 l = memory_access_size(mr, l, addr1);
2774
2775
2776 val = ldn_he_p(buf, l);
2777 result |= memory_region_dispatch_write(mr, addr1, val,
2778 size_memop(l), attrs);
2779 } else {
2780
2781 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2782 memcpy(ram_ptr, buf, l);
2783 invalidate_and_set_dirty(mr, addr1, l);
2784 }
2785
2786 if (release_lock) {
2787 qemu_mutex_unlock_iothread();
2788 release_lock = false;
2789 }
2790
2791 len -= l;
2792 buf += l;
2793 addr += l;
2794
2795 if (!len) {
2796 break;
2797 }
2798
2799 l = len;
2800 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2801 }
2802
2803 return result;
2804}
2805
2806
2807static MemTxResult flatview_write(FlatView *fv, hwaddr addr, MemTxAttrs attrs,
2808 const void *buf, hwaddr len)
2809{
2810 hwaddr l;
2811 hwaddr addr1;
2812 MemoryRegion *mr;
2813 MemTxResult result = MEMTX_OK;
2814
2815 l = len;
2816 mr = flatview_translate(fv, addr, &addr1, &l, true, attrs);
2817 result = flatview_write_continue(fv, addr, attrs, buf, len,
2818 addr1, l, mr);
2819
2820 return result;
2821}
2822
2823
2824MemTxResult flatview_read_continue(FlatView *fv, hwaddr addr,
2825 MemTxAttrs attrs, void *ptr,
2826 hwaddr len, hwaddr addr1, hwaddr l,
2827 MemoryRegion *mr)
2828{
2829 uint8_t *ram_ptr;
2830 uint64_t val;
2831 MemTxResult result = MEMTX_OK;
2832 bool release_lock = false;
2833 uint8_t *buf = ptr;
2834
2835 fuzz_dma_read_cb(addr, len, mr);
2836 for (;;) {
2837 if (!memory_access_is_direct(mr, false)) {
2838
2839 release_lock |= prepare_mmio_access(mr);
2840 l = memory_access_size(mr, l, addr1);
2841 result |= memory_region_dispatch_read(mr, addr1, &val,
2842 size_memop(l), attrs);
2843 stn_he_p(buf, l, val);
2844 } else {
2845
2846 ram_ptr = qemu_ram_ptr_length(mr->ram_block, addr1, &l, false);
2847 memcpy(buf, ram_ptr, l);
2848 }
2849
2850 if (release_lock) {
2851 qemu_mutex_unlock_iothread();
2852 release_lock = false;
2853 }
2854
2855 len -= l;
2856 buf += l;
2857 addr += l;
2858
2859 if (!len) {
2860 break;
2861 }
2862
2863 l = len;
2864 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2865 }
2866
2867 return result;
2868}
2869
2870
2871static MemTxResult flatview_read(FlatView *fv, hwaddr addr,
2872 MemTxAttrs attrs, void *buf, hwaddr len)
2873{
2874 hwaddr l;
2875 hwaddr addr1;
2876 MemoryRegion *mr;
2877
2878 l = len;
2879 mr = flatview_translate(fv, addr, &addr1, &l, false, attrs);
2880 return flatview_read_continue(fv, addr, attrs, buf, len,
2881 addr1, l, mr);
2882}
2883
2884MemTxResult address_space_read_full(AddressSpace *as, hwaddr addr,
2885 MemTxAttrs attrs, void *buf, hwaddr len)
2886{
2887 MemTxResult result = MEMTX_OK;
2888 FlatView *fv;
2889
2890 if (len > 0) {
2891 RCU_READ_LOCK_GUARD();
2892 fv = address_space_to_flatview(as);
2893 result = flatview_read(fv, addr, attrs, buf, len);
2894 }
2895
2896 return result;
2897}
2898
2899MemTxResult address_space_write(AddressSpace *as, hwaddr addr,
2900 MemTxAttrs attrs,
2901 const void *buf, hwaddr len)
2902{
2903 MemTxResult result = MEMTX_OK;
2904 FlatView *fv;
2905
2906 if (len > 0) {
2907 RCU_READ_LOCK_GUARD();
2908 fv = address_space_to_flatview(as);
2909 result = flatview_write(fv, addr, attrs, buf, len);
2910 }
2911
2912 return result;
2913}
2914
2915MemTxResult address_space_rw(AddressSpace *as, hwaddr addr, MemTxAttrs attrs,
2916 void *buf, hwaddr len, bool is_write)
2917{
2918 if (is_write) {
2919 return address_space_write(as, addr, attrs, buf, len);
2920 } else {
2921 return address_space_read_full(as, addr, attrs, buf, len);
2922 }
2923}
2924
2925void cpu_physical_memory_rw(hwaddr addr, void *buf,
2926 hwaddr len, bool is_write)
2927{
2928 address_space_rw(&address_space_memory, addr, MEMTXATTRS_UNSPECIFIED,
2929 buf, len, is_write);
2930}
2931
2932enum write_rom_type {
2933 WRITE_DATA,
2934 FLUSH_CACHE,
2935};
2936
2937static inline MemTxResult address_space_write_rom_internal(AddressSpace *as,
2938 hwaddr addr,
2939 MemTxAttrs attrs,
2940 const void *ptr,
2941 hwaddr len,
2942 enum write_rom_type type)
2943{
2944 hwaddr l;
2945 uint8_t *ram_ptr;
2946 hwaddr addr1;
2947 MemoryRegion *mr;
2948 const uint8_t *buf = ptr;
2949
2950 RCU_READ_LOCK_GUARD();
2951 while (len > 0) {
2952 l = len;
2953 mr = address_space_translate(as, addr, &addr1, &l, true, attrs);
2954
2955 if (!(memory_region_is_ram(mr) ||
2956 memory_region_is_romd(mr))) {
2957 l = memory_access_size(mr, l, addr1);
2958 } else {
2959
2960 ram_ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
2961 switch (type) {
2962 case WRITE_DATA:
2963 memcpy(ram_ptr, buf, l);
2964 invalidate_and_set_dirty(mr, addr1, l);
2965 break;
2966 case FLUSH_CACHE:
2967 flush_idcache_range((uintptr_t)ram_ptr, (uintptr_t)ram_ptr, l);
2968 break;
2969 }
2970 }
2971 len -= l;
2972 buf += l;
2973 addr += l;
2974 }
2975 return MEMTX_OK;
2976}
2977
2978
2979MemTxResult address_space_write_rom(AddressSpace *as, hwaddr addr,
2980 MemTxAttrs attrs,
2981 const void *buf, hwaddr len)
2982{
2983 return address_space_write_rom_internal(as, addr, attrs,
2984 buf, len, WRITE_DATA);
2985}
2986
2987void cpu_flush_icache_range(hwaddr start, hwaddr len)
2988{
2989
2990
2991
2992
2993
2994
2995 if (tcg_enabled()) {
2996 return;
2997 }
2998
2999 address_space_write_rom_internal(&address_space_memory,
3000 start, MEMTXATTRS_UNSPECIFIED,
3001 NULL, len, FLUSH_CACHE);
3002}
3003
3004typedef struct {
3005 MemoryRegion *mr;
3006 void *buffer;
3007 hwaddr addr;
3008 hwaddr len;
3009 bool in_use;
3010} BounceBuffer;
3011
3012static BounceBuffer bounce;
3013
3014typedef struct MapClient {
3015 QEMUBH *bh;
3016 QLIST_ENTRY(MapClient) link;
3017} MapClient;
3018
3019QemuMutex map_client_list_lock;
3020static QLIST_HEAD(, MapClient) map_client_list
3021 = QLIST_HEAD_INITIALIZER(map_client_list);
3022
3023static void cpu_unregister_map_client_do(MapClient *client)
3024{
3025 QLIST_REMOVE(client, link);
3026 g_free(client);
3027}
3028
3029static void cpu_notify_map_clients_locked(void)
3030{
3031 MapClient *client;
3032
3033 while (!QLIST_EMPTY(&map_client_list)) {
3034 client = QLIST_FIRST(&map_client_list);
3035 qemu_bh_schedule(client->bh);
3036 cpu_unregister_map_client_do(client);
3037 }
3038}
3039
3040void cpu_register_map_client(QEMUBH *bh)
3041{
3042 MapClient *client = g_malloc(sizeof(*client));
3043
3044 qemu_mutex_lock(&map_client_list_lock);
3045 client->bh = bh;
3046 QLIST_INSERT_HEAD(&map_client_list, client, link);
3047 if (!qatomic_read(&bounce.in_use)) {
3048 cpu_notify_map_clients_locked();
3049 }
3050 qemu_mutex_unlock(&map_client_list_lock);
3051}
3052
3053void cpu_exec_init_all(void)
3054{
3055 qemu_mutex_init(&ram_list.mutex);
3056
3057
3058
3059
3060
3061
3062
3063 finalize_target_page_bits();
3064 io_mem_init();
3065 memory_map_init();
3066 qemu_mutex_init(&map_client_list_lock);
3067}
3068
3069void cpu_unregister_map_client(QEMUBH *bh)
3070{
3071 MapClient *client;
3072
3073 qemu_mutex_lock(&map_client_list_lock);
3074 QLIST_FOREACH(client, &map_client_list, link) {
3075 if (client->bh == bh) {
3076 cpu_unregister_map_client_do(client);
3077 break;
3078 }
3079 }
3080 qemu_mutex_unlock(&map_client_list_lock);
3081}
3082
3083static void cpu_notify_map_clients(void)
3084{
3085 qemu_mutex_lock(&map_client_list_lock);
3086 cpu_notify_map_clients_locked();
3087 qemu_mutex_unlock(&map_client_list_lock);
3088}
3089
3090static bool flatview_access_valid(FlatView *fv, hwaddr addr, hwaddr len,
3091 bool is_write, MemTxAttrs attrs)
3092{
3093 MemoryRegion *mr;
3094 hwaddr l, xlat;
3095
3096 while (len > 0) {
3097 l = len;
3098 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3099 if (!memory_access_is_direct(mr, is_write)) {
3100 l = memory_access_size(mr, l, addr);
3101 if (!memory_region_access_valid(mr, xlat, l, is_write, attrs)) {
3102 return false;
3103 }
3104 }
3105
3106 len -= l;
3107 addr += l;
3108 }
3109 return true;
3110}
3111
3112bool address_space_access_valid(AddressSpace *as, hwaddr addr,
3113 hwaddr len, bool is_write,
3114 MemTxAttrs attrs)
3115{
3116 FlatView *fv;
3117 bool result;
3118
3119 RCU_READ_LOCK_GUARD();
3120 fv = address_space_to_flatview(as);
3121 result = flatview_access_valid(fv, addr, len, is_write, attrs);
3122 return result;
3123}
3124
3125static hwaddr
3126flatview_extend_translation(FlatView *fv, hwaddr addr,
3127 hwaddr target_len,
3128 MemoryRegion *mr, hwaddr base, hwaddr len,
3129 bool is_write, MemTxAttrs attrs)
3130{
3131 hwaddr done = 0;
3132 hwaddr xlat;
3133 MemoryRegion *this_mr;
3134
3135 for (;;) {
3136 target_len -= len;
3137 addr += len;
3138 done += len;
3139 if (target_len == 0) {
3140 return done;
3141 }
3142
3143 len = target_len;
3144 this_mr = flatview_translate(fv, addr, &xlat,
3145 &len, is_write, attrs);
3146 if (this_mr != mr || xlat != base + done) {
3147 return done;
3148 }
3149 }
3150}
3151
3152
3153
3154
3155
3156
3157
3158
3159void *address_space_map(AddressSpace *as,
3160 hwaddr addr,
3161 hwaddr *plen,
3162 bool is_write,
3163 MemTxAttrs attrs)
3164{
3165 hwaddr len = *plen;
3166 hwaddr l, xlat;
3167 MemoryRegion *mr;
3168 void *ptr;
3169 FlatView *fv;
3170
3171 if (len == 0) {
3172 return NULL;
3173 }
3174
3175 l = len;
3176 RCU_READ_LOCK_GUARD();
3177 fv = address_space_to_flatview(as);
3178 mr = flatview_translate(fv, addr, &xlat, &l, is_write, attrs);
3179
3180 if (!memory_access_is_direct(mr, is_write)) {
3181 if (qatomic_xchg(&bounce.in_use, true)) {
3182 *plen = 0;
3183 return NULL;
3184 }
3185
3186 l = MIN(l, TARGET_PAGE_SIZE);
3187 bounce.buffer = qemu_memalign(TARGET_PAGE_SIZE, l);
3188 bounce.addr = addr;
3189 bounce.len = l;
3190
3191 memory_region_ref(mr);
3192 bounce.mr = mr;
3193 if (!is_write) {
3194 flatview_read(fv, addr, MEMTXATTRS_UNSPECIFIED,
3195 bounce.buffer, l);
3196 }
3197
3198 *plen = l;
3199 return bounce.buffer;
3200 }
3201
3202
3203 memory_region_ref(mr);
3204 *plen = flatview_extend_translation(fv, addr, len, mr, xlat,
3205 l, is_write, attrs);
3206 fuzz_dma_read_cb(addr, *plen, mr);
3207 ptr = qemu_ram_ptr_length(mr->ram_block, xlat, plen, true);
3208
3209 return ptr;
3210}
3211
3212
3213
3214
3215
3216void address_space_unmap(AddressSpace *as, void *buffer, hwaddr len,
3217 bool is_write, hwaddr access_len)
3218{
3219 if (buffer != bounce.buffer) {
3220 MemoryRegion *mr;
3221 ram_addr_t addr1;
3222
3223 mr = memory_region_from_host(buffer, &addr1);
3224 assert(mr != NULL);
3225 if (is_write) {
3226 invalidate_and_set_dirty(mr, addr1, access_len);
3227 }
3228 if (xen_enabled()) {
3229 xen_invalidate_map_cache_entry(buffer);
3230 }
3231 memory_region_unref(mr);
3232 return;
3233 }
3234 if (is_write) {
3235 address_space_write(as, bounce.addr, MEMTXATTRS_UNSPECIFIED,
3236 bounce.buffer, access_len);
3237 }
3238 qemu_vfree(bounce.buffer);
3239 bounce.buffer = NULL;
3240 memory_region_unref(bounce.mr);
3241 qatomic_mb_set(&bounce.in_use, false);
3242 cpu_notify_map_clients();
3243}
3244
3245void *cpu_physical_memory_map(hwaddr addr,
3246 hwaddr *plen,
3247 bool is_write)
3248{
3249 return address_space_map(&address_space_memory, addr, plen, is_write,
3250 MEMTXATTRS_UNSPECIFIED);
3251}
3252
3253void cpu_physical_memory_unmap(void *buffer, hwaddr len,
3254 bool is_write, hwaddr access_len)
3255{
3256 return address_space_unmap(&address_space_memory, buffer, len, is_write, access_len);
3257}
3258
3259#define ARG1_DECL AddressSpace *as
3260#define ARG1 as
3261#define SUFFIX
3262#define TRANSLATE(...) address_space_translate(as, __VA_ARGS__)
3263#define RCU_READ_LOCK(...) rcu_read_lock()
3264#define RCU_READ_UNLOCK(...) rcu_read_unlock()
3265#include "memory_ldst.c.inc"
3266
3267int64_t address_space_cache_init(MemoryRegionCache *cache,
3268 AddressSpace *as,
3269 hwaddr addr,
3270 hwaddr len,
3271 bool is_write)
3272{
3273 AddressSpaceDispatch *d;
3274 hwaddr l;
3275 MemoryRegion *mr;
3276 Int128 diff;
3277
3278 assert(len > 0);
3279
3280 l = len;
3281 cache->fv = address_space_get_flatview(as);
3282 d = flatview_to_dispatch(cache->fv);
3283 cache->mrs = *address_space_translate_internal(d, addr, &cache->xlat, &l, true);
3284
3285
3286
3287
3288
3289
3290 diff = int128_sub(cache->mrs.size,
3291 int128_make64(cache->xlat - cache->mrs.offset_within_region));
3292 l = int128_get64(int128_min(diff, int128_make64(l)));
3293
3294 mr = cache->mrs.mr;
3295 memory_region_ref(mr);
3296 if (memory_access_is_direct(mr, is_write)) {
3297
3298
3299
3300
3301 l = flatview_extend_translation(cache->fv, addr, len, mr,
3302 cache->xlat, l, is_write,
3303 MEMTXATTRS_UNSPECIFIED);
3304 cache->ptr = qemu_ram_ptr_length(mr->ram_block, cache->xlat, &l, true);
3305 } else {
3306 cache->ptr = NULL;
3307 }
3308
3309 cache->len = l;
3310 cache->is_write = is_write;
3311 return l;
3312}
3313
3314void address_space_cache_invalidate(MemoryRegionCache *cache,
3315 hwaddr addr,
3316 hwaddr access_len)
3317{
3318 assert(cache->is_write);
3319 if (likely(cache->ptr)) {
3320 invalidate_and_set_dirty(cache->mrs.mr, addr + cache->xlat, access_len);
3321 }
3322}
3323
3324void address_space_cache_destroy(MemoryRegionCache *cache)
3325{
3326 if (!cache->mrs.mr) {
3327 return;
3328 }
3329
3330 if (xen_enabled()) {
3331 xen_invalidate_map_cache_entry(cache->ptr);
3332 }
3333 memory_region_unref(cache->mrs.mr);
3334 flatview_unref(cache->fv);
3335 cache->mrs.mr = NULL;
3336 cache->fv = NULL;
3337}
3338
3339
3340
3341
3342
3343
3344static inline MemoryRegion *address_space_translate_cached(
3345 MemoryRegionCache *cache, hwaddr addr, hwaddr *xlat,
3346 hwaddr *plen, bool is_write, MemTxAttrs attrs)
3347{
3348 MemoryRegionSection section;
3349 MemoryRegion *mr;
3350 IOMMUMemoryRegion *iommu_mr;
3351 AddressSpace *target_as;
3352
3353 assert(!cache->ptr);
3354 *xlat = addr + cache->xlat;
3355
3356 mr = cache->mrs.mr;
3357 iommu_mr = memory_region_get_iommu(mr);
3358 if (!iommu_mr) {
3359
3360 return mr;
3361 }
3362
3363 section = address_space_translate_iommu(iommu_mr, xlat, plen,
3364 NULL, is_write, true,
3365 &target_as, attrs);
3366 return section.mr;
3367}
3368
3369
3370
3371
3372MemTxResult
3373address_space_read_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3374 void *buf, hwaddr len)
3375{
3376 hwaddr addr1, l;
3377 MemoryRegion *mr;
3378
3379 l = len;
3380 mr = address_space_translate_cached(cache, addr, &addr1, &l, false,
3381 MEMTXATTRS_UNSPECIFIED);
3382 return flatview_read_continue(cache->fv,
3383 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3384 addr1, l, mr);
3385}
3386
3387
3388
3389
3390MemTxResult
3391address_space_write_cached_slow(MemoryRegionCache *cache, hwaddr addr,
3392 const void *buf, hwaddr len)
3393{
3394 hwaddr addr1, l;
3395 MemoryRegion *mr;
3396
3397 l = len;
3398 mr = address_space_translate_cached(cache, addr, &addr1, &l, true,
3399 MEMTXATTRS_UNSPECIFIED);
3400 return flatview_write_continue(cache->fv,
3401 addr, MEMTXATTRS_UNSPECIFIED, buf, len,
3402 addr1, l, mr);
3403}
3404
3405#define ARG1_DECL MemoryRegionCache *cache
3406#define ARG1 cache
3407#define SUFFIX _cached_slow
3408#define TRANSLATE(...) address_space_translate_cached(cache, __VA_ARGS__)
3409#define RCU_READ_LOCK() ((void)0)
3410#define RCU_READ_UNLOCK() ((void)0)
3411#include "memory_ldst.c.inc"
3412
3413
3414int cpu_memory_rw_debug(CPUState *cpu, target_ulong addr,
3415 void *ptr, target_ulong len, bool is_write)
3416{
3417 hwaddr phys_addr;
3418 target_ulong l, page;
3419 uint8_t *buf = ptr;
3420
3421 cpu_synchronize_state(cpu);
3422 while (len > 0) {
3423 int asidx;
3424 MemTxAttrs attrs;
3425 MemTxResult res;
3426
3427 page = addr & TARGET_PAGE_MASK;
3428 phys_addr = cpu_get_phys_page_attrs_debug(cpu, page, &attrs);
3429 asidx = cpu_asidx_from_attrs(cpu, attrs);
3430
3431 if (phys_addr == -1)
3432 return -1;
3433 l = (page + TARGET_PAGE_SIZE) - addr;
3434 if (l > len)
3435 l = len;
3436 phys_addr += (addr & ~TARGET_PAGE_MASK);
3437 if (is_write) {
3438 res = address_space_write_rom(cpu->cpu_ases[asidx].as, phys_addr,
3439 attrs, buf, l);
3440 } else {
3441 res = address_space_read(cpu->cpu_ases[asidx].as, phys_addr,
3442 attrs, buf, l);
3443 }
3444 if (res != MEMTX_OK) {
3445 return -1;
3446 }
3447 len -= l;
3448 buf += l;
3449 addr += l;
3450 }
3451 return 0;
3452}
3453
3454
3455
3456
3457
3458size_t qemu_target_page_size(void)
3459{
3460 return TARGET_PAGE_SIZE;
3461}
3462
3463int qemu_target_page_bits(void)
3464{
3465 return TARGET_PAGE_BITS;
3466}
3467
3468int qemu_target_page_bits_min(void)
3469{
3470 return TARGET_PAGE_BITS_MIN;
3471}
3472
3473bool cpu_physical_memory_is_io(hwaddr phys_addr)
3474{
3475 MemoryRegion*mr;
3476 hwaddr l = 1;
3477 bool res;
3478
3479 RCU_READ_LOCK_GUARD();
3480 mr = address_space_translate(&address_space_memory,
3481 phys_addr, &phys_addr, &l, false,
3482 MEMTXATTRS_UNSPECIFIED);
3483
3484 res = !(memory_region_is_ram(mr) || memory_region_is_romd(mr));
3485 return res;
3486}
3487
3488int qemu_ram_foreach_block(RAMBlockIterFunc func, void *opaque)
3489{
3490 RAMBlock *block;
3491 int ret = 0;
3492
3493 RCU_READ_LOCK_GUARD();
3494 RAMBLOCK_FOREACH(block) {
3495 ret = func(block, opaque);
3496 if (ret) {
3497 break;
3498 }
3499 }
3500 return ret;
3501}
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511int ram_block_discard_range(RAMBlock *rb, uint64_t start, size_t length)
3512{
3513 int ret = -1;
3514
3515 uint8_t *host_startaddr = rb->host + start;
3516
3517 if (!QEMU_PTR_IS_ALIGNED(host_startaddr, rb->page_size)) {
3518 error_report("ram_block_discard_range: Unaligned start address: %p",
3519 host_startaddr);
3520 goto err;
3521 }
3522
3523 if ((start + length) <= rb->max_length) {
3524 bool need_madvise, need_fallocate;
3525 if (!QEMU_IS_ALIGNED(length, rb->page_size)) {
3526 error_report("ram_block_discard_range: Unaligned length: %zx",
3527 length);
3528 goto err;
3529 }
3530
3531 errno = ENOTSUP;
3532
3533
3534
3535
3536
3537
3538 need_madvise = (rb->page_size == qemu_host_page_size);
3539 need_fallocate = rb->fd != -1;
3540 if (need_fallocate) {
3541
3542
3543
3544
3545#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
3546 ret = fallocate(rb->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
3547 start, length);
3548 if (ret) {
3549 ret = -errno;
3550 error_report("ram_block_discard_range: Failed to fallocate "
3551 "%s:%" PRIx64 " +%zx (%d)",
3552 rb->idstr, start, length, ret);
3553 goto err;
3554 }
3555#else
3556 ret = -ENOSYS;
3557 error_report("ram_block_discard_range: fallocate not available/file"
3558 "%s:%" PRIx64 " +%zx (%d)",
3559 rb->idstr, start, length, ret);
3560 goto err;
3561#endif
3562 }
3563 if (need_madvise) {
3564
3565
3566
3567
3568
3569#if defined(CONFIG_MADVISE)
3570 if (qemu_ram_is_shared(rb) && rb->fd < 0) {
3571 ret = madvise(host_startaddr, length, QEMU_MADV_REMOVE);
3572 } else {
3573 ret = madvise(host_startaddr, length, QEMU_MADV_DONTNEED);
3574 }
3575 if (ret) {
3576 ret = -errno;
3577 error_report("ram_block_discard_range: Failed to discard range "
3578 "%s:%" PRIx64 " +%zx (%d)",
3579 rb->idstr, start, length, ret);
3580 goto err;
3581 }
3582#else
3583 ret = -ENOSYS;
3584 error_report("ram_block_discard_range: MADVISE not available"
3585 "%s:%" PRIx64 " +%zx (%d)",
3586 rb->idstr, start, length, ret);
3587 goto err;
3588#endif
3589 }
3590 trace_ram_block_discard_range(rb->idstr, host_startaddr, length,
3591 need_madvise, need_fallocate, ret);
3592 } else {
3593 error_report("ram_block_discard_range: Overrun block '%s' (%" PRIu64
3594 "/%zx/" RAM_ADDR_FMT")",
3595 rb->idstr, start, length, rb->max_length);
3596 }
3597
3598err:
3599 return ret;
3600}
3601
3602bool ramblock_is_pmem(RAMBlock *rb)
3603{
3604 return rb->flags & RAM_PMEM;
3605}
3606
3607static void mtree_print_phys_entries(int start, int end, int skip, int ptr)
3608{
3609 if (start == end - 1) {
3610 qemu_printf("\t%3d ", start);
3611 } else {
3612 qemu_printf("\t%3d..%-3d ", start, end - 1);
3613 }
3614 qemu_printf(" skip=%d ", skip);
3615 if (ptr == PHYS_MAP_NODE_NIL) {
3616 qemu_printf(" ptr=NIL");
3617 } else if (!skip) {
3618 qemu_printf(" ptr=#%d", ptr);
3619 } else {
3620 qemu_printf(" ptr=[%d]", ptr);
3621 }
3622 qemu_printf("\n");
3623}
3624
3625#define MR_SIZE(size) (int128_nz(size) ? (hwaddr)int128_get64( \
3626 int128_sub((size), int128_one())) : 0)
3627
3628void mtree_print_dispatch(AddressSpaceDispatch *d, MemoryRegion *root)
3629{
3630 int i;
3631
3632 qemu_printf(" Dispatch\n");
3633 qemu_printf(" Physical sections\n");
3634
3635 for (i = 0; i < d->map.sections_nb; ++i) {
3636 MemoryRegionSection *s = d->map.sections + i;
3637 const char *names[] = { " [unassigned]", " [not dirty]",
3638 " [ROM]", " [watch]" };
3639
3640 qemu_printf(" #%d @" TARGET_FMT_plx ".." TARGET_FMT_plx
3641 " %s%s%s%s%s",
3642 i,
3643 s->offset_within_address_space,
3644 s->offset_within_address_space + MR_SIZE(s->mr->size),
3645 s->mr->name ? s->mr->name : "(noname)",
3646 i < ARRAY_SIZE(names) ? names[i] : "",
3647 s->mr == root ? " [ROOT]" : "",
3648 s == d->mru_section ? " [MRU]" : "",
3649 s->mr->is_iommu ? " [iommu]" : "");
3650
3651 if (s->mr->alias) {
3652 qemu_printf(" alias=%s", s->mr->alias->name ?
3653 s->mr->alias->name : "noname");
3654 }
3655 qemu_printf("\n");
3656 }
3657
3658 qemu_printf(" Nodes (%d bits per level, %d levels) ptr=[%d] skip=%d\n",
3659 P_L2_BITS, P_L2_LEVELS, d->phys_map.ptr, d->phys_map.skip);
3660 for (i = 0; i < d->map.nodes_nb; ++i) {
3661 int j, jprev;
3662 PhysPageEntry prev;
3663 Node *n = d->map.nodes + i;
3664
3665 qemu_printf(" [%d]\n", i);
3666
3667 for (j = 0, jprev = 0, prev = *n[0]; j < ARRAY_SIZE(*n); ++j) {
3668 PhysPageEntry *pe = *n + j;
3669
3670 if (pe->ptr == prev.ptr && pe->skip == prev.skip) {
3671 continue;
3672 }
3673
3674 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3675
3676 jprev = j;
3677 prev = *pe;
3678 }
3679
3680 if (jprev != ARRAY_SIZE(*n)) {
3681 mtree_print_phys_entries(jprev, j, prev.skip, prev.ptr);
3682 }
3683 }
3684}
3685
3686
3687static unsigned int ram_block_discard_required_cnt;
3688
3689static unsigned int ram_block_coordinated_discard_required_cnt;
3690
3691static unsigned int ram_block_discard_disabled_cnt;
3692
3693static unsigned int ram_block_uncoordinated_discard_disabled_cnt;
3694static QemuMutex ram_block_discard_disable_mutex;
3695
3696static void ram_block_discard_disable_mutex_lock(void)
3697{
3698 static gsize initialized;
3699
3700 if (g_once_init_enter(&initialized)) {
3701 qemu_mutex_init(&ram_block_discard_disable_mutex);
3702 g_once_init_leave(&initialized, 1);
3703 }
3704 qemu_mutex_lock(&ram_block_discard_disable_mutex);
3705}
3706
3707static void ram_block_discard_disable_mutex_unlock(void)
3708{
3709 qemu_mutex_unlock(&ram_block_discard_disable_mutex);
3710}
3711
3712int ram_block_discard_disable(bool state)
3713{
3714 int ret = 0;
3715
3716 ram_block_discard_disable_mutex_lock();
3717 if (!state) {
3718 ram_block_discard_disabled_cnt--;
3719 } else if (ram_block_discard_required_cnt ||
3720 ram_block_coordinated_discard_required_cnt) {
3721 ret = -EBUSY;
3722 } else {
3723 ram_block_discard_disabled_cnt++;
3724 }
3725 ram_block_discard_disable_mutex_unlock();
3726 return ret;
3727}
3728
3729int ram_block_uncoordinated_discard_disable(bool state)
3730{
3731 int ret = 0;
3732
3733 ram_block_discard_disable_mutex_lock();
3734 if (!state) {
3735 ram_block_uncoordinated_discard_disabled_cnt--;
3736 } else if (ram_block_discard_required_cnt) {
3737 ret = -EBUSY;
3738 } else {
3739 ram_block_uncoordinated_discard_disabled_cnt++;
3740 }
3741 ram_block_discard_disable_mutex_unlock();
3742 return ret;
3743}
3744
3745int ram_block_discard_require(bool state)
3746{
3747 int ret = 0;
3748
3749 ram_block_discard_disable_mutex_lock();
3750 if (!state) {
3751 ram_block_discard_required_cnt--;
3752 } else if (ram_block_discard_disabled_cnt ||
3753 ram_block_uncoordinated_discard_disabled_cnt) {
3754 ret = -EBUSY;
3755 } else {
3756 ram_block_discard_required_cnt++;
3757 }
3758 ram_block_discard_disable_mutex_unlock();
3759 return ret;
3760}
3761
3762int ram_block_coordinated_discard_require(bool state)
3763{
3764 int ret = 0;
3765
3766 ram_block_discard_disable_mutex_lock();
3767 if (!state) {
3768 ram_block_coordinated_discard_required_cnt--;
3769 } else if (ram_block_discard_disabled_cnt) {
3770 ret = -EBUSY;
3771 } else {
3772 ram_block_coordinated_discard_required_cnt++;
3773 }
3774 ram_block_discard_disable_mutex_unlock();
3775 return ret;
3776}
3777
3778bool ram_block_discard_is_disabled(void)
3779{
3780 return qatomic_read(&ram_block_discard_disabled_cnt) ||
3781 qatomic_read(&ram_block_uncoordinated_discard_disabled_cnt);
3782}
3783
3784bool ram_block_discard_is_required(void)
3785{
3786 return qatomic_read(&ram_block_discard_required_cnt) ||
3787 qatomic_read(&ram_block_coordinated_discard_required_cnt);
3788}
3789