1 // SPDX-License-Identifier: LGPL-2.1-or-later
3 * Copyright (C) 2022 Paul Cercueil <paul@crapouillou.net>
17 #include "../psxmem.h"
18 #include "../r3000a.h"
22 #define ARRAY_SIZE(a) (sizeof(a) ? (sizeof(a) / sizeof((a)[0])) : 0)
24 #ifndef MAP_FIXED_NOREPLACE
25 #define MAP_FIXED_NOREPLACE 0x100000
29 #define MFD_HUGETLB 0x0004
32 static const uintptr_t supported_io_bases[] = {
39 static void * mmap_huge(void *addr, size_t length, int prot, int flags,
42 void *map = MAP_FAILED;
44 if (length >= 0x200000) {
45 map = mmap(addr, length, prot,
46 flags | MAP_HUGETLB | (21 << MAP_HUGE_SHIFT),
48 if (map != MAP_FAILED)
49 printf("Hugetlb mmap to address 0x%lx succeeded\n", (uintptr_t) addr);
52 if (map == MAP_FAILED) {
53 map = mmap(addr, length, prot, flags, fd, offset);
54 if (map != MAP_FAILED)
55 printf("Regular mmap to address 0x%lx succeeded\n", (uintptr_t) addr);
61 static int lightrec_mmap_ram(bool hugetlb)
64 int err, memfd, flags = 0;
71 memfd = memfd_create("/lightrec_memfd", flags);
74 fprintf(stderr, "Failed to create memfd: %d\n", err);
78 err = ftruncate(memfd, 0x200000);
81 fprintf(stderr, "Could not trim memfd: %d\n", err);
85 for (i = 0; i < ARRAY_SIZE(supported_io_bases); i++) {
86 base = supported_io_bases[i];
88 for (j = 0; j < 4; j++) {
89 map = mmap_huge((void *)(base + j * 0x200000),
90 0x200000, PROT_READ | PROT_WRITE,
91 MAP_SHARED | MAP_FIXED, memfd, 0);
92 if (map == MAP_FAILED)
96 /* Impossible to map using this base */
100 /* All mirrors mapped - we got a match! */
104 /* Only some mirrors mapped - clean the mess and try again */
106 munmap((void *)(base + (j - 1) * 0x200000), 0x200000);
109 if (i == ARRAY_SIZE(supported_io_bases)) {
111 goto err_close_memfd;
122 int lightrec_init_mmap(void)
129 err = lightrec_mmap_ram(true);
131 err = lightrec_mmap_ram(false);
133 fprintf(stderr, "Unable to mmap RAM and mirrors\n");
138 base = (uintptr_t) psxM;
140 map = mmap((void *)(base + 0x1f000000), 0x10000,
141 PROT_READ | PROT_WRITE,
142 MAP_PRIVATE | MAP_FIXED_NOREPLACE | MAP_ANONYMOUS, 0, 0);
143 if (map == MAP_FAILED) {
145 fprintf(stderr, "Unable to mmap parallel port\n");
151 map = mmap_huge((void *)(base + 0x1fc00000), 0x200000,
152 PROT_READ | PROT_WRITE,
153 MAP_PRIVATE | MAP_FIXED_NOREPLACE | MAP_ANONYMOUS, 0, 0);
154 if (map == MAP_FAILED) {
156 fprintf(stderr, "Unable to mmap BIOS\n");
157 goto err_unmap_parallel;
162 map = mmap((void *)(base + 0x1f800000), 0x10000,
163 PROT_READ | PROT_WRITE,
164 MAP_PRIVATE | MAP_FIXED_NOREPLACE | MAP_ANONYMOUS, 0, 0);
165 if (map == MAP_FAILED) {
167 fprintf(stderr, "Unable to mmap scratchpad\n");
176 munmap(psxR, 0x80000);
178 munmap(psxP, 0x10000);
180 for (i = 0; i < 4; i++)
181 munmap((void *)((uintptr_t)psxM + i * 0x200000), 0x200000);
185 void lightrec_free_mmap(void)
189 munmap(psxH, 0x10000);
190 munmap(psxR, 0x80000);
191 munmap(psxP, 0x10000);
192 for (i = 0; i < 4; i++)
193 munmap((void *)((uintptr_t)psxM + i * 0x200000), 0x200000);