Commit graph

44 commits

Author SHA1 Message Date
nickci2002
20670186ab
Potential MacOS Build Fix (#3117)
* Potential MacOS build fix for update

* Imported string instead of changing name to std::string_view
2025-06-18 19:04:00 +02:00
Stephen Miller
3e0ec9ebef
Core: Merge Direct Memory Areas (#3084)
* Merge dmem areas

* Fix DirectMemoryArea::CanMergeWith

Don't merge dmem areas if the memory types are different.

* Reduce some warnings to info

Both functions should behave properly now, there's no reason to warn about their use.

* Clang
2025-06-11 17:34:00 +03:00
TheTurtle
d7051f15f4
texture_cache: Basic handling of partially resident images (#3066)
* texture_cache: Avoid gpu tracking assert on sparse image

At the moment just take the easy way of creating the entire image normally and uploading unmapped subresources are zero

* tile_manager: Downgrade assert to error

* fix macos
2025-06-09 01:26:10 -07:00
Stephen Miller
6cdc52cdde
Core: More Memory Cleanup & Fixes (#2997)
* Only perform GPU memory mapping when GPU can access it

This better aligns with hardware observations, and should also speed up unmaps and decommits, since they don't need to be compared with the GPU max address anymore.

* Reserve fixes

ReserveVirtualRange seems to follow the 0x200000000 base address like MemoryPoolReserve does.
Both also need checks in their flags Fixed path to ensure we're mapping in-bounds. If we're not in mapping to our address space, we'll end up reserving and returning the wrong address, which could lead to weird memory issues in games.

I'll need to test on real hardware to verify if such changes are appropriate.

* Better sceKernelMmap

Handles errors where we would previously throw exceptions. Also moves the file logic to MapFile, since that way all the possible errors are in one place.
Also fixes some function parameters to align with our current standards.

* Major refactor

MapDirectMemory, MapFlexibleMemory, ReserveVirtualRange, and MemoryPoolReserve all internally use mmap to perform their mappings. Naturally, this means that all functions have similar behaviors, and a lot of duplicate code.
This add necessary conditional behavior to MapMemory so MemoryPoolReserve and ReserveVirtualRange can use it, without disrupting the behavior of MapDirectMemory or MapFlexibleMemory calls.

* Accurate phys_addr for non-direct mappings

* Properly handle GPU access rights

Since my first commit restricts GPU mappings to memory areas with GPU access permissions, we also need to be updating the GPU mappings appropriately during Protect calls too.

* Update memory.cpp

* Update memory.h

* Update memory.cpp

* Update memory.cpp

* Update memory.cpp

* Revert "Update memory.cpp"

This reverts commit 2c55d014c0.

* Coalesce dmem map

Aligns with hardware observations, hopefully shouldn't break anything since nothing should change hardware-wise when release dmem calls and unmap calls are performed?
Either that or Windows breaks because Windows, will need to test.

* Implement posix_mprotect

Unity calls this
Also fixes the names of sceKernelMprotect and sceKernelMtypeprotect, though that's more of a style change and can be reverted if requested.

* Fix sceKernelSetVirtualRangeName

Partially addresses a "regression" introduced when I fixed up some asserts.
As noted in the code, this implementation is still slightly inaccurate, as handling this properly could cause regressions on Windows.

* Unconditional assert in MapFile

* Remove protect warning

This is expected behavior, shouldn't need any logging.

* Respect alignment

Forgot to properly do this when updating ReserveVirtualRange and MemoryPoolReserve

* Fix Mprotect on free memory

On real hardware, this just does nothing. If something did get protected, there's no way to query that information.
Therefore, it seems pretty safe to just behave like munmap and return size here.

* Minor tidy-up

No functional difference, but looks better.
2025-05-29 18:56:03 +03:00
Stephen Miller
18ff65efc8
Implement sceKernelMapDirectMemory2 (#2940)
* Implement sceKernelMapDirectMemory2

Behaves similarly to sceKernelMapDirectMemory, but has a type parameter.

* Simplify

No need to copy all the MapDirectMemory code over, can just call the function, then do the SetDirectMemoryType call

* Clang
2025-05-16 05:38:40 -07:00
Marcin Mikołajczyk
1832ec2ac2
Implement sceKernelIsStack (#2917) 2025-05-13 13:54:22 -07:00
Stephen Miller
afcf3a12a3
Core: Pooled Memory Fixes (#2895)
Some checks are pending
Build and Release / macos-sdl (push) Blocked by required conditions
Build and Release / macos-qt (push) Blocked by required conditions
Build and Release / reuse (push) Waiting to run
Build and Release / clang-format (push) Waiting to run
Build and Release / get-info (push) Waiting to run
Build and Release / windows-sdl (push) Blocked by required conditions
Build and Release / windows-qt (push) Blocked by required conditions
Build and Release / linux-sdl (push) Blocked by required conditions
Build and Release / linux-qt (push) Blocked by required conditions
Build and Release / linux-sdl-gcc (push) Blocked by required conditions
Build and Release / linux-qt-gcc (push) Blocked by required conditions
Build and Release / pre-release (push) Blocked by required conditions
* Update sceKernelMemoryPoolExpand

Hardware tests show that this function is basically the same as sceKernelAllocateDirectMemory, with some minor differences.
Update the memory searching code to match my updated AllocateDirectMemory code, with appropriate error conditions.

* Update MemoryPoolReserve

Only difference between real hw and our code is behavior with addr = 0.

* Don't coalesce PoolReserved areas.

Real hardware doesn't coalesce them.

* Update PoolCommit

Plenty of edge case behaviors to handle here.
Addresses are treated as fixed, EINVAL is returned for bad mappings, name should be preserved from PoolReserving, committed areas should coalesce, reserved areas get their phys_base updated

* Formatting

* Adjust fixed PoolReserve path

Hardware tests suggest this will overwrite all VMAs in the range. Run UnmapMemoryImpl on the full area, then reserve. Same logic applies to normal reservations too.

Also adjusts logic of the non-fixed path to more closely align with hardware observations.

* Remove phys_base modifications

This can be handled later. Doing the logic properly would likely take work in MergeAdjacent, and would probably need to be applied to normal dmem mappings too.

* Use VMAHandle.Contains()

Why do extra math when we have a function specifically for this?

* Update memory.cpp

* Remove unnecessary code

Since I've removed those two asserts, these two lines of code effectively do nothing.

* Clang

* Fix names

* Fix PoolDecommit

Should fix the address space regressions in UE titles on Windows.

* Fix error log

Should make the cause of this clearer?

* Clang

* Oops

* Remove coalesce on PoolCommit

Windows makes this more difficult.

* Track pool budgets

If you try to commit more pooled memory than is allocated, PoolCommit returns ENOMEM.
Also fixes error conditions for PoolDecommit, that should return EINVAL if given an address that isn't part of the pool.

Note: Seems like the pool budget can't hit zero? I used a <= comparison based on hardware tests, otherwise we're able to make more mappings than real hardware can.
2025-05-11 02:59:14 -07:00
Stephen Miller
6477dc4f1e
Core: Memory Fixes (#2872)
Some checks are pending
Build and Release / reuse (push) Waiting to run
Build and Release / clang-format (push) Waiting to run
Build and Release / get-info (push) Waiting to run
Build and Release / windows-sdl (push) Blocked by required conditions
Build and Release / windows-qt (push) Blocked by required conditions
Build and Release / macos-sdl (push) Blocked by required conditions
Build and Release / macos-qt (push) Blocked by required conditions
Build and Release / linux-sdl (push) Blocked by required conditions
Build and Release / linux-qt (push) Blocked by required conditions
Build and Release / linux-sdl-gcc (push) Blocked by required conditions
Build and Release / linux-qt-gcc (push) Blocked by required conditions
Build and Release / pre-release (push) Blocked by required conditions
* Fix VirtualQuery behavior on low addresses.

* Fix VirtualQuery struct

Somewhere in our BitField and array use, the size of our VirtualQuery struct became larger than the struct used on real hardware.
Fixing this fixes some data corruption visible in the name parameter during my tests.

* Default name to anon

On real hardware, nameless mappings are given the name "anon:address" where address appears to be the address that made the memory call.
For simplicity sake, I'll stick to the name "anon" for now.

* Place an upper bound on returns from SearchFree

Right now, this upper bound is set based on the limitations of our GPU buffer cache and page table.
Someone with more experience in that area of code should probably fix that at some point.

* More anons

* Clang

* Fix name in sceKernelMapNamedDirectMemory

* strncpy instead of strcpy

Hardcoded the constant size for now, I need to review how real hardware behaves here to determine if anything else is necessary for this to be accurate.

* Fix name behavior

All memory naming functions restrict the name size to a 31 character limit, and return `ORBIS_KERNEL_ERROR_ENAMETOOLONG` if that limit is exceeded.
Since this value is constant for all functions involving names, I've defined it as a constant in kernel's memory.h, and used that in place of any hardcoded 32 character limits.

* Error logging

Hopefully this helps in catching the UFC regression?

* Increase address space upper bound

Probably needs heavy testing, especially on Mac/Windows.
This increases the address space, as needed to accommodate strange memory behaviors seen in UFC.

* VirtualQuery fix

Due to limitations of certain platforms, we initialize our vma_map with 3 separate free mappings.
As such, we need to use a while loop here to accurately query mappings with high addresses

* Fix mappings to high addresses

The PS4's GPU can only handle 40bit addresses. Our texture cache and buffer cache were designed around these limits, and mapping to higher addresses would cause segmentation faults and access violations.
To fix these crashes, only map to the GPU if the mapping is fully contained within the address space the GPU should access.
I'm open to suggestions on how to make this cleaner

* Revert "Increase address space upper bound"

This reverts commit 3d50eeeebb.

* Revert VirtualQuery while loop

Windows wasn't happy with this, again.
Will try to debug and properly fix this when I have a good chance.

* Fix asserts

FindVMA, due to the way it's programmed, never actually returns vma_map.end(), the furthest it ever returns is the last valid memory area. All those asserts we involving vma_map.end() never actually trigger due to this.
This commit removes redundant asserts, adds messages to asserts that were lacking them, and fixes all asserts designed to detect out of bounds memory accesses so they actually trigger.
I've also fixed some potential memory safety issues.

* Proper error behavior in QueryProtection

Might as well handle this properly while I'm here.

* Clang

* More information about ReserveVirtualRange results

Should help debug issues like the one in The Order: 1886 (CUSA00076)

* Fix assert message

* Update assert message

Extra space

* Fix my bug

Oh hey, finally something that's my fault.

* Fix rasterizer unmaps

Should use adjusted_size here, otherwise we could unmap too much.
Thanks to diegolix29 for spotting this.

* Fix edge case in MapMemory

Code comments explain everything.
This should fix some memory asserts.

* Fix fix

Avoid running the code path if it's unnecessary, since there are many additional edge cases to handle when the VMA map is small.

* Fix fix fix

Should prevent infinite loops, haven't tested properly yet though.

* Split logging for inputs and out_addr in ReserveVirtualRange

Addresses review comments.
2025-05-09 12:33:04 -07:00
Stephen Miller
54a1694a2b
memory: Implement protecting multiple VMAs (#2484)
* Implement protecting multiple VMAs

A handful of games expect this to work, and updated versions of Grand Theft Auto V crash if it doesn't work.

* Clang
2025-02-21 08:28:47 +02:00
TheTurtle
da0ab005c7
video_core: Fix some cases of "Attempted to track non-GPU memory" (#2447)
* memory: Consider flexible mappings as gpu accessible

Multiple guest apps do this with perfectly valid sharps in simple shaders. This needs some hw testing to see how it is handled but for now doesnt hurt to handle it

* memory: Clamp large buffers to mapped area

Sometimes huge buffers can be bound that start on some valid mapping but arent fully contained by it. It is not reasonable to expect the game needing all of the memory, so clamp the size to avoid the gpu tracking assert

* clang-format fix

---------

Co-authored-by: georgemoralis <giorgosmrls@gmail.com>
2025-02-19 13:31:35 +02:00
kalaposfos13
4f426b723f
Rebase of "Handle munmap over multiple VMAs" (#2233)
* Unmap memory in chunks if spanning over multiple VMAs

* clang

* Merge fixups

* Minor code style changes

* Update function declarations

---------

Co-authored-by: Marcin Mikołajczyk <marcinmikolajcz@gmail.com>
2025-01-24 15:30:55 +02:00
polybiusproxy
817a62468e
core: better memory configuration (#1896) 2024-12-28 12:03:00 +01:00
squidbus
14f7dc3527
cache: Invalidate pages for file reads. (#1726)
* cache: Invalidate pages for file reads.

* texture_cache: Simplify invalidate intersection check.

* vk_rasterizer: Make aware of mapped memory ranges.

* buffer_cache: Remove redundant page calculations.

Called functions will convert to page numbers/addresses themselves.

* file_system: Simplify memory invalidation and add a few missed cases.
2024-12-11 21:11:24 +02:00
Daniel R.
fea2593ab4
The way to Unity, pt.3 (#1681) 2024-12-08 18:30:33 +02:00
Vinicius Rangel
0835dc71b3
More devtools stuff (#1637)
* devtools: memory map viewer

* devtools: batch highlight only for non-group viewer

* devtools: fix not showing entire user data

* devtools: shader debug viewer

* devtools: add more reg naming
2024-12-01 19:34:29 +01:00
TheTurtle
c4506da0ae
kernel: Rewrite pthread emulation (#1440)
* libkernel: Cleanup some function places

* kernel: Refactor thread functions

* kernel: It builds

* kernel: Fix a bunch of bugs, kernel thread heap

* kernel: File cleanup pt1

* File cleanup pt2

* File cleanup pt3

* File cleanup pt4

* kernel: Add missing funcs

* kernel: Add basic exceptions for linux

* gnmdriver: Add workload functions

* kernel: Fix new pthreads code on macOS. (#1441)

* kernel: Downgrade edeadlk to log

* gnmdriver: Add sceGnmSubmitCommandBuffersForWorkload

* exception: Add context register population for macOS. (#1444)

* kernel: Pthread rewrite touchups for Windows

* kernel: Multiplatform thread implementation

* mutex: Remove spamming log

* pthread_spec: Make assert into a log

* pthread_spec: Zero initialize array

* Attempt to fix non-Windows builds

* hotfix: change incorrect NID for scePthreadAttrSetaffinity

* scePthreadAttrSetaffinity implementation

* Attempt to fix Linux

* windows: Address a bunch of address space problems

* address_space: Fix unmap of region surrounded by placeholders

* libs: Reduce logging

* pthread: Implement condvar with waitable atomics and sleepqueue

* sleepq: Separate and make faster

* time: Remove delay execution

* Causes high cpu usage in Tohou Luna Nights

* kernel: Cleanup files again

* pthread: Add missing include

* semaphore: Use binary_semaphore instead of condvar

* Seems more reliable

* libraries/sysmodule: log module on `sceSysmoduleIsLoaded`

* libraries/kernel: implement `scePthreadSetPrio`

---------

Co-authored-by: squidbus <175574877+squidbus@users.noreply.github.com>
Co-authored-by: Daniel R. <47796739+polybiusproxy@users.noreply.github.com>
2024-11-21 22:59:38 +02:00
TheTurtle
87f8fea4de
renderer_vulkan: Commize and adjust buffer bindings (#1412)
* shader_recompiler: Implement finite cmp class

* shader_recompiler: Implement more opcodes

* renderer_vulkan: Commonize buffer binding

* liverpool: More dma data impl

* fix

* copy_shader: Handle additional instructions from Knack

* translator: Add V_CMPX_GE_I32
2024-10-19 15:30:58 +03:00
Daniel R.
7c00ac637a
core: Fix mmap being unable to map GPU memory 2024-10-12 16:35:12 +02:00
Daniel R.
80bf46da4c
core/memory: Pooled memory implementation (#1085) 2024-09-29 10:28:41 +03:00
Daniel R.
8c8a6ccddd
core/memory: Fix sceKernelMTypeProtect setting VMA type (#1037)
* I hate programming and will furiously smash my monitor if I ever see another oversight of this caliber ever again in my goddamn life

* Merge both protect functions together
2024-09-23 18:49:57 +02:00
menaman123
b9c6093717
Implemented sceKernelMTypeProtect and sceKernelMProtect (#387)
* Fixed ORBIS_KERNEL_MAP_OP_TYPE_PROTECT for batchmap2

* Fix merge

* Changed 4 to ORBIS_KERNEL_MAP_OP_TYPE_PROTECT

* Removed MProtect from AddressSpace

* Added Mtyprotect and moved Mprotect to ORBIS_KERNEL_MAP_OP_PROTECT

* Changed Protect for Windows

* reverted the previous function

* Fixed Mtypeprotect and MProtect

* ''

* ''

* Took out logs stopping build

* clang-format issues

* Fixed the order of mtypeprotect and mprotect in batchmap2

* ''

* update branch

* ''

* Fixed nits

* ''

* Update submodules to latest commits

* ''

* reverted ffmpeg

* ''

* Fixed the nits

* ''

* ''

* ''

* ''

* ''

* Fix clang formatting, DEBUG_ASSERT, and extra spacing

* Fix build issues

* Revert "Fix build issues"

This reverts commit 9185f96ec9.

* ''

* ''

* ''

* Changes for MemoryProt Format

* ''

* ''

* ''
2024-09-04 23:36:23 +03:00
Stephen Miller
04fbd7b9e7 Clang 2024-09-02 10:04:56 -05:00
Stephen Miller
9a772aa2f5 Clang fix 2024-09-02 10:03:39 -05:00
Stephen Miller
f8d71b59d9 Fix MemoryManager::VirtualQuery header
The headers for these functions were technically not the same as the actual function definition. This didn't cause any emulation issues, but caused some weird issues with my IDE.
2024-09-02 09:30:32 -05:00
Paris Oplopoios
f514fdfd18
Replace recursive_mutex with mutex (#708)
* Replace recursive_mutex with mutex

* Move mutex lock outside of ObtainBuffer
2024-09-01 22:20:22 +03:00
squidbus
905d49fd96
memory: Fixes for direct memory allocation. (#615)
* memory: Size direct memory based on requested flexible memory.

* memory: Guard against OrbisProcParam without an OrbisKernelMemParam.

* memory: Account for alignment in direct memory suitability checks and add more debugging.
2024-08-28 13:42:53 +03:00
Borchev
18f1799280
Add partial unmap support (#322)
* Add partial unmap support

* undo accidental whitespace removal

* Fix assertions

* Adjust Reserve and Free functions for partial unmapping
2024-08-13 09:05:30 +03:00
TheTurtle
381ba8c7a5
video_core: Implement guest buffer manager (#373)
* video_core: Introduce buffer cache

* video_core: Use multi level page table for caches

* renderer_vulkan: Remove unused stream buffer

* fix build

* oops forgot optimize off
2024-08-08 15:02:10 +03:00
georgemoralis
c1d01709be
kernel: Implement sceKernelSetVirtualRangeName (#338)
* Fix in searchFree should fix #337

* clang format fix

* sceKernelSetVirtualRangeName implementation

* improved vaddr conversion

* updated VirtualQuery to include name too

* unmap also removed name thanks @red_prig

* fixed copy...
2024-07-29 19:08:06 +03:00
TheTurtle
a2cd1669b6
memory: Cleanups and refactors (#324)
* memory: Various fixes

* Added (Partial) sceKernelBatchMap/sceKernelBatchMap2

* memory: Rename and implement batch unmap

* memory: Remove uneeded assert

* memory: Commonize free search routine

* memory: Contains check is inclusive

* memory: Address some alignment issues

* clang format

---------

Co-authored-by: raziel1000 <ckraziel@gmail.com>
2024-07-25 23:01:12 +03:00
georgemoralis
36ec7a1a43
Merge pull request #312 from Borchev/main
Add sceKernelGetDirectMemoryType, update sceKernelReserveVirtualRange
2024-07-21 22:52:50 +03:00
squidbus
b3d97dcd89 Make sure system managed memory is in correct location on macOS. 2024-07-21 22:36:12 +03:00
squidbus
66fa29059c Add initial macOS support. 2024-07-21 22:36:12 +03:00
Borchev
f556f85279 Add sceKernelGetDirectMemoryType and update sceKernelReserveVirtualRange to search for free region when virtual_addr==0 2024-07-21 11:29:24 -07:00
Daniel R
914aa10875
Misc implementations and fixes. (#250)
* Implement `sceKernelFtruncate` and `sceKernelUnlink`.

* Remove unused variable.

* Implement `sceKernelReserveVirtualRange`, misc fixes

* Fix `sceKernelReserveVirtualRange`.

* Add TODO on reserve

* Replace comment with assert.

* Add missing copyright header

* Add `UNREACHABLE` for `IOFile::Unlink`.

* Move NT API initialization out of the header

* Fix bug where files were always mapped as read only.

* `clang-format`
2024-07-11 15:35:58 +03:00
IndecisiveTurtle
2506a285f4 kernel: Implement some functions 2024-06-22 18:09:03 +03:00
TheTurtle
c5d1d579b1
core: Many things (#194)
* video_core: Add a few missed things

* libkernel: More proper memory mapped files

* memory: Fix tessellation buffer mapping

* Cuphead work

* sceKernelPollSema fix

* clang format

* fixed ngs2 lle loading and rtc lib

* draft pthreads keys implementation

* fixed return codes

* return error code if sceKernelLoadStartModule module is invalid

* re-enabled system modules and disable debug in libs.h

* Improve linux support

* fix windows build

* kernel: Rework keys

---------

Co-authored-by: georgemoralis <giorgosmrls@gmail.com>
2024-06-15 14:36:07 +03:00
raphaelthegreat
fc887bf3f5 core: Rework memory manager 2024-06-10 02:13:44 +03:00
psucien
edaeee194d libs: gnmdriver: get tessellation ring factor address 2024-06-08 01:19:52 +02:00
TheTurtle
728249f58d
core: Properly implement TLS (#164)
* core: Split module code from linker

* linker: Properly implement thread local storage

* kernel: Fix a few memory functions

* kernel: Implement module loading

* Now it's easy to do anyway with new module rework
2024-06-05 22:08:18 +03:00
raphaelthegreat
dd91456b48 video_core: Moar shader instruction 2024-05-30 18:17:54 +03:00
TheTurtle
8dfa5782b2
video_core: Add constant buffer support (#147) 2024-05-26 15:51:35 +03:00
TheTurtle
3c90b8ac00
video_core: Bringup some basic functionality (#145)
* video_core: Remove hack in rasterizer

* The hack was to skip the first draw as the display buffer had not been created yet and the texture cache couldn't create one itself. With this patch it now can, using the color buffer parameters from registers

* shader_recompiler: Implement attribute loads/stores

* video_core: Add basic vertex, index buffer handling and pipeline caching

* externals: Make xxhash lowercase
2024-05-25 15:33:15 +03:00
TheTurtle
55855b4195
core: Implement new memory manager (#133)
* core: Implement new memory manager

* ci: Attempt to fix linux build

* code: Fix a few build errors
2024-05-16 15:55:50 +03:00