CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/Core/MemMap.cpp
Views: 1401
// Copyright (C) 2003 Dolphin Project / 2012 PPSSPP Project12// This program is free software: you can redistribute it and/or modify3// it under the terms of the GNU General Public License as published by4// the Free Software Foundation, version 2.0 or later versions.56// This program is distributed in the hope that it will be useful,7// but WITHOUT ANY WARRANTY; without even the implied warranty of8// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9// GNU General Public License 2.0 for more details.1011// A copy of the GPL 2.0 should have been included with the program.12// If not, see http://www.gnu.org/licenses/1314// Official git repository and contact information can be found at15// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.1617#include "ppsspp_config.h"1819#if PPSSPP_PLATFORM(UWP)20#include "Common/CommonWindows.h"21#endif2223#include <algorithm>24#include <mutex>2526#include "Common/Common.h"27#include "Common/MemoryUtil.h"28#include "Common/MemArena.h"29#include "Common/Serialize/Serializer.h"30#include "Common/Serialize/SerializeFuncs.h"3132#include "Core/Core.h"33#include "Core/Config.h"34#include "Core/ConfigValues.h"35#include "Core/Debugger/SymbolMap.h"36#include "Core/Debugger/MemBlockInfo.h"37#include "Core/HDRemaster.h"38#include "Core/HLE/HLE.h"39#include "Core/HLE/ReplaceTables.h"40#include "Core/MemMap.h"41#include "Core/MemFault.h"42#include "Core/MIPS/MIPS.h"43#include "Core/MIPS/JitCommon/JitBlockCache.h"44#include "Core/MIPS/JitCommon/JitCommon.h"45#include "Common/Thread/ParallelLoop.h"4647namespace Memory {4849// The base pointer to the auto-mirrored arena.50u8* base = nullptr;5152// The MemArena class53MemArena g_arena;54// ==============5556u8 *m_pPhysicalScratchPad;57u8 *m_pUncachedScratchPad;58// 64-bit: Pointers to high-mem mirrors59// 32-bit: Same as above60u8 *m_pPhysicalRAM[3];61u8 *m_pUncachedRAM[3];62u8 *m_pKernelRAM[3]; // RAM mirrored up to "kernel space". Fully accessible at all times currently.63// Technically starts at 0xA0000000, which we don't properly support (but we don't really support kernel code.)64// This matches how we handle 32-bit masking.65u8 *m_pUncachedKernelRAM[3];6667// VRAM is mirrored 4 times. The second and fourth mirrors are swizzled.68// In practice, a game accessing the mirrors most likely is deswizzling the depth buffer.69u8 *m_pPhysicalVRAM[4];70u8 *m_pUncachedVRAM[4];7172// Holds the ending address of the PSP's user space.73// Required for HD Remasters to work properly.74// This replaces RAM_NORMAL_SIZE at runtime.75u32 g_MemorySize;76// Used to store the PSP model on game startup.77u32 g_PSPModel;7879std::recursive_mutex g_shutdownLock;8081// We don't declare the IO region in here since its handled by other means.82static MemoryView views[] =83{84{&m_pPhysicalScratchPad, 0x00010000, SCRATCHPAD_SIZE, 0},85{&m_pUncachedScratchPad, 0x40010000, SCRATCHPAD_SIZE, MV_MIRROR_PREVIOUS},86{&m_pPhysicalVRAM[0], 0x04000000, 0x00200000, 0},87{&m_pPhysicalVRAM[1], 0x04200000, 0x00200000, MV_MIRROR_PREVIOUS},88{&m_pPhysicalVRAM[2], 0x04400000, 0x00200000, MV_MIRROR_PREVIOUS},89{&m_pPhysicalVRAM[3], 0x04600000, 0x00200000, MV_MIRROR_PREVIOUS},90{&m_pUncachedVRAM[0], 0x44000000, 0x00200000, MV_MIRROR_PREVIOUS},91{&m_pUncachedVRAM[1], 0x44200000, 0x00200000, MV_MIRROR_PREVIOUS},92{&m_pUncachedVRAM[2], 0x44400000, 0x00200000, MV_MIRROR_PREVIOUS},93{&m_pUncachedVRAM[3], 0x44600000, 0x00200000, MV_MIRROR_PREVIOUS},94{&m_pPhysicalRAM[0], 0x08000000, g_MemorySize, MV_IS_PRIMARY_RAM}, // only from 0x08800000 is it usable (last 24 megs)95{&m_pUncachedRAM[0], 0x48000000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_PRIMARY_RAM},96{&m_pKernelRAM[0], 0x88000000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_PRIMARY_RAM | MV_KERNEL},97{&m_pUncachedKernelRAM[0],0xC8000000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_PRIMARY_RAM | MV_KERNEL},98// Starts at memory + 31 MB.99{&m_pPhysicalRAM[1], 0x09F00000, g_MemorySize, MV_IS_EXTRA1_RAM},100{&m_pUncachedRAM[1], 0x49F00000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_EXTRA1_RAM},101{&m_pKernelRAM[1], 0x89F00000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_EXTRA1_RAM | MV_KERNEL},102{&m_pUncachedKernelRAM[1],0xC9F00000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_EXTRA1_RAM | MV_KERNEL},103// Starts at memory + 31 * 2 MB.104{&m_pPhysicalRAM[2], 0x0BE00000, g_MemorySize, MV_IS_EXTRA2_RAM},105{&m_pUncachedRAM[2], 0x4BE00000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_EXTRA2_RAM},106{&m_pKernelRAM[2], 0x8BE00000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_EXTRA2_RAM | MV_KERNEL},107{&m_pUncachedKernelRAM[2],0xCBE00000, g_MemorySize, MV_MIRROR_PREVIOUS | MV_IS_EXTRA2_RAM | MV_KERNEL},108109// TODO: There are a few swizzled mirrors of VRAM, not sure about the best way to110// implement those.111};112113static const int num_views = sizeof(views) / sizeof(MemoryView);114115inline static bool CanIgnoreView(const MemoryView &view) {116#ifdef MASKED_PSP_MEMORY117// Basically, 32-bit platforms can ignore views that are masked out anyway.118return (view.flags & MV_MIRROR_PREVIOUS) && (view.virtual_address & ~MEMVIEW32_MASK) != 0;119#else120return false;121#endif122}123124#if PPSSPP_PLATFORM(IOS) && PPSSPP_ARCH(64BIT)125#define SKIP(a_flags, b_flags) \126if ((b_flags) & MV_KERNEL) \127continue;128#else129#define SKIP(a_flags, b_flags) \130;131#endif132133static bool Memory_TryBase(u32 flags) {134// OK, we know where to find free space. Now grab it!135// We just mimic the popular BAT setup.136137size_t position = 0;138size_t last_position = 0;139140// Zero all the pointers to be sure.141for (int i = 0; i < num_views; i++) {142if (views[i].out_ptr)143*views[i].out_ptr = 0;144}145146int i;147for (i = 0; i < num_views; i++) {148const MemoryView &view = views[i];149if (view.size == 0)150continue;151SKIP(flags, view.flags);152153if (view.flags & MV_MIRROR_PREVIOUS) {154position = last_position;155}156#ifndef MASKED_PSP_MEMORY157*view.out_ptr = (u8*)g_arena.CreateView(158position, view.size, base + view.virtual_address);159if (!*view.out_ptr) {160goto bail;161DEBUG_LOG(Log::MemMap, "Failed at view %d", i);162}163#else164if (CanIgnoreView(view)) {165// This is handled by address masking in 32-bit, no view needs to be created.166*view.out_ptr = *views[i - 1].out_ptr;167} else {168*view.out_ptr = (u8*)g_arena.CreateView(169position, view.size, base + (view.virtual_address & MEMVIEW32_MASK));170if (!*view.out_ptr) {171DEBUG_LOG(Log::MemMap, "Failed at view %d", i);172goto bail;173}174}175#endif176last_position = position;177position += g_arena.roundup(view.size);178}179180return true;181bail:182// Argh! ERROR! Free what we grabbed so far so we can try again.183for (int j = 0; j <= i; j++) {184if (views[i].size == 0)185continue;186SKIP(flags, views[i].flags);187if (*views[j].out_ptr) {188if (!CanIgnoreView(views[j])) {189g_arena.ReleaseView(0, *views[j].out_ptr, views[j].size);190}191*views[j].out_ptr = NULL;192}193}194return false;195}196197bool MemoryMap_Setup(u32 flags) {198#if PPSSPP_PLATFORM(UWP)199// We reserve the memory, then simply commit in TryBase.200base = (u8*)VirtualAllocFromApp(0, 0x10000000, MEM_RESERVE, PAGE_READWRITE);201#else202203// Figure out how much memory we need to allocate in total.204size_t total_mem = 0;205for (int i = 0; i < num_views; i++) {206if (views[i].size == 0)207continue;208SKIP(flags, views[i].flags);209if (!CanIgnoreView(views[i]))210total_mem += g_arena.roundup(views[i].size);211}212213// Grab some pagefile backed memory out of the void ...214if (!g_arena.GrabMemSpace(total_mem)) {215// It'll already have logged.216return false;217}218#endif219220#if !PPSSPP_PLATFORM(ANDROID)221if (g_arena.NeedsProbing()) {222int base_attempts = 0;223#if PPSSPP_PLATFORM(WINDOWS) && PPSSPP_ARCH(32BIT)224// Try a whole range of possible bases. Return once we got a valid one.225uintptr_t max_base_addr = 0x7FFF0000 - 0x10000000;226uintptr_t min_base_addr = 0x01000000;227uintptr_t stride = 0x400000;228#elif PPSSPP_ARCH(ARM64) && PPSSPP_PLATFORM(IOS)229// iOS230uintptr_t max_base_addr = 0x1FFFF0000ULL - 0x80000000ULL;231uintptr_t min_base_addr = 0x100000000ULL;232uintptr_t stride = 0x800000;233#else234uintptr_t max_base_addr = 0;235uintptr_t min_base_addr = 0;236uintptr_t stride = 0;237ERROR_LOG(Log::MemMap, "MemoryMap_Setup: Hit a wrong path, should not be needed on this platform.");238return false;239#endif240for (uintptr_t base_addr = min_base_addr; base_addr < max_base_addr; base_addr += stride) {241base_attempts++;242base = (u8 *)base_addr;243if (Memory_TryBase(flags)) {244INFO_LOG(Log::MemMap, "Found valid memory base at %p after %i tries.", base, base_attempts);245return true;246}247}248ERROR_LOG(Log::MemMap, "MemoryMap_Setup: Failed finding a memory base.");249return false;250}251else252#endif253{254#if !PPSSPP_PLATFORM(UWP)255base = g_arena.Find4GBBase();256if (!base) {257return false;258}259#endif260}261262// Should return true...263return Memory_TryBase(flags);264}265266void MemoryMap_Shutdown(u32 flags) {267size_t position = 0;268size_t last_position = 0;269270for (int i = 0; i < num_views; i++) {271if (views[i].size == 0)272continue;273SKIP(flags, views[i].flags);274275if (views[i].flags & MV_MIRROR_PREVIOUS) {276position = last_position;277}278279if (*views[i].out_ptr)280g_arena.ReleaseView(position, *views[i].out_ptr, views[i].size);281*views[i].out_ptr = nullptr;282283last_position = position;284position += g_arena.roundup(views[i].size);285}286g_arena.ReleaseSpace();287288#if PPSSPP_PLATFORM(UWP)289VirtualFree(base, 0, MEM_RELEASE);290#endif291}292293bool Init() {294// On some 32 bit platforms (like Android, iOS, etc.), you can only map < 32 megs at a time.295const static int MAX_MMAP_SIZE = 31 * 1024 * 1024;296_dbg_assert_msg_(g_MemorySize <= MAX_MMAP_SIZE * 3, "ACK - too much memory for three mmap views.");297for (size_t i = 0; i < ARRAY_SIZE(views); i++) {298if (views[i].flags & MV_IS_PRIMARY_RAM)299views[i].size = std::min((int)g_MemorySize, MAX_MMAP_SIZE);300if (views[i].flags & MV_IS_EXTRA1_RAM)301views[i].size = std::min(std::max((int)g_MemorySize - MAX_MMAP_SIZE, 0), MAX_MMAP_SIZE);302if (views[i].flags & MV_IS_EXTRA2_RAM)303views[i].size = std::min(std::max((int)g_MemorySize - MAX_MMAP_SIZE * 2, 0), MAX_MMAP_SIZE);304}305306int flags = 0;307if (!MemoryMap_Setup(flags)) {308return false;309}310311INFO_LOG(Log::MemMap, "Memory system initialized. Base at %p (RAM at @ %p, uncached @ %p)",312base, m_pPhysicalRAM, m_pUncachedRAM);313314MemFault_Init();315return true;316}317318void Reinit() {319_assert_msg_(PSP_IsInited(), "Cannot reinit during startup/shutdown");320Core_NotifyLifecycle(CoreLifecycle::MEMORY_REINITING);321Shutdown();322Init();323Core_NotifyLifecycle(CoreLifecycle::MEMORY_REINITED);324}325326static void DoMemoryVoid(PointerWrap &p, uint32_t start, uint32_t size) {327uint8_t *d = GetPointerWrite(start);328uint8_t *&storage = *p.ptr;329330// We only handle aligned data and sizes.331if ((size & 0x3F) != 0 || ((uintptr_t)d & 0x3F) != 0)332return p.DoVoid(d, size);333334switch (p.mode) {335case PointerWrap::MODE_READ:336ParallelMemcpy(&g_threadManager, d, storage, size);337break;338case PointerWrap::MODE_WRITE:339ParallelMemcpy(&g_threadManager, storage, d, size);340break;341case PointerWrap::MODE_MEASURE:342// Nothing to do here.343break;344case PointerWrap::MODE_VERIFY:345ParallelRangeLoop(&g_threadManager, [&](int l, int h) {346for (int i = l; i < h; i++)347_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]);348}, 0, size, 128);349break;350case PointerWrap::MODE_NOOP:351break;352}353storage += size;354}355356void DoState(PointerWrap &p) {357auto s = p.Section("Memory", 1, 3);358if (!s)359return;360361if (s < 2) {362if (!g_RemasterMode)363g_MemorySize = RAM_NORMAL_SIZE;364g_PSPModel = PSP_MODEL_FAT;365} else if (s == 2) {366// In version 2, we determine memory size based on PSP model.367u32 oldMemorySize = g_MemorySize;368Do(p, g_PSPModel);369p.DoMarker("PSPModel");370if (!g_RemasterMode) {371g_MemorySize = g_PSPModel == PSP_MODEL_FAT ? RAM_NORMAL_SIZE : RAM_DOUBLE_SIZE;372if (oldMemorySize < g_MemorySize) {373Reinit();374}375}376} else {377// In version 3, we started just saving the memory size directly.378// It's no longer based strictly on the PSP model.379u32 oldMemorySize = g_MemorySize;380Do(p, g_PSPModel);381p.DoMarker("PSPModel");382Do(p, g_MemorySize);383if (oldMemorySize != g_MemorySize) {384Reinit();385}386}387388DoMemoryVoid(p, PSP_GetKernelMemoryBase(), g_MemorySize);389p.DoMarker("RAM");390391DoMemoryVoid(p, PSP_GetVidMemBase(), VRAM_SIZE);392p.DoMarker("VRAM");393DoArray(p, m_pPhysicalScratchPad, SCRATCHPAD_SIZE);394p.DoMarker("ScratchPad");395}396397void Shutdown() {398std::lock_guard<std::recursive_mutex> guard(g_shutdownLock);399u32 flags = 0;400MemoryMap_Shutdown(flags);401base = nullptr;402DEBUG_LOG(Log::MemMap, "Memory system shut down.");403}404405bool IsActive() {406return base != nullptr;407}408409// Wanting to avoid include pollution, MemMap.h is included a lot.410MemoryInitedLock::MemoryInitedLock()411{412g_shutdownLock.lock();413}414MemoryInitedLock::~MemoryInitedLock()415{416g_shutdownLock.unlock();417}418419MemoryInitedLock Lock()420{421return MemoryInitedLock();422}423424__forceinline static Opcode Read_Instruction(u32 address, bool resolveReplacements, Opcode inst)425{426if (!MIPS_IS_EMUHACK(inst.encoding)) {427return inst;428}429430// No mutex on jit access here, but we assume the caller has locked, if necessary.431if (MIPS_IS_RUNBLOCK(inst.encoding) && MIPSComp::jit) {432inst = MIPSComp::jit->GetOriginalOp(inst);433if (resolveReplacements && MIPS_IS_REPLACEMENT(inst)) {434u32 op;435if (GetReplacedOpAt(address, &op)) {436if (MIPS_IS_EMUHACK(op)) {437ERROR_LOG(Log::MemMap, "WTF 1");438return Opcode(op);439} else {440return Opcode(op);441}442} else {443ERROR_LOG(Log::MemMap, "Replacement, but no replacement op? %08x", inst.encoding);444}445}446return inst;447} else if (resolveReplacements && MIPS_IS_REPLACEMENT(inst.encoding)) {448u32 op;449if (GetReplacedOpAt(address, &op)) {450if (MIPS_IS_EMUHACK(op)) {451ERROR_LOG(Log::MemMap, "WTF 2");452return Opcode(op);453} else {454return Opcode(op);455}456} else {457return inst;458}459} else {460return inst;461}462}463464Opcode Read_Instruction(u32 address, bool resolveReplacements)465{466Opcode inst = Opcode(Read_U32(address));467return Read_Instruction(address, resolveReplacements, inst);468}469470Opcode ReadUnchecked_Instruction(u32 address, bool resolveReplacements)471{472Opcode inst = Opcode(ReadUnchecked_U32(address));473return Read_Instruction(address, resolveReplacements, inst);474}475476Opcode Read_Opcode_JIT(u32 address)477{478Opcode inst = Opcode(Read_U32(address));479// No mutex around jit access here, but we assume caller has if necessary.480if (MIPS_IS_RUNBLOCK(inst.encoding) && MIPSComp::jit) {481return MIPSComp::jit->GetOriginalOp(inst);482} else {483return inst;484}485}486487// WARNING! No checks!488// We assume that _Address is cached489void Write_Opcode_JIT(const u32 _Address, const Opcode& _Value)490{491Memory::WriteUnchecked_U32(_Value.encoding, _Address);492}493494void Memset(const u32 _Address, const u8 _iValue, const u32 _iLength, const char *tag) {495if (IsValidRange(_Address, _iLength)) {496uint8_t *ptr = GetPointerWriteUnchecked(_Address);497memset(ptr, _iValue, _iLength);498} else {499for (size_t i = 0; i < _iLength; i++)500Write_U8(_iValue, (u32)(_Address + i));501}502503NotifyMemInfo(MemBlockFlags::WRITE, _Address, _iLength, tag, strlen(tag));504}505506} // namespace507508void PSPPointerNotifyRW(int rw, uint32_t ptr, uint32_t bytes, const char * tag, size_t tagLen) {509if (MemBlockInfoDetailed(bytes)) {510if (rw & 1)511NotifyMemInfo(MemBlockFlags::WRITE, ptr, bytes, tag, tagLen);512if (rw & 2)513NotifyMemInfo(MemBlockFlags::READ, ptr, bytes, tag, tagLen);514}515}516517518