Skip to content
Open
1 change: 1 addition & 0 deletions core/libs/prx/libSceAmpr/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ if(BUILD_TESTING)
target_link_libraries(guest_amm_placement_tests PRIVATE libSceAmpr libkernel libc)
configure_windows_unwind(guest_amm_placement_tests)
add_test(NAME guest_amm_placement COMMAND guest_amm_placement_tests)
set_tests_properties(guest_amm_placement PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
if(WIN32)
set_tests_properties(guest_amm_placement PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceAmpr>")
Expand Down
23 changes: 21 additions & 2 deletions core/libs/prx/libc/include/GuestArena.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
struct _EXCEPTION_POINTERS;
#endif

// Guest virtual memory is placed inside one reserved arena below the PS5 application map limit
// absolute address and breaks on host addresses outside that range.
namespace GuestArena {

#ifdef ANYPS5_ENABLE_ASAN
Expand All @@ -18,6 +16,13 @@ inline constexpr std::uintptr_t GuestAddressOffset = 0x0000100000000000ull;
inline constexpr std::uintptr_t GuestAddressOffset = 0;
#endif

#ifdef ANYPS5_ENABLE_TSAN
inline constexpr std::uintptr_t MapperWindowStart = 0x00007E8000000000ull;
#else
inline constexpr std::uintptr_t MapperWindowStart = 0x0000080000000000ull + GuestAddressOffset;
#endif
inline constexpr std::size_t MapperWindowBytes = std::size_t{512} << 30;

#ifndef _WIN32
using SharedBackingResolver = bool (*)(std::uintptr_t address, std::size_t bytes, int* file, std::uint64_t* offset);
using SharedBackingWriter = bool (*)(std::uintptr_t address, const void* source, std::size_t bytes);
Expand All @@ -43,6 +48,12 @@ void GuestArenaRelease_nid_postfix(const void* pointer, std::size_t bytes);
// The reserved range, and whether it was reserved with page write watching (Windows MEM_WRITE_WATCH).
void GuestArenaRange_nid_postfix(std::uintptr_t* base, std::size_t* bytes);
bool GuestArenaWriteWatched_nid_postfix();
void GuestArenaMapperWindow_nid_no_patch(std::uintptr_t* base, std::size_t* bytes, int* error);
bool GuestArenaMapperOnly_nid_no_patch(const void* pointer, std::size_t bytes);
void GuestArenaBeginMapperAccess_nid_no_patch();
void GuestArenaEndMapperAccess_nid_no_patch();
void GuestArenaRequireMapperAccess_nid_no_patch(const void* pointer, std::size_t bytes);
bool GuestArenaFixedTarget_nid_no_patch(const void* pointer, std::size_t bytes);
void GuestArenaSetProtection_nid_postfix(std::uintptr_t address, std::size_t bytes, std::uint32_t protection);
void GuestArenaCommit_nid_postfix(void* pointer, std::size_t bytes, std::uint32_t protection, std::size_t granule);
void GuestArenaReset_nid_postfix(void* pointer, std::size_t bytes);
Expand Down Expand Up @@ -123,6 +134,14 @@ class HostWrite {
bool open;
};

class MapperAccess {
public:
MapperAccess() { GuestArenaBeginMapperAccess_nid_no_patch(); }
~MapperAccess() { GuestArenaEndMapperAccess_nid_no_patch(); }
MapperAccess(const MapperAccess&) = delete;
MapperAccess& operator=(const MapperAccess&) = delete;
};

#ifdef _WIN32
class HostImportAccess {
public:
Expand Down
74 changes: 72 additions & 2 deletions core/libs/prx/libc/src/GuestArena.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "prx/libc/include/GuestArena.hpp"
#include "prx/libc/include/General.hpp"
#include "prx/libc/include/GuestWriteWatch.hpp"
#include "prx/libc/include/HostRegionIndex.hpp"
#include "prx/libc/include/WindowsMappings.hpp"
Expand Down Expand Up @@ -69,6 +70,13 @@ std::uintptr_t alignUp(std::uintptr_t value, std::size_t alignment) {
return (value + alignment - 1) & ~(static_cast<std::uintptr_t>(alignment) - 1);
}

bool Within(std::uintptr_t base, std::uintptr_t end, const void* pointer, std::size_t bytes) {
const auto address = reinterpret_cast<std::uintptr_t>(pointer);
return base != 0 && address >= base && bytes <= end - base && address - base <= (end - base) - bytes;
}

thread_local unsigned mapperAccessDepth = 0;

class Arena {
public:
static Arena& Get() {
Expand All @@ -81,10 +89,27 @@ class Arena {
}

bool Contains(const void* pointer, std::size_t bytes) const {
return Within(_base, _end, pointer, bytes) || InMapperWindow(pointer, bytes);
}

bool InUserWindow(const void* pointer, std::size_t bytes) const {
return Within(_base, _end, pointer, bytes);
}

bool InMapperWindow(const void* pointer, std::size_t bytes) const {
return Within(_mapperBase, _mapperEnd, pointer, bytes);
}

static bool OverlapsMapperWindow(const void* pointer, std::size_t bytes) {
const auto address = reinterpret_cast<std::uintptr_t>(pointer);
return _base != 0 && address >= _base && bytes <= _end - _base && address - _base <= (_end - _base) - bytes;
if (bytes > std::numeric_limits<std::uintptr_t>::max() - address || address >= MapperWindowStart + MapperWindowBytes) return false;
return bytes > MapperWindowStart - std::min(address, MapperWindowStart);
}

std::uintptr_t MapperBase() const { return _mapperBase; }
std::size_t MapperSize() const { return _mapperEnd - _mapperBase; }
int MapperError() const { return _mapperError; }

void* Allocate(std::size_t bytes, std::size_t alignment) {
return AllocateAtOrAbove(0, bytes, alignment);
}
Expand Down Expand Up @@ -231,9 +256,18 @@ class Arena {
for (const auto& [holeStart, holeEnd] : _holes) _used.emplace(holeStart, holeEnd);
_base = ArenaStart;
_end = end;
const bool mapperReserved = WindowsMappings::Get().Reserve(reinterpret_cast<void*>(MapperWindowStart), MapperWindowBytes) != nullptr;
RecordMapperWindow(mapperReserved, mapperReserved ? 0 : static_cast<int>(GetLastError()));
#endif
}

void RecordMapperWindow(bool reserved, int error) {
_mapperError = error;
if (!reserved) return;
_mapperBase = MapperWindowStart;
_mapperEnd = MapperWindowStart + MapperWindowBytes;
}

#if defined(__linux__)
static std::vector<std::pair<std::uintptr_t, std::uintptr_t>> HostMappings() {
std::vector<std::pair<std::uintptr_t, std::uintptr_t>> mappings;
Expand Down Expand Up @@ -303,6 +337,8 @@ class Arena {
ReserveFreeRanges();
_base = ArenaStart;
_end = ApplicationAreaEnd;
const int mapperError = ReserveNoReplace(MapperWindowStart, MapperWindowBytes);
RecordMapperWindow(mapperError == 0, mapperError);
}

static void TryReserve(std::vector<std::pair<std::uintptr_t, std::uintptr_t>>& occupied, std::uintptr_t from, std::uintptr_t to) {
Expand Down Expand Up @@ -417,6 +453,9 @@ class Arena {

std::uintptr_t _base = 0;
std::uintptr_t _end = 0;
std::uintptr_t _mapperBase = 0;
std::uintptr_t _mapperEnd = 0;
int _mapperError = 0;
std::uintptr_t _occupiedPrefixEnd = ArenaStart;
std::uintptr_t _occupiedDefaultPrefixEnd = DefaultAllocationStart;
bool _writeWatched = false;
Expand Down Expand Up @@ -501,6 +540,37 @@ void GuestArenaRange_nid_postfix(std::uintptr_t* base, std::size_t* bytes) {
*bytes = Arena::Get().Size();
}

void GuestArenaMapperWindow_nid_no_patch(std::uintptr_t* base, std::size_t* bytes, int* error) {
*base = Arena::Get().MapperBase();
*bytes = Arena::Get().MapperSize();
*error = Arena::Get().MapperError();
}

bool GuestArenaMapperOnly_nid_no_patch(const void* pointer, std::size_t bytes) {
return mapperAccessDepth == 0 && Arena::OverlapsMapperWindow(pointer, bytes);
}

void GuestArenaBeginMapperAccess_nid_no_patch() {
++mapperAccessDepth;
}

void GuestArenaEndMapperAccess_nid_no_patch() {
--mapperAccessDepth;
}

void GuestArenaRequireMapperAccess_nid_no_patch(const void* pointer, std::size_t bytes) {
if (!GuestArenaMapperOnly_nid_no_patch(pointer, bytes)) return;
char message[160];
std::snprintf(message, sizeof(message), "a title's fixed mapping 0x%llx+0x%zx inside the AMM virtual address range", static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(pointer)), bytes);
NotImplemented_nid_no_patch(message);
}

bool GuestArenaFixedTarget_nid_no_patch(const void* pointer, std::size_t bytes) {
GuestArenaRequireMapperAccess_nid_no_patch(pointer, bytes);
const auto& arena = Arena::Get();
return arena.InUserWindow(pointer, bytes) || (mapperAccessDepth != 0 && arena.InMapperWindow(pointer, bytes));
}

namespace {

std::invalid_argument OutsideArena(const char* operation, const void* pointer, std::size_t bytes) {
Expand Down Expand Up @@ -1024,7 +1094,7 @@ bool GuestArenaArmOwned_nid_no_patch(std::uintptr_t address, std::size_t bytes,
if (bytes == 0 || bytes > std::numeric_limits<std::uintptr_t>::max() - address) return false;
const auto first = address & ~std::uintptr_t{65535};
const auto last = (address + bytes - 1) | std::uintptr_t{65535};
if (last == std::numeric_limits<std::uintptr_t>::max() || !Arena::Get().Contains(reinterpret_cast<void*>(first), last + 1 - first) || Arena::Get().OverlapsHostRegion(first, last + 1 - first)) return false;
if (last == std::numeric_limits<std::uintptr_t>::max() || !Arena::Get().InUserWindow(reinterpret_cast<void*>(first), last + 1 - first) || Arena::Get().OverlapsHostRegion(first, last + 1 - first)) return false;
return WindowsMappings::Get().ArmOwned(address, bytes, words, count, flags);
#else
static_cast<void>(address);
Expand Down
1 change: 1 addition & 0 deletions core/libs/prx/libkernel/Apr/include/AprCommandBuffer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ inline std::optional<AmmProtectCommand> EncodeAmmProtect(Opcode opcode, std::uin
extern "C" {
int AmmGiveDirectMemory_nid_no_patch(std::int64_t searchStart, std::int64_t searchEnd, std::size_t size, std::size_t alignment, int usage, std::int64_t* offset);
void AmmVirtualAddressRanges_nid_no_patch(std::uint64_t* start, std::uint64_t* end, std::uint64_t* multimapStart, std::uint64_t* multimapEnd);
bool AmmClaimRelease_nid_no_patch(std::int64_t start, std::size_t bytes, bool requireAllocated);
std::uint32_t AmmSubmit_nid_no_patch(void* base, std::uint32_t bytes);
bool AmmSubmitted_nid_no_patch(std::uint32_t id);
}
Expand Down
73 changes: 60 additions & 13 deletions core/libs/prx/libkernel/Apr/src/Apr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -493,18 +493,19 @@ TCommand _read(const Apr::CommandBufferObject& buffer, std::uint32_t cursor) {
return command;
}

constexpr std::uint64_t AmmRangeBytes = 256ull << 30;
constexpr std::uint64_t AmmRangeBytes = 480ull << 30;
constexpr std::uint64_t AmmMultimapRangeBytes = 32ull << 30;
constexpr std::uint64_t AmmReservedBytes = AmmRangeBytes + AmmMultimapRangeBytes;
constexpr std::uint64_t AmmRangeAlignment = 64ull << 30;
constexpr int GuestMapFixed = 0x10;
constexpr int GuestMapNoOverwrite = 0x80;

static_assert(AmmPool::PageBytes == PS5_PAGE_SIZE);
static_assert(AmmReservedBytes == GuestArena::MapperWindowBytes);

using AmmPage = AmmPool::Page;

struct AmmState : AmmPool::Records {
std::mutex gift;
std::mutex lock;
std::uintptr_t base = 0;
std::set<std::uintptr_t> prt;
Expand All @@ -517,13 +518,17 @@ AmmState& _amm() {

std::uintptr_t _ammBase(AmmState& state) {
if (state.base == 0) {
std::uintptr_t arenaBase = 0;
std::size_t arenaBytes = 0;
GuestArena::GuestArenaRange_nid_postfix(&arenaBase, &arenaBytes);
if (arenaBase == 0 || arenaBytes < AmmReservedBytes) throw std::runtime_error("AMM: the guest address space arena cannot hold the virtual address range");
const auto top = GuestArena::GuestArenaHighestFree_nid_no_patch(AmmReservedBytes, AmmRangeAlignment);
if (top == 0) throw std::runtime_error("AMM: the guest address space arena has no free virtual address range");
void* address = reinterpret_cast<void*>(top);
std::uintptr_t windowBase = 0;
std::size_t windowBytes = 0;
int windowError = 0;
GuestArena::GuestArenaMapperWindow_nid_no_patch(&windowBase, &windowBytes, &windowError);
if (windowBase == 0 || windowBytes < AmmReservedBytes) {
char message[160];
std::snprintf(message, sizeof(message), "AMM: the host cannot reserve the AMM virtual address range at 0x%llx (OS error %d)", static_cast<unsigned long long>(GuestArena::MapperWindowStart), windowError);
throw std::runtime_error(message);
}
void* address = reinterpret_cast<void*>(windowBase);
const GuestArena::MapperAccess access;
if (DoReserveVirtual(&address, AmmReservedBytes, GuestMapFixed | GuestMapNoOverwrite, 0) != 0) throw std::runtime_error("AMM: cannot reserve the virtual address range");
state.base = reinterpret_cast<std::uintptr_t>(address);
}
Expand Down Expand Up @@ -603,11 +608,13 @@ std::vector<AmmPage> _mappedPages(AmmState& state, std::uint64_t address, std::u

void _reserve(std::uint64_t address, std::uint64_t size) {
void* target = reinterpret_cast<void*>(address);
const GuestArena::MapperAccess access;
if (DoReserveVirtual(&target, size, GuestMapFixed, 0) != 0) throw std::runtime_error("AMM: cannot return the range to the reservation");
}

void _mapRun(std::uint64_t address, std::uint64_t physical, std::uint64_t size, std::int32_t protection) {
void* target = reinterpret_cast<void*>(address);
const GuestArena::MapperAccess access;
if (DoMapDirect(&target, size, _ammHostProtection(protection), GuestMapFixed, static_cast<std::int64_t>(physical), 0) != 0) throw std::runtime_error("AMM: map failed");
}

Expand All @@ -634,6 +641,7 @@ void _requirePrt(AmmState& state, std::uint64_t address, std::uint64_t size) {
void _zeroPrt(std::uint64_t address, std::uint64_t size) {
constexpr int GpuRead = 0x10;
void* target = reinterpret_cast<void*>(address);
const GuestArena::MapperAccess access;
if (DoMapZero(&target, size, GpuRead, GuestMapFixed) != 0) throw std::runtime_error("AMM: cannot map the unbacked PRT pages");
}

Expand Down Expand Up @@ -681,6 +689,7 @@ void _ammAllocatePrt(const Apr::AmmProtectCommand& command) {
entry.type = command.type;
entry.protection = command.protection;
}
const GuestArena::MapperAccess access;
if (DoMprotect(reinterpret_cast<void*>(address), bytes, _ammHostProtection(command.protection)) != 0) throw std::runtime_error("AMM: protection change failed");
} else {
try {
Expand Down Expand Up @@ -757,6 +766,7 @@ void _ammProtect(const Apr::AmmProtectCommand& command, bool type) {
const int host = _ammHostProtection(pages[first].protection);
std::size_t last = first + 1;
while (last < pages.size() && _ammHostProtection(pages[last].protection) == host) ++last;
const GuestArena::MapperAccess access;
if (DoMprotect(reinterpret_cast<void*>(command.address + first * PS5_PAGE_SIZE), (last - first) * PS5_PAGE_SIZE, host) != 0) throw std::runtime_error("AMM: protection change failed");
first = last;
}
Expand Down Expand Up @@ -929,12 +939,24 @@ std::optional<Deferred> _execute(const Apr::CommandBufferObject& buffer, int& st
extern "C" {

int AmmGiveDirectMemory_nid_no_patch(std::int64_t searchStart, std::int64_t searchEnd, std::size_t size, std::size_t alignment, int usage, std::int64_t* offset) {
if (!offset || (usage != 0 && usage != 1)) return SCE_KERNEL_ERROR_EINVAL;
const int result = sceKernelAllocateDirectMemory(searchStart, searchEnd, size, alignment, 0, offset);
if (result != 0 || usage == 0) return result;
if (usage != 0 && usage != 1) return SCE_KERNEL_ERROR_EINVAL;
if (!DirectMemoryAllocationValid(searchStart, searchEnd, size, alignment, offset)) return SCE_KERNEL_ERROR_EINVAL;
auto& state = _amm();
const std::lock_guard gift(state.gift);
if (usage == 1) {
const std::lock_guard lock(state.lock);
_ammBase(state);
}
std::int64_t physical = 0;
const int result = sceKernelAllocateDirectMemory(searchStart, searchEnd, size, alignment, 0, &physical);
if (result != 0) return result;
if (!GuestCopyOut_nid_no_patch(offset, &physical, sizeof(physical))) {
DirectMemoryFree(physical, size);
return SCE_KERNEL_ERROR_EFAULT;
}
if (usage == 0) return 0;
const std::lock_guard lock(state.lock);
_returnPoolPages(state, static_cast<std::uint64_t>(*offset), size);
_returnPoolPages(state, static_cast<std::uint64_t>(physical), size);
return 0;
}

Expand All @@ -948,6 +970,31 @@ void AmmVirtualAddressRanges_nid_no_patch(std::uint64_t* start, std::uint64_t* e
if (multimapEnd) *multimapEnd = base + AmmReservedBytes;
}

bool AmmClaimRelease_nid_no_patch(std::int64_t start, std::size_t bytes, bool requireAllocated) {
auto& state = _amm();
const auto first = static_cast<std::uint64_t>(start);
const auto end = first + bytes;
for (;;) {
{
const std::lock_guard gift(state.gift);
{
const std::lock_guard lock(state.lock);
const auto run = state.pool.upper_bound(first);
const bool free = (run != state.pool.begin() && std::prev(run)->first + std::prev(run)->second > first) || (run != state.pool.end() && run->first < end);
const auto used = state.pooledUses.lower_bound(first);
if (free || (used != state.pooledUses.end() && used->first < end)) {
char message[128];
std::snprintf(message, sizeof(message), "releasing direct memory 0x%llx+0x%llx given to the AMM pool", static_cast<unsigned long long>(first), static_cast<unsigned long long>(bytes));
NotImplemented_nid_no_patch(message);
}
}
const auto claim = DirectMemoryTryClaimRelease(start, bytes, requireAllocated);
if (claim != DirectMemoryReleaseClaim::Busy) return claim == DirectMemoryReleaseClaim::Claimed;
}
if (DirectMemoryAwaitReleaseClaim(start, bytes, requireAllocated) == DirectMemoryReleaseClaim::Refused) return false;
}
}

struct AprQueue {
std::mutex submit;
std::mutex mutex;
Expand Down
Loading
Loading