Commit graph

109 commits

Author SHA1 Message Date
gdkchan
f5a1de6ac5
Fix kernel VA allocation when random allocation fails (#3755)
* Fix kernel VA allocation when random allocation fails

* This was off by one
2022-10-17 22:12:49 +00:00
gdkchan
6922862db8
Optimize kernel memory block lookup and consolidate RBTree implementations (#3410)
* Implement intrusive red-black tree, use it for HLE kernel block manager

* Implement TreeDictionary using IntrusiveRedBlackTree

* Implement IntervalTree using IntrusiveRedBlackTree

* Implement IntervalTree (on Ryujinx.Memory) using IntrusiveRedBlackTree

* Make PredecessorOf and SuccessorOf internal, expose Predecessor and Successor properties on the node itself

* Allocation free tree node lookup
2022-08-26 18:21:48 +00:00
Nicholas Rodine
951700fdd8
Removed unused usings. (#3593)
* Removed unused usings.

* Added back using, now that it's used.

* Removed extra whitespace.
2022-08-18 18:04:54 +02:00
gdkchan
232b1012b0
Fix ThreadingLock deadlock on invalid access and TerminateProcess (#3407) 2022-06-24 02:53:16 +02:00
gdkchan
f2a41b7a1c
Rewrite kernel memory allocator (#3316)
* Rewrite kernel memory allocator

* Remove unused using

* Adjust private static field naming

* Change UlongBitSize to UInt64BitSize

* Fix unused argument, change argument order to be inline with official code and disable random allocation
2022-06-22 12:28:14 -03:00
gdkchan
70895bdb04
Allow concurrent BSD EventFd read/write (#3385) 2022-06-11 14:58:30 -03:00
gdkchan
e546e5933f
Rewrite SVC handler using source generators rather than IL emit (#3371)
* Implement syscall handlers using a source generator

* Copy FlushProcessDataCache implementation to Syscall since it was only implemented on Syscall32

* Fix wrong argument order in some syscalls

* Delete old Reflection.Emit based syscall handling code

* Improvements to the code generation

* ControlCodeMemory address and size is always 64-bit
2022-05-31 17:12:46 -03:00
gdkchan
0c87bf9ea4
Refactor CPU interface to allow the implementation of other CPU emulators (#3362)
* Refactor CPU interface

* Use IExecutionContext interface on SVC handler, change how CPU interrupts invokes the handlers

* Make CpuEngine take a ITickSource rather than returning one

The previous implementation had the scenario where the CPU engine had to implement the tick source in mind, like for example, when we have a hypervisor and the game can read CNTPCT on the host directly. However given that we need to do conversion due to different frequencies anyway, it's not worth it. It's better to just let the user pass the tick source and redirect any reads to CNTPCT to the user tick source

* XML docs for the public interfaces

* PPTC invalidation due to NativeInterface function name changes

* Fix build of the CPU tests

* PR feedback
2022-05-31 16:29:35 -03:00
gdkchan
556be08c4e
Implement PM GetProcessInfo atmosphere extension (partially) (#2966) 2022-05-03 23:28:32 +02:00
gdkchan
1cbca5eecb
Implement code memory syscalls (#2958)
* Implement code memory syscalls

* Remove owner process validation

* Add 32-bit code memory syscalls

* Remove unused field
2022-05-03 13:16:31 +02:00
gdkchan
95017b8c66
Support memory aliasing (#2954)
* Back to the origins: Make memory manager take guest PA rather than host address once again

* Direct mapping with alias support on Windows

* Fixes and remove more of the emulated shared memory

* Linux support

* Make shared and transfer memory not depend on SharedMemoryStorage

* More efficient view mapping on Windows (no more restricted to 4KB pages at a time)

* Handle potential access violations caused by partial unmap

* Implement host mapping using shared memory on Linux

* Add new GetPhysicalAddressChecked method, used to ensure the virtual address is mapped before address translation

Also align GetRef behaviour with software memory manager

* We don't need a mirrorable memory block for software memory manager mode

* Disable memory aliasing tests while we don't have shared memory support on Mac

* Shared memory & SIGBUS handler for macOS

* Fix typo + nits + re-enable memory tests

* Set MAP_JIT_DARWIN on x86 Mac too

* Add back the address space mirror

* Only set MAP_JIT_DARWIN if we are mapping as executable

* Disable aliasing tests again (still fails on Mac)

* Fix UnmapView4KB (by not casting size to int)

* Use ref counting on memory blocks to delay closing the shared memory handle until all blocks using it are disposed

* Address PR feedback

* Make RO hold a reference to the guest process memory manager to avoid early disposal

Co-authored-by: nastys <nastys@users.noreply.github.com>
2022-05-02 20:30:02 -03:00
gdkchan
69b05f9918
Fix GetUserDisableCount NRE (#3187) 2022-03-12 18:12:12 +01:00
merry
bb2f9df0a1
KThread: Fix GetPsr mask (#3180)
* ExecutionContext: GetPstate / SetPstate

* Put it in NativeContext

* KThread: Fix GetPsr mask

* ExecutionContext: Turn methods into Pstate property

* Address nit
2022-03-11 03:16:32 +01:00
gdkchan
92d166ecb7
Enable CPU JIT cache invalidation (#2965)
* Enable CPU JIT cache invalidation

* Invalidate cache on IC IVAU
2022-02-18 02:53:18 +01:00
Berkan Diler
98c838b24c
Use BitOperations methods and delete now unused BitUtils methods (#3134)
Replaces BitUtils.CountTrailingZeros/CountLeadingZeros/IsPowerOfTwo with BitOperations methods
2022-02-18 02:35:23 +01:00
gdkchan
63c9c64196
Move kernel syscall logs to new trace log level (#3137) 2022-02-18 02:14:05 +01:00
mlgatto
95cc18a7b4
Added trace log level (#3096)
* added trace log level

* use trace log level instead of debug ( #1547)

* alignment #1547

* moved trace logs toggle at the bottom #1547

* bumped config file version #3096

* added migration step #3096

* setting moved to the dev section #1547

* performance warning displayed when trace is enabled #1547
2022-02-17 21:08:07 -03:00
Berkan Diler
8f35345729
Use Enum and Delegate.CreateDelegate generic overloads (#3111)
* Use Enum generic overloads

* Remove EnumExtensions.cs

* Use Delegate.CreateDelegate generic overloads
2022-02-13 10:50:07 -03:00
Mary
6dffe0fad4
misc: Make PID unsigned long instead of long (#3043) 2022-02-09 17:18:07 -03:00
Mary
20ce37dee6
kernel: A bit of refactoring and fix GetThreadContext3 correctness (#3042)
* Start refactoring kernel a bit and import some changes from kernel decoupling PR

* kernel: Put output always at the start in Syscall functions

* kernel: Rewrite GetThreadContext3 to use a structure and to be accurate

* kernel: make KernelTransfer use generic types and simplify

* Fix some warning and do not use getters on MemoryInfo

* Address gdkchan's comment

* GetThreadContext3: use correct pause flag
2022-01-29 22:18:03 +01:00
Mary
929a97d432
kernel: Fix deadlock when pinning in interrupt handler (#2999)
* kernel: Fix deadlock when pinning in interrupt handler

This fix a deadlock on DoDonPachi Resurrection when starting a new game

* Address gdkchan's comment
2022-01-16 13:21:44 +01:00
Mary
e96ef6d532
kernel: Implement thread pinning support (#2840)
* kernel: Implement Thread pinning support

This commit adds support for 8.x thread pinning changes and implement SynchronizePreemptionState syscall.

Based on kernel 13.x reverse.

* Address gdkchan's comment

* kernel: fix missing critical section leave in SetActivity

Fix Unity games

* Implement missing bits on the interrupt handler and inline update pinning function as it cannot be generic

* Fix some bugs in SetActivity and SetCoreAndAffinityMask

* Address gdkchan's comments
2021-12-30 10:55:06 +01:00
gdkchan
a438a4bc16
Remove PortRemoteClosed warning (#2928) 2021-12-23 14:43:30 -03:00
Mary
2ab777885b
kernel: Improve GetInfo readability and update to 13.0.0 (#2900)
* kernel: Define InfoTYpe and make it less obscure when reading GetInfo

Also map ThreadTickCount to 25 instead of 0xF0000002 like 13.x kernel.

* kernel: Implement GetInfo IsApplication

* kernel: Implement GetInfo FreeThreadCount
2021-12-04 20:23:26 -03:00
Mary
7b040e51b0
kernel: Fix sleep timing accuracy (#2828)
* kernel: Fix sleep timing accuracy

This commit corrects some mistake while comparing reversing of kernel
13.x with our own.

WaitAndCheckScheduledObjects timing accuracy was also improved.

* Make KTimeManager.WaitAndCheckScheduledObjects spin wait for sub milliseconds

Fix performance regression on Pokemon Let's Go games and possibly
others.

* Address rip's comment

* kernel: Fix issues with timeout of -1 (0xFFFFFFFF)

Fixes possible hang on Pokemon DP and possibly others
2021-11-28 13:15:26 +01:00
Mary
786fb04d20
kernel: Add support for CFI (#2839)
Add basic support for the CFI value being passed in X18 since 11.0.0 by the official kernel.
We do not implement any random generator atm in the kernel and as such the KSystemControl.GenerateRandom function is stubbed
2021-11-28 13:01:17 +01:00
Mary
5c66a36ed6
kernel: Fix inverted condition on permission check of SetMemoryPermission syscall (#2777)
* kernel: Fix inverted condition on permission check of SetMemoryPermission syscall

* Fix condition for real..
2021-10-24 20:00:31 -03:00
Mary
b4dc33efc2
kernel: Clear pages allocated with SetHeapSize (#2776)
* kernel: Clear pages allocated with SetHeapSize

Before this commit, all new pages allocated by SetHeapSize were not
cleared by the kernel.

This would cause undefined data to be pass to the userland and possibly
resulting in weird memory corruption.

This commit also add support for custom fill heap and ipc value (that is also
supported by the official kernel)

* Remove dots at the end of KPageTableBase.MapPages new documentation

* Remove unused _stackFillValue
2021-10-24 18:52:59 -03:00
Mary
dc837c0042
kernel: Add resource limit related syscalls (#2773)
* kernel: Add resource limit related syscalls

This commit implements all resource limit related syscalls.

* Fix register mapping being wrong for SetResourceLimitLimitValue

* Address gdkchan's comment
2021-10-24 01:40:13 +02:00
Mary
c94d47cc40
kernel: Implement SetMemoryPermission syscall (#2772)
* kernel: Implement SetMemoryPermission syscall

This commit implement the SetMemoryPermission syscall accurately.
This also fix KMemoryPermission not being an unsigned 32 bits type and
add the "DontCare" bit (used by shared memory, currently unused in
Ryujinx)

* Update MemoryPermission mask

* Address gdkchan's comments

* Fix a nit

* Address gdkchan's comment
2021-10-24 01:24:49 +02:00
Mary
e7e65ccbc9
kernel: Add missing address space check in SetMemoryAttribute syscall (#2771) 2021-10-24 01:07:41 +02:00
mpnico
117e32a6ff
Implement a "Pause Emulation" option & hotkey (#2428)
* Add a "Pause Emulation" option and hotkey

Closes Ryujinx#1604

* Refactoring how pause is handled

* Applied suggested changes from review

* Applied suggested fixes

* Pass correct suspend type to threads for suspend/resume

* Fix NRE after stoping emulation

* Removing SimulateWakeUpMessage call after resuming emulation

* Skip suspending non game process

* Pause the tickCounter in the ExecutionContext

* Refactoring tickCounter pause/resume as suggested

* Fix Config migration to add pause hotkey

* Fixed pausing only application threads

* Fix exiting emulator while paused

* Avoid pause/resume while already paused/resumed

* Cleanup unused code

* Avoid restarting audio if stopping emulation while in pause.

* Added suggested changes

* Fix ConfigurationState
2021-09-11 22:08:25 +02:00
Caian Benedicto
ff8849671a
Update TamperMachine and disable write-to-code prevention (#2506)
* Enable write to memory and improve logging

* Update tamper machine opcodes and improve reporting

* Add Else support

* Add missing private statement
2021-08-04 22:05:17 +02:00
gdkchan
b5190f1681
Fix virtual memory allocation being out of range (#2464) 2021-07-11 16:24:31 -03:00
gdkchan
fbb4019ed5
Initial support for separate GPU address spaces (#2394)
* Make GPU memory manager a member of GPU channel

* Move physical memory instance to the memory manager, and the caches to the physical memory

* PR feedback
2021-06-29 19:32:02 +02:00
Mary
0644db02ad
kernel: Implement MapTransferMemory and UnmapTransferMemory (#2386)
Based on my reversing of kernel 12.0.0
2021-06-23 21:52:11 +02:00
gdkchan
91fdaea39b
Fix guest stack trace inexistent function names (#2326) 2021-05-30 20:53:02 +02:00
gdkchan
f6fcef483f
Fix inverted low/high mask value on GetThreadCoreMask32 syscall (#2325) 2021-05-30 20:44:59 +02:00
FICTURE7
9d7627af64
Add multi-level function table (#2228)
* Add AddressTable<T>

* Use AddressTable<T> for dispatch

* Remove JumpTable & co.

* Add fallback for out of range addresses

* Add PPTC support

* Add documentation to `AddressTable<T>`

* Make AddressTable<T> configurable

* Fix table walk

* Fix IsMapped check

* Remove CountTableCapacity

* Add PPTC support for fast path

* Rename IsMapped to IsValid

* Remove stale comment

* Change format of address in exception message

* Add TranslatorStubs

* Split DispatchStub

Avoids recompilation of stubs during tests.

* Add hint for 64bit or 32bit

* Add documentation to `Symbol`

* Add documentation to `TranslatorStubs`

Make `TranslatorStubs` disposable as well.

* Add documentation to `SymbolType`

* Add `AddressTableEventSource` to monitor function table size

Add an EventSource which measures the amount of unmanaged bytes
allocated by AddressTable<T> instances.

 dotnet-counters monitor -n Ryujinx --counters ARMeilleure

* Add `AllowLcqInFunctionTable` optimization toggle

This is to reduce the impact this change has on the test duration.
Before everytime a test was ran, the FunctionTable would be initialized
and populated so that the newly compiled test would get registered to
it.

* Implement unmanaged dispatcher

Uses the DispatchStub to dispatch into the next translation, which
allows execution to stay in unmanaged for longer and skips a
ConcurrentDictionary look up when the target translation has been
registered to the FunctionTable.

* Remove redundant null check

* Tune levels of FunctionTable

Uses 5 levels instead of 4 and change unit of AddressTableEventSource
from KB to MB.

* Use 64-bit function table

Improves codegen for direct branches:

    mov qword [rax+0x408],0x10603560
 -  mov rcx,sub_10603560_OFFSET
 -  mov ecx,[rcx]
 -  mov ecx,ecx
 -  mov rdx,JIT_CACHE_BASE
 -  add rdx,rcx
 +  mov rcx,sub_10603560
 +  mov rdx,[rcx]
    mov rcx,rax

Improves codegen for dispatch stub:

    and rax,byte +0x1f
 -  mov eax,[rcx+rax*4]
 -  mov eax,eax
 -  mov rcx,JIT_CACHE_BASE
 -  lea rax,[rcx+rax]
 +  mov rax,[rcx+rax*8]
    mov rcx,rbx

* Remove `JitCacheSymbol` & `JitCache.Offset`

* Turn `Translator.Translate` into an instance method

We do not have to add more parameter to this method and related ones as
new structures are added & needed for translation.

* Add symbol only when PTC is enabled

Address LDj3SNuD's feedback

* Change `NativeContext.Running` to a 32-bit integer

* Fix PageTable symbol for host mapped
2021-05-29 18:06:28 -03:00
riperiperi
54ea2285f0
POWER - Performance Optimizations With Extensive Ramifications (#2286)
* Refactoring of KMemoryManager class

* Replace some trivial uses of DRAM address with VA

* Get rid of GetDramAddressFromVa

* Abstracting more operations on derived page table class

* Run auto-format on KPageTableBase

* Managed to make TryConvertVaToPa private, few uses remains now

* Implement guest physical pages ref counting, remove manual freeing

* Make DoMmuOperation private and call new abstract methods only from the base class

* Pass pages count rather than size on Map/UnmapMemory

* Change memory managers to take host pointers

* Fix a guest memory leak and simplify KPageTable

* Expose new methods for host range query and mapping

* Some refactoring of MapPagesFromClientProcess to allow proper page ref counting and mapping without KPageLists

* Remove more uses of AddVaRangeToPageList, now only one remains (shared memory page checking)

* Add a SharedMemoryStorage class, will be useful for host mapping

* Sayonara AddVaRangeToPageList, you served us well

* Start to implement host memory mapping (WIP)

* Support memory tracking through host exception handling

* Fix some access violations from HLE service guest memory access and CPU

* Fix memory tracking

* Fix mapping list bugs, including a race and a error adding mapping ranges

* Simple page table for memory tracking

* Simple "volatile" region handle mode

* Update UBOs directly (experimental, rough)

* Fix the overlap check

* Only set non-modified buffers as volatile

* Fix some memory tracking issues

* Fix possible race in MapBufferFromClientProcess (block list updates were not locked)

* Write uniform update to memory immediately, only defer the buffer set.

* Fix some memory tracking issues

* Pass correct pages count on shared memory unmap

* Armeilleure Signal Handler v1 + Unix changes

Unix currently behaves like windows, rather than remapping physical

* Actually check if the host platform is unix

* Fix decommit on linux.

* Implement windows 10 placeholder shared memory, fix a buffer issue.

* Make PTC version something that will never match with master

* Remove testing variable for block count

* Add reference count for memory manager, fix dispose

Can still deadlock with OpenAL

* Add address validation, use page table for mapped check, add docs

Might clean up the page table traversing routines.

* Implement batched mapping/tracking.

* Move documentation, fix tests.

* Cleanup uniform buffer update stuff.

* Remove unnecessary assignment.

* Add unsafe host mapped memory switch

On by default. Would be good to turn this off for untrusted code (homebrew, exefs mods) and give the user the option to turn it on manually, though that requires some UI work.

* Remove C# exception handlers

They have issues due to current .NET limitations, so the meilleure one fully replaces them for now.

* Fix MapPhysicalMemory on the software MemoryManager.

* Null check for GetHostAddress, docs

* Add configuration for setting memory manager mode (not in UI yet)

* Add config to UI

* Fix type mismatch on Unix signal handler code emit

* Fix 6GB DRAM mode.

The size can be greater than `uint.MaxValue` when the DRAM is >4GB.

* Address some feedback.

* More detailed error if backing memory cannot be mapped.

* SetLastError on all OS functions for consistency

* Force pages dirty with UBO update instead of setting them directly.

Seems to be much faster across a few games. Need retesting.

* Rebase, configuration rework, fix mem tracking regression

* Fix race in FreePages

* Set memory managers null after decrementing ref count

* Remove readonly keyword, as this is now modified.

* Use a local variable for the signal handler rather than a register.

* Fix bug with buffer resize, and index/uniform buffer binding.

Should fix flickering in games.

* Add InvalidAccessHandler to MemoryTracking

Doesn't do anything yet

* Call invalid access handler on unmapped read/write.

Same rules as the regular memory manager.

* Make unsafe mapped memory its own MemoryManagerType

* Move FlushUboDirty into UpdateState.

* Buffer dirty cache, rather than ubo cache

Much cleaner, may be reusable for Inline2Memory updates.

* This doesn't return anything anymore.

* Add sigaction remove methods, correct a few function signatures.

* Return empty list of physical regions for size 0.

* Also on AddressSpaceManager

Co-authored-by: gdkchan <gab.dark.100@gmail.com>
2021-05-24 22:52:44 +02:00
Somebody Whoisbored
26e5b5acff
Extend info printed when guest crashes/breaks execution (#1845)
* Add CPU register printout when guest crashes/breaks execution

* Print out registers when undefined instruction is hit

* Apply suggestions from code review

Co-authored-by: Ac_K <Acoustik666@gmail.com>

* Fixes after rebase

* Address gdkchan's comments

Co-authored-by: Ac_K <Acoustik666@gmail.com>
Co-authored-by: Mary <me@thog.eu>
2021-05-21 01:27:16 +02:00
gdkchan
ebdbaa6db0
Fix a specific core migration bug on the scheduler (#2271) 2021-05-11 13:18:50 -03:00
Mary
305f06eb71
HLE: Fix integer sign inconcistency accross the codebase (#2222)
* Make all title id instances unsigned

* Replace address and size with ulong instead of signed types

Long overdue change.
Also change some logics here and there to optimize with the new memory
manager.

* Address Ac_K's comments

* Remove uneeded cast all around

* Fixes some others misalignment
2021-04-24 12:16:01 +02:00
gdkchan
874540bb5c
Allow DRAM size to be increased from 4GB to 6GB (#2174)
* Allow DRAM size to be increased from 4GB to 6GB

* Add option on the UI
2021-04-04 14:06:59 +02:00
Caian Benedicto
0c1ea1212a
Add the TamperMachine module for runtime mods and cheats (#1928)
* Add initial implementation of the Tamper Machine

* Implement Atmosphere opcodes 0, 4 and 9

* Add missing TamperCompilationException class

* Implement Atmosphere conditional and loop opcodes 1, 2 and 3

* Inplement input conditional opcode 8

* Add register store opcode A

* Implement extended pause/resume opcodes FF0 and FF1

* Implement extended log opcode FFF

* Implement extended register conditional opcode C0

* Refactor TamperProgram to an interface

* Moved Atmosphere classes to a separate subdirectory

* Fix OpProcCtrl class not setting process

* Implement extended register save/restore opcodes C1, C2 and C3

* Refactor code emitters to separate classes

* Supress memory access errors from the Tamper Machine

* Add debug information to tamper register and memory writes

* Add block stack check to Atmosphere Cheat compiler

* Add handheld input support to Tamper Machine

* Fix code styling

* Fix build id and cheat case mismatch

* Fix invalid immediate size selection

* Print build ids of the title

* Prevent Tamper Machine from change code regions

* Remove Atmosphere namespace

* Remove empty cheats from the list

* Prevent code modification without disabling the tampering

* Fix missing addressing mode in LoadRegisterWithMemory

* Fix wrong addressing in RegisterConditional

* Add name to the tamper machine thread

* Fix code styling
2021-03-27 15:12:05 +01:00
gdkchan
5ea7d77981
Fix inter-process data copy on non-contiguous physical regions (#1988) 2021-02-08 10:54:49 +11:00
gdkchan
532b8cad13
Update KAddressArbiter implementation to 11.x kernel (#1851)
* Update KAddressArbiter implementation to 11.x kernel

* InsertSortedByPriority is no longer needed
2021-01-01 14:59:26 -03:00
gdkchan
19d18662ea
Correct type of executable sizes (#1802) 2020-12-13 08:30:27 +01:00
gdkchan
48278905d1
Rewrite scheduler context switch code (#1786)
* Rewrite scheduler context switch code

* Fix race in UnmapIpcRestorePermission

* Fix thread exit issue that could leave the scheduler in a invalid state

* Change context switch method to not wait on guest thread, remove spin wait, use SignalAndWait to pass control

* Remove multi-core setting (it is always on now)

* Re-enable assert

* Remove multicore from default config and schema

* Fix race in KTimeManager
2020-12-09 19:20:05 -03:00
riperiperi
4594c3b310
Signal memory tracking before/after mapping into another process (#1785)
* Signal memory tracking before/after mapping into another process

* Wording.

* Add missing method.
2020-12-07 21:42:17 -03:00