Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions core/libs/prx/libkernel/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2734,6 +2734,13 @@ add_test_executable(guest_thermal_sensors_tests ${LIBS_INCLUDE_DIR}/tests/GuestT
add_test(NAME guest_direct_memory_pages_${pages} COMMAND guest_memory_tests direct-pages)
set_tests_properties(guest_direct_memory_pages_${pages} PROPERTIES ENVIRONMENT "KYTY_DIRECT_MEMORY_PAGES=${pages}" SKIP_RETURN_CODE 77)
endforeach()
elseif(WIN32)
foreach(pages populate demand)
add_test(NAME guest_direct_memory_pages_${pages} COMMAND guest_memory_tests direct-pages)
set_tests_properties(guest_direct_memory_pages_${pages} PROPERTIES ENVIRONMENT "KYTY_DIRECT_MEMORY_PAGES=${pages}")
endforeach()
add_test(NAME guest_direct_memory_pages_changing COMMAND guest_memory_tests direct-pages-changing)
set_tests_properties(guest_direct_memory_pages_changing PROPERTIES ENVIRONMENT "KYTY_DIRECT_MEMORY_PAGES=populate" TIMEOUT 120)
endif()
if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
add_test(NAME guest_mmap_executable COMMAND guest_memory_tests executable-mappings)
Expand Down
66 changes: 66 additions & 0 deletions core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
#include <sys/mman.h>
#include <unistd.h>
#else
#include <thread>
#include <windows.h>
#include "prx/libc/include/WindowsDescriptor.hpp"

Expand Down Expand Up @@ -1943,10 +1944,75 @@ int MapDirectRecorded(void** addr, size_t len, int prot, int flags, int64_t phys
return 0;
}

#if defined(_WIN32) && defined(ANYPS5_KYTY)
static bool PopulatesDirectMappings() {
static const bool populates = [] {
const char* value = std::getenv("KYTY_DIRECT_MEMORY_PAGES");
const std::string_view text{value == nullptr ? "populate" : value};
if (text == "demand") {
std::fprintf(stderr, "[memory] direct memory: 4 KiB pages on demand, as KYTY_DIRECT_MEMORY_PAGES asks\n");
return false;
}
if (text == "private") throw std::runtime_error("KYTY_DIRECT_MEMORY_PAGES=private: the private tmpfs needs a Linux host");
if (text != "populate") throw std::invalid_argument("KYTY_DIRECT_MEMORY_PAGES must be private, populate or demand");
std::fprintf(stderr, "[memory] direct memory: mappings populated when they are made while the host has room%s\n", value != nullptr ? ", as KYTY_DIRECT_MEMORY_PAGES asks" : "");
return true;
}();
return populates;
}

static bool HostKeepsResident(std::size_t bytes) {
MEMORYSTATUSEX status{};
status.dwLength = sizeof(status);
return GlobalMemoryStatusEx(&status) != 0 && status.ullAvailPhys >= bytes + status.ullTotalPhys / 4;
}

static bool TouchPages(std::uintptr_t start, std::uintptr_t end, std::size_t pageBytes) {
for (auto page = start; page < end; page += pageBytes) {
std::uint8_t byte = 0;
SIZE_T read = 0;
if (ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<const void*>(page), &byte, 1, &read) == 0 || read != 1) return false;
}
return true;
}

static void PopulateDirectMapping(std::uintptr_t address, std::size_t bytes) {
if (!PopulatesDirectMappings()) return;
if (!HostKeepsResident(bytes)) {
static std::once_flag noted;
std::call_once(noted, [bytes] { std::fprintf(stderr, "[memory] direct memory of %zu MiB and later mappings that do not fit in a quarter of host memory stay paged on demand\n", bytes >> 20); });
return;
}
SYSTEM_INFO system{};
GetSystemInfo(&system);
const std::size_t pageBytes = system.dwPageSize;
constexpr std::size_t chunkBytes = std::size_t{256} << 20;
const auto chunks = (bytes + chunkBytes - 1) / chunkBytes;
const auto workers = std::min<std::size_t>(chunks, std::max(1u, std::thread::hardware_concurrency()));
std::atomic<std::size_t> next{0};
std::atomic<bool> stopped{false};
const auto populate = [&] {
for (auto chunk = next++; chunk < chunks && !stopped.load(std::memory_order_relaxed); chunk = next++) {
const auto first = address + chunk * chunkBytes;
if (!TouchPages(first, first + std::min(chunkBytes, bytes - chunk * chunkBytes), pageBytes)) stopped.store(true, std::memory_order_relaxed);
}
};
std::vector<std::thread> threads;
try {
for (std::size_t worker = 1; worker < workers; ++worker) threads.emplace_back(populate);
} catch (const std::system_error&) {
}
populate();
for (auto& thread : threads) thread.join();
}
#endif

int DoMapDirect(void** addr, size_t len, int prot, int flags, int64_t physStart, size_t alignment) {
const int result = MapDirectRecorded(addr, len, prot, flags, physStart, alignment);
#if defined(__linux__) && defined(ANYPS5_KYTY)
if (result == 0) PopulateDirectMapping(reinterpret_cast<std::uintptr_t>(*addr), len, LinuxProtFromSce(prot));
#elif defined(_WIN32) && defined(ANYPS5_KYTY)
if (result == 0) PopulateDirectMapping(reinterpret_cast<std::uintptr_t>(*addr), len);
#endif
return result;
}
Expand Down
62 changes: 61 additions & 1 deletion core/libs/tests/GuestMemory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,63 @@ static int CheckDirectMemoryPages() {
}
#endif

#if defined(_WIN32) && defined(ANYPS5_KYTY)
static bool HostHasRoomFor(std::size_t bytes) {
MEMORYSTATUSEX status{};
status.dwLength = sizeof(status);
return GlobalMemoryStatusEx(&status) != 0 && status.ullAvailPhys >= bytes + status.ullTotalPhys / 2;
}

static int CheckDirectMemoryPages() {
const char* requested = std::getenv("KYTY_DIRECT_MEMORY_PAGES");
Require(requested != nullptr);
const std::string mode{requested};
constexpr std::size_t length = 0x400000;
std::int64_t physical = 0;
Require(sceKernelAllocateDirectMemory(0, 0x7fffffffffll, length, 0x200000, 0, &physical) == 0);
void* mapping = nullptr;
Require(sceKernelMapDirectMemory(&mapping, length, 3, 0, physical, 0x200000) == 0);
SYSTEM_INFO system{};
GetSystemInfo(&system);
const std::size_t pageBytes = system.dwPageSize;
std::vector<PSAPI_WORKING_SET_EX_INFORMATION> pages(length / pageBytes);
for (std::size_t index = 0; index < pages.size(); ++index) pages[index].VirtualAddress = static_cast<char*>(mapping) + index * pageBytes;
Require(K32QueryWorkingSetEx(GetCurrentProcess(), pages.data(), static_cast<DWORD>(pages.size() * sizeof(pages[0]))) != 0);
const auto residentPages = std::count_if(pages.begin(), pages.end(), [](const PSAPI_WORKING_SET_EX_INFORMATION& page) { return page.VirtualAttributes.Valid != 0; });
if (mode == "demand") Require(residentPages == 0);
if (mode == "populate") Require(!HostHasRoomFor(length) || residentPages == static_cast<long>(pages.size()));
Require(sceKernelMunmap(reinterpret_cast<std::uint64_t>(mapping), length) == 0);
Require(sceKernelReleaseDirectMemory(physical, length) == 0);
return 0;
}

static int CheckDirectMemoryPagesWhileMappingsChange() {
constexpr std::size_t length = 0x4000000;
std::int64_t physical = 0;
Require(sceKernelAllocateDirectMemory(0, 0x7fffffffffll, length, 0x200000, 0, &physical) == 0);
void* mapping = nullptr;
Require(sceKernelMapDirectMemory(&mapping, length, 3, 0, physical, 0x200000) == 0);
const auto address = reinterpret_cast<std::uint64_t>(mapping);
std::atomic<bool> done{false};
std::thread changer([&] {
for (std::size_t round = 0; !done.load(); ++round) {
const auto offset = (round * 0x200000) % length;
static_cast<void>(sceKernelMprotect(reinterpret_cast<void*>(address + offset), 0x200000, (round & 1) != 0 ? 0 : 3));
if (round % 7 == 0) static_cast<void>(sceKernelMunmap(address + offset, 0x200000));
}
});
for (int round = 0; round < 40; ++round) {
void* again = mapping;
Require(sceKernelMapDirectMemory(&again, length, 3, 0x10, physical, 0x200000) == 0 && again == mapping);
}
done.store(true);
changer.join();
Require(sceKernelMunmap(address, length) == 0);
Require(sceKernelReleaseDirectMemory(physical, length) == 0);
return 0;
}
#endif

static void CheckDirectMapRefusesExecute() {
constexpr std::size_t length = 0x4000;
constexpr int invalid = static_cast<int>(0x80020016u);
Expand Down Expand Up @@ -4967,8 +5024,11 @@ int main(int argc, char** argv) {
return CheckExecutableSharedMappings() ? 0 : 77;
}
#endif
#if defined(__linux__) && defined(ANYPS5_KYTY)
#if (defined(__linux__) || defined(_WIN32)) && defined(ANYPS5_KYTY)
if (argc == 2 && std::strcmp(argv[1], "direct-pages") == 0) return CheckDirectMemoryPages();
#endif
#if defined(_WIN32) && defined(ANYPS5_KYTY)
if (argc == 2 && std::strcmp(argv[1], "direct-pages-changing") == 0) return CheckDirectMemoryPagesWhileMappingsChange();
#endif
Require(argc == 1);
CheckResidentMappingBookkeepingStaysSmall();
Expand Down
2 changes: 1 addition & 1 deletion docs/dev/THIRD_PARTY_KYTY.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ The table draws are GPU-driven draws of a shader pair's table programs.

| Variable | Values | Default | Effect | Category | Platform | Origin |
|---|---|---|---|---|---|---|
| `KYTY_DIRECT_MEMORY_PAGES` | `private`, `populate` or `demand`, else stops | `private` where it works, else `populate` | How the host backs direct memory, so a game's first write to fresh direct memory does not fault once per 4 KiB page on its own thread: `private` puts it in a file on a tmpfs mounted with `huge=within_size` in a private user and mount namespace (2 MiB pages, memory resident only where written), `populate` keeps the memfd and pre-reads each new mapping while a quarter of host memory stays available afterwards (resident memory grows by everything mapped), `demand` is the old 4 KiB demand paging. Unset tries `private` and falls back to `populate` where the namespace or the mount is refused, for example by Ubuntu's AppArmor policy or `shmem_enabled=deny`, while `private` set explicitly stops there instead; the log names the backing | perf | Linux | AnyKyty |
| `KYTY_DIRECT_MEMORY_PAGES` | `private` (Linux only), `populate` or `demand`, else stops | Linux: `private` where it works, else `populate`; Windows: `populate` | How the host backs direct memory, so a game's first write to fresh direct memory does not fault once per 4 KiB page on its own thread: `private` puts it in a file on a tmpfs mounted with `huge=within_size` in a private user and mount namespace (2 MiB pages, memory resident only where written), `populate` pre-reads each new mapping while a quarter of host memory stays available afterwards (resident memory grows by everything mapped; Linux keeps the memfd and uses `MADV_POPULATE_READ`, Windows reads one byte of each page of the new view with `ReadProcessMemory` on several threads and stops at the first page that is no longer readable, so a mapping that another thread removes or protects meanwhile is left as it is), `demand` is the old 4 KiB demand paging. On Linux, unset tries `private` and falls back to `populate` where the namespace or the mount is refused, for example by Ubuntu's AppArmor policy or `shmem_enabled=deny`, while `private` set explicitly stops there instead; on Windows, unset is `populate` and `private` stops; the log names the backing | perf | all | AnyKyty |
| `KYTY_WRITE_BACK_IMAGES` | `0` or `1`, empty counts as unset, else stops | on | Copies the queued readbacks back at each `ACQUIRE_MEM` or `RELEASE_MEM` with GL2 write-back and at each flip; `0` is KytyPS5's behaviour. See [below](#details) | compat | all | `9d957fd81e` |
| `KYTY_URGENT_WRITEBACK_WAIT` | `0` turns it off, any other value or unset leaves it on | on | A guest thread that faults on a page whose texture write-back is still in the open command buffer sends the flush on the urgent queue and waits for that submission itself, instead of queueing the flush behind every operation the command processor has queued; `0` sends it through the ordinary command queue | perf | all | AnyKyty |
| `KYTY_TILE_VIA_VRAM` | `0` or `1`, empty counts as unset, else stops | on | Tiles a tiled image's readback in device-local memory, then copies it once to the host; `0` is KytyPS5's behaviour. See [below](#details) | perf | all | `08c666a175` |
Expand Down
Loading