Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/Core/MemMap.cpp
3185 views
1
// Copyright (C) 2003 Dolphin Project / 2012 PPSSPP Project
2
3
// This program is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, version 2.0 or later versions.
6
7
// This program is distributed in the hope that it will be useful,
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
// GNU General Public License 2.0 for more details.
11
12
// A copy of the GPL 2.0 should have been included with the program.
13
// If not, see http://www.gnu.org/licenses/
14
15
// Official git repository and contact information can be found at
16
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
17
18
#include "ppsspp_config.h"
19
20
#if PPSSPP_PLATFORM(UWP)
21
#include "Common/CommonWindows.h"
22
#endif
23
24
#include <algorithm>
25
#include <mutex>
26
27
#include "Common/CommonTypes.h"
28
#include "Common/MemArena.h"
29
#include "Common/Serialize/Serializer.h"
30
#include "Common/Serialize/SerializeFuncs.h"
31
32
#include "Core/System.h"
33
#include "Core/Core.h"
34
#include "Core/ConfigValues.h"
35
#include "Core/Debugger/MemBlockInfo.h"
36
#include "Core/HDRemaster.h"
37
#include "Core/HLE/ReplaceTables.h"
38
#include "Core/MemMap.h"
39
#include "Core/MemFault.h"
40
#include "Core/MIPS/MIPS.h"
41
#include "Core/MIPS/JitCommon/JitCommon.h"
42
#include "Common/Thread/ParallelLoop.h"
43
44
namespace Memory {
45
46
// The base pointer to the auto-mirrored arena.
47
u8* base = nullptr;
48
49
// The MemArena class
50
MemArena g_arena;
51
// ==============
52
53
u8 *m_pPhysicalScratchPad;
54
u8 *m_pUncachedScratchPad;
55
// 64-bit: Pointers to high-mem mirrors
56
// 32-bit: Same as above
57
u8 *m_pPhysicalRAM[3];
58
u8 *m_pUncachedRAM[3];
59
u8 *m_pKernelRAM[3]; // RAM mirrored up to "kernel space". Fully accessible at all times currently.
60
// Technically starts at 0xA0000000, which we don't properly support (but we don't really support kernel code.)
61
// This matches how we handle 32-bit masking.
62
u8 *m_pUncachedKernelRAM[3];
63
64
// VRAM is mirrored 4 times. The second and fourth mirrors are swizzled.
65
// In practice, a game accessing the mirrors most likely is deswizzling the depth buffer.
66
u8 *m_pPhysicalVRAM[4];
67
u8 *m_pUncachedVRAM[4];
68
69
// Holds the ending address of the PSP's user space.
70
// Required for HD Remasters to work properly.
71
// This replaces RAM_NORMAL_SIZE at runtime.
72
u32 g_MemorySize;
73
// Used to store the PSP model on game startup.
74
u32 g_PSPModel;
75
76
std::recursive_mutex g_shutdownLock;
77
78
// We don't declare the IO region in here since its handled by other means.
79
static MemoryView views[] =
80
{
81
{&m_pPhysicalScratchPad, 0x00010000, SCRATCHPAD_SIZE, 0},
82
{&m_pUncachedScratchPad, 0x40010000, SCRATCHPAD_SIZE, MV_MIRROR_PREVIOUS},
83
{&m_pPhysicalVRAM[0], 0x04000000, 0x00200000, 0},
84
{&m_pPhysicalVRAM[1], 0x04200000, 0x00200000, MV_MIRROR_PREVIOUS},
85
{&m_pPhysicalVRAM[2], 0x04400000, 0x00200000, MV_MIRROR_PREVIOUS},
86
{&m_pPhysicalVRAM[3], 0x04600000, 0x00200000, MV_MIRROR_PREVIOUS},
87
{&m_pUncachedVRAM[0], 0x44000000, 0x00200000, MV_MIRROR_PREVIOUS},
88
{&m_pUncachedVRAM[1], 0x44200000, 0x00200000, MV_MIRROR_PREVIOUS},
89
{&m_pUncachedVRAM[2], 0x44400000, 0x00200000, MV_MIRROR_PREVIOUS},
90
{&m_pUncachedVRAM[3], 0x44600000, 0x00200000, MV_MIRROR_PREVIOUS},
91
{&m_pPhysicalRAM[0], 0x08000000, g_MemorySize, MV_IS_PRIMARY_RAM}, // only from 0x08800000 is it usable (last 24 megs)
92
{&m_pUncachedRAM[0], 0x48000000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_PRIMARY_RAM},
93
{&m_pKernelRAM[0], 0x88000000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_PRIMARY_RAM | MV_KERNEL},
94
{&m_pUncachedKernelRAM[0],0xC8000000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_PRIMARY_RAM | MV_KERNEL},
95
// Starts at memory + 31 MB.
96
{&m_pPhysicalRAM[1], 0x09F00000, g_MemorySize, MV_IS_EXTRA1_RAM},
97
{&m_pUncachedRAM[1], 0x49F00000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_EXTRA1_RAM},
98
{&m_pKernelRAM[1], 0x89F00000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_EXTRA1_RAM | MV_KERNEL},
99
{&m_pUncachedKernelRAM[1],0xC9F00000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_EXTRA1_RAM | MV_KERNEL},
100
// Starts at memory + 31 * 2 MB.
101
{&m_pPhysicalRAM[2], 0x0BE00000, g_MemorySize, MV_IS_EXTRA2_RAM},
102
{&m_pUncachedRAM[2], 0x4BE00000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_EXTRA2_RAM},
103
{&m_pKernelRAM[2], 0x8BE00000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_EXTRA2_RAM | MV_KERNEL},
104
{&m_pUncachedKernelRAM[2],0xCBE00000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_EXTRA2_RAM | MV_KERNEL},
105
106
// TODO: There are a few swizzled mirrors of VRAM, not sure about the best way to
107
// implement those.
108
};
109
110
static const int num_views = sizeof(views) / sizeof(MemoryView);
111
112
inline static bool CanIgnoreView(const MemoryView &view) {
113
#ifdef MASKED_PSP_MEMORY
114
// Basically, 32-bit platforms can ignore views that are masked out anyway.
115
return (view.flags & MV_MIRROR_PREVIOUS) && (view.virtual_address & ~MEMVIEW32_MASK) != 0;
116
#else
117
return false;
118
#endif
119
}
120
121
#if PPSSPP_PLATFORM(IOS) && PPSSPP_ARCH(64BIT)
122
#define SKIP(a_flags, b_flags) \
123
if ((b_flags) & MV_KERNEL) \
124
continue;
125
#else
126
#define SKIP(a_flags, b_flags) \
127
;
128
#endif
129
130
static bool Memory_TryBase(u32 flags) {
131
// OK, we know where to find free space. Now grab it!
132
// We just mimic the popular BAT setup.
133
134
size_t position = 0;
135
size_t last_position = 0;
136
137
// Zero all the pointers to be sure.
138
for (int i = 0; i < num_views; i++) {
139
if (views[i].out_ptr)
140
*views[i].out_ptr = 0;
141
}
142
143
int i;
144
for (i = 0; i < num_views; i++) {
145
const MemoryView &view = views[i];
146
if (view.size == 0)
147
continue;
148
SKIP(flags, view.flags);
149
150
if (view.flags & MV_MIRROR_PREVIOUS) {
151
position = last_position;
152
}
153
#ifndef MASKED_PSP_MEMORY
154
*view.out_ptr = (u8*)g_arena.CreateView(
155
position, view.size, base + view.virtual_address);
156
if (!*view.out_ptr) {
157
ERROR_LOG(Log::MemMap, "Failed at view %d", i);
158
goto bail;
159
}
160
#else
161
if (CanIgnoreView(view)) {
162
// This is handled by address masking in 32-bit, no view needs to be created.
163
*view.out_ptr = *views[i - 1].out_ptr;
164
} else {
165
*view.out_ptr = (u8*)g_arena.CreateView(
166
position, view.size, base + (view.virtual_address & MEMVIEW32_MASK));
167
if (!*view.out_ptr) {
168
ERROR_LOG(Log::MemMap, "Failed at view %d", i);
169
goto bail;
170
}
171
}
172
#endif
173
last_position = position;
174
position += g_arena.roundup(view.size);
175
}
176
177
return true;
178
bail:
179
// Argh! ERROR! Free what we grabbed so far so we can try again.
180
for (int j = 0; j <= i; j++) {
181
if (views[i].size == 0)
182
continue;
183
SKIP(flags, views[i].flags);
184
if (views[j].out_ptr && *views[j].out_ptr) {
185
if (!CanIgnoreView(views[j])) {
186
g_arena.ReleaseView(0, *views[j].out_ptr, views[j].size);
187
}
188
*views[j].out_ptr = nullptr;
189
}
190
}
191
return false;
192
}
193
194
bool MemoryMap_Setup(u32 flags) {
195
#if PPSSPP_PLATFORM(UWP)
196
// We reserve the memory, then simply commit in TryBase.
197
base = (u8*)VirtualAllocFromApp(0, 0x10000000, MEM_RESERVE, PAGE_READWRITE);
198
#else
199
200
// Figure out how much memory we need to allocate in total.
201
size_t total_mem = 0;
202
for (int i = 0; i < num_views; i++) {
203
if (views[i].size == 0)
204
continue;
205
SKIP(flags, views[i].flags);
206
if (!CanIgnoreView(views[i]))
207
total_mem += g_arena.roundup(views[i].size);
208
}
209
210
// Grab some pagefile backed memory out of the void ...
211
if (!g_arena.GrabMemSpace(total_mem)) {
212
// It'll already have logged.
213
return false;
214
}
215
#endif
216
217
#if !PPSSPP_PLATFORM(ANDROID)
218
if (g_arena.NeedsProbing()) {
219
int base_attempts = 0;
220
#if PPSSPP_PLATFORM(WINDOWS) && PPSSPP_ARCH(32BIT)
221
// Try a whole range of possible bases. Return once we got a valid one.
222
uintptr_t max_base_addr = 0x7FFF0000 - 0x10000000;
223
uintptr_t min_base_addr = 0x01000000;
224
uintptr_t stride = 0x400000;
225
#elif PPSSPP_ARCH(ARM64) && PPSSPP_PLATFORM(IOS)
226
// iOS
227
uintptr_t max_base_addr = 0x1FFFF0000ULL - 0x80000000ULL;
228
uintptr_t min_base_addr = 0x100000000ULL;
229
uintptr_t stride = 0x800000;
230
#else
231
uintptr_t max_base_addr = 0;
232
uintptr_t min_base_addr = 0;
233
uintptr_t stride = 0;
234
ERROR_LOG(Log::MemMap, "MemoryMap_Setup: Hit a wrong path, should not be needed on this platform.");
235
return false;
236
#endif
237
for (uintptr_t base_addr = min_base_addr; base_addr < max_base_addr; base_addr += stride) {
238
base_attempts++;
239
base = (u8 *)base_addr;
240
if (Memory_TryBase(flags)) {
241
INFO_LOG(Log::MemMap, "Found valid memory base at %p after %i tries.", base, base_attempts);
242
return true;
243
}
244
}
245
ERROR_LOG(Log::MemMap, "MemoryMap_Setup: Failed finding a memory base.");
246
return false;
247
}
248
else
249
#endif
250
{
251
#if !PPSSPP_PLATFORM(UWP)
252
base = g_arena.Find4GBBase();
253
if (!base) {
254
return false;
255
}
256
#endif
257
}
258
259
// Should return true...
260
return Memory_TryBase(flags);
261
}
262
263
void MemoryMap_Shutdown(u32 flags) {
264
size_t position = 0;
265
size_t last_position = 0;
266
267
for (int i = 0; i < num_views; i++) {
268
if (views[i].size == 0)
269
continue;
270
SKIP(flags, views[i].flags);
271
272
if (views[i].flags & MV_MIRROR_PREVIOUS) {
273
position = last_position;
274
}
275
276
if (*views[i].out_ptr)
277
g_arena.ReleaseView(position, *views[i].out_ptr, views[i].size);
278
*views[i].out_ptr = nullptr;
279
280
last_position = position;
281
position += g_arena.roundup(views[i].size);
282
}
283
g_arena.ReleaseSpace();
284
285
#if PPSSPP_PLATFORM(UWP)
286
VirtualFree(base, 0, MEM_RELEASE);
287
#endif
288
}
289
290
bool Init() {
291
// On some 32 bit platforms (like Android, iOS, etc.), you can only map < 32 megs at a time.
292
const static int MAX_MMAP_SIZE = 31 * 1024 * 1024;
293
_dbg_assert_msg_(g_MemorySize <= MAX_MMAP_SIZE * 3, "ACK - too much memory for three mmap views.");
294
for (size_t i = 0; i < ARRAY_SIZE(views); i++) {
295
if (views[i].flags & MV_IS_PRIMARY_RAM)
296
views[i].size = std::min((int)g_MemorySize, MAX_MMAP_SIZE);
297
if (views[i].flags & MV_IS_EXTRA1_RAM)
298
views[i].size = std::min(std::max((int)g_MemorySize - MAX_MMAP_SIZE, 0), MAX_MMAP_SIZE);
299
if (views[i].flags & MV_IS_EXTRA2_RAM)
300
views[i].size = std::min(std::max((int)g_MemorySize - MAX_MMAP_SIZE * 2, 0), MAX_MMAP_SIZE);
301
}
302
303
int flags = 0;
304
if (!MemoryMap_Setup(flags)) {
305
return false;
306
}
307
308
INFO_LOG(Log::MemMap, "Memory system initialized. Base at %p (RAM at @ %p, uncached @ %p)",
309
base, m_pPhysicalRAM, m_pUncachedRAM);
310
311
MemFault_Init();
312
return true;
313
}
314
315
void Reinit() {
316
_assert_msg_(PSP_GetBootState() == BootState::Complete, "Cannot reinit during startup/shutdown");
317
Core_NotifyLifecycle(CoreLifecycle::MEMORY_REINITING);
318
Shutdown();
319
Init();
320
Core_NotifyLifecycle(CoreLifecycle::MEMORY_REINITED);
321
}
322
323
static void DoMemoryVoid(PointerWrap &p, uint32_t start, uint32_t size) {
324
uint8_t *d = GetPointerWrite(start);
325
uint8_t *&storage = *p.ptr;
326
327
// We only handle aligned data and sizes.
328
if ((size & 0x3F) != 0 || ((uintptr_t)d & 0x3F) != 0)
329
return p.DoVoid(d, size);
330
331
switch (p.mode) {
332
case PointerWrap::MODE_READ:
333
ParallelMemcpy(&g_threadManager, d, storage, size);
334
break;
335
case PointerWrap::MODE_WRITE:
336
ParallelMemcpy(&g_threadManager, storage, d, size);
337
break;
338
case PointerWrap::MODE_MEASURE:
339
// Nothing to do here.
340
break;
341
case PointerWrap::MODE_VERIFY:
342
ParallelRangeLoop(&g_threadManager, [&](int l, int h) {
343
for (int i = l; i < h; i++)
344
_dbg_assert_msg_(d[i] == storage[i], "Savestate verification failure: %d (0x%X) (at %p) != %d (0x%X) (at %p).\n", d[i], d[i], &d[i], storage[i], storage[i], &storage[i]);
345
}, 0, size, 128);
346
break;
347
case PointerWrap::MODE_NOOP:
348
break;
349
}
350
storage += size;
351
}
352
353
void DoState(PointerWrap &p) {
354
auto s = p.Section("Memory", 1, 3);
355
if (!s)
356
return;
357
358
if (s < 2) {
359
if (!g_RemasterMode)
360
g_MemorySize = RAM_NORMAL_SIZE;
361
g_PSPModel = PSP_MODEL_FAT;
362
} else if (s == 2) {
363
// In version 2, we determine memory size based on PSP model.
364
u32 oldMemorySize = g_MemorySize;
365
Do(p, g_PSPModel);
366
p.DoMarker("PSPModel");
367
if (!g_RemasterMode) {
368
g_MemorySize = g_PSPModel == PSP_MODEL_FAT ? RAM_NORMAL_SIZE : RAM_DOUBLE_SIZE;
369
if (oldMemorySize < g_MemorySize) {
370
Reinit();
371
}
372
}
373
} else {
374
// In version 3, we started just saving the memory size directly.
375
// It's no longer based strictly on the PSP model.
376
u32 oldMemorySize = g_MemorySize;
377
Do(p, g_PSPModel);
378
p.DoMarker("PSPModel");
379
Do(p, g_MemorySize);
380
if (oldMemorySize != g_MemorySize) {
381
Reinit();
382
}
383
}
384
385
DoMemoryVoid(p, PSP_GetKernelMemoryBase(), g_MemorySize);
386
p.DoMarker("RAM");
387
388
DoMemoryVoid(p, PSP_GetVidMemBase(), VRAM_SIZE);
389
p.DoMarker("VRAM");
390
DoArray(p, m_pPhysicalScratchPad, SCRATCHPAD_SIZE);
391
p.DoMarker("ScratchPad");
392
}
393
394
void Shutdown() {
395
std::lock_guard<std::recursive_mutex> guard(g_shutdownLock);
396
u32 flags = 0;
397
MemoryMap_Shutdown(flags);
398
base = nullptr;
399
DEBUG_LOG(Log::MemMap, "Memory system shut down.");
400
}
401
402
bool IsActive() {
403
return base != nullptr;
404
}
405
406
// Wanting to avoid include pollution, MemMap.h is included a lot.
407
MemoryInitedLock::MemoryInitedLock()
408
{
409
g_shutdownLock.lock();
410
}
411
MemoryInitedLock::~MemoryInitedLock()
412
{
413
g_shutdownLock.unlock();
414
}
415
416
MemoryInitedLock Lock()
417
{
418
return MemoryInitedLock();
419
}
420
421
static Opcode Read_Instruction(u32 address, bool resolveReplacements, Opcode inst) {
422
if (!MIPS_IS_EMUHACK(inst.encoding)) {
423
return inst;
424
}
425
426
// No mutex on jit access here, but we assume the caller has locked, if necessary.
427
if (MIPS_IS_RUNBLOCK(inst.encoding) && MIPSComp::jit) {
428
inst = MIPSComp::jit->GetOriginalOp(inst);
429
if (resolveReplacements && MIPS_IS_REPLACEMENT(inst)) {
430
u32 op;
431
if (GetReplacedOpAt(address, &op)) {
432
if (MIPS_IS_EMUHACK(op)) {
433
ERROR_LOG(Log::MemMap, "WTF 1");
434
return Opcode(op);
435
} else {
436
return Opcode(op);
437
}
438
} else {
439
ERROR_LOG(Log::MemMap, "Replacement, but no replacement op? %08x", inst.encoding);
440
}
441
}
442
return inst;
443
} else if (resolveReplacements && MIPS_IS_REPLACEMENT(inst.encoding)) {
444
u32 op;
445
if (GetReplacedOpAt(address, &op)) {
446
if (MIPS_IS_EMUHACK(op)) {
447
ERROR_LOG(Log::MemMap, "WTF 2");
448
return Opcode(op);
449
} else {
450
return Opcode(op);
451
}
452
} else {
453
return inst;
454
}
455
} else {
456
return inst;
457
}
458
}
459
460
Opcode Read_Instruction(u32 address, bool resolveReplacements) {
461
if (!IsValid4AlignedAddress(address)) {
462
// BAD!
463
_dbg_assert_(false);
464
return Opcode(0);
465
}
466
467
Opcode inst = Opcode(ReadUnchecked_U32(address));
468
return Read_Instruction(address, resolveReplacements, inst);
469
}
470
471
Opcode ReadUnchecked_Instruction(u32 address, bool resolveReplacements) {
472
_dbg_assert_((address & 3) == 0);
473
Opcode inst = Opcode(ReadUnchecked_U32(address));
474
return Read_Instruction(address, resolveReplacements, inst);
475
}
476
477
Opcode Read_Opcode_JIT(u32 address)
478
{
479
Opcode inst = Opcode(Read_U32(address));
480
// No mutex around jit access here, but we assume caller has if necessary.
481
if (MIPS_IS_RUNBLOCK(inst.encoding) && MIPSComp::jit) {
482
return MIPSComp::jit->GetOriginalOp(inst);
483
} else {
484
return inst;
485
}
486
}
487
488
// WARNING! No checks!
489
void Write_Opcode_JIT(const u32 address, const Opcode& _Value) {
490
_dbg_assert_((address & 3) == 0);
491
Memory::WriteUnchecked_U32(_Value.encoding, address);
492
}
493
494
void Memset(const u32 _Address, const u8 _iValue, const u32 _iLength, const char *tag) {
495
if (IsValidRange(_Address, _iLength)) {
496
uint8_t *ptr = GetPointerWriteUnchecked(_Address);
497
memset(ptr, _iValue, _iLength);
498
} else {
499
// TODO: This mainly seems to be produced by GPUCommon::PerformMemorySet, called from
500
// Replace_memset_jak(). Strangely, this managed to crash in Write_U8().
501
for (size_t i = 0; i < _iLength; i++) {
502
if (Memory::IsValidAddress(_Address + (u32)i)) {
503
WriteUnchecked_U8(_iValue, (u32)(_Address + i));
504
}
505
}
506
}
507
508
if (tag) {
509
NotifyMemInfo(MemBlockFlags::WRITE, _Address, _iLength, tag, strlen(tag));
510
}
511
}
512
513
} // namespace
514
515
void PSPPointerNotifyRW(int rw, uint32_t ptr, uint32_t bytes, const char * tag, size_t tagLen) {
516
if (MemBlockInfoDetailed(bytes)) {
517
if (rw & 1)
518
NotifyMemInfo(MemBlockFlags::WRITE, ptr, bytes, tag, tagLen);
519
if (rw & 2)
520
NotifyMemInfo(MemBlockFlags::READ, ptr, bytes, tag, tagLen);
521
}
522
}
523
524