Ryujinx/src/Ryujinx.HLE/HOS/Services/ServerBase.cs

519 lines
18 KiB
C#
Raw Normal View History

using Ryujinx.Common;
using Ryujinx.Common.Logging;
using Ryujinx.Common.Memory;
using Ryujinx.HLE.HOS.Ipc;
using Ryujinx.HLE.HOS.Kernel;
using Ryujinx.HLE.HOS.Kernel.Ipc;
using Ryujinx.HLE.HOS.Kernel.Process;
using Ryujinx.HLE.HOS.Kernel.Threading;
using Ryujinx.Horizon.Common;
2018-02-04 23:08:20 +00:00
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Collections.Generic;
2018-02-04 23:08:20 +00:00
using System.IO;
using System.Threading;
2018-02-04 23:08:20 +00:00
namespace Ryujinx.HLE.HOS.Services
2018-02-04 23:08:20 +00:00
{
class ServerBase : IDisposable
2018-02-04 23:08:20 +00:00
{
// Must be the maximum value used by services (highest one know is the one used by nvservices = 0x8000).
// Having a size that is too low will cause failures as data copy will fail if the receiving buffer is
// not large enough.
private const int PointerBufferSize = 0x8000;
private readonly static uint[] DefaultCapabilities = new uint[]
2018-02-04 23:08:20 +00:00
{
0x030363F7,
0x1FFFFFCF,
0x207FFFEF,
0x47E0060F,
0x0048BFFF,
0x01007FFF
};
// The amount of time Dispose() will wait to Join() the thread executing the ServerLoop()
private static readonly TimeSpan ThreadJoinTimeout = TimeSpan.FromSeconds(3);
private readonly KernelContext _context;
private KProcess _selfProcess;
private KThread _selfThread;
private readonly ReaderWriterLockSlim _handleLock = new ReaderWriterLockSlim();
private readonly Dictionary<int, IpcService> _sessions = new Dictionary<int, IpcService>();
private readonly Dictionary<int, Func<IpcService>> _ports = new Dictionary<int, Func<IpcService>>();
private readonly MemoryStream _requestDataStream;
private readonly BinaryReader _requestDataReader;
private readonly MemoryStream _responseDataStream;
private readonly BinaryWriter _responseDataWriter;
private int _isDisposed = 0;
public ManualResetEvent InitDone { get; }
public string Name { get; }
public Func<IpcService> SmObjectFactory { get; }
public ServerBase(KernelContext context, string name, Func<IpcService> smObjectFactory = null)
{
_context = context;
_requestDataStream = MemoryStreamManager.Shared.GetStream();
_requestDataReader = new BinaryReader(_requestDataStream);
_responseDataStream = MemoryStreamManager.Shared.GetStream();
_responseDataWriter = new BinaryWriter(_responseDataStream);
InitDone = new ManualResetEvent(false);
Name = name;
2021-05-11 22:57:21 +00:00
SmObjectFactory = smObjectFactory;
const ProcessCreationFlags Flags =
ProcessCreationFlags.EnableAslr |
ProcessCreationFlags.AddressSpace64Bit |
ProcessCreationFlags.Is64Bit |
ProcessCreationFlags.PoolPartitionSystem;
ProcessCreationInfo creationInfo = new ProcessCreationInfo("Service", 1, 0, 0x8000000, 1, Flags, 0, 0);
KernelStatic.StartInitialProcess(context, creationInfo, DefaultCapabilities, 44, Main);
}
private void AddPort(int serverPortHandle, Func<IpcService> objectFactory)
{
bool lockTaken = false;
try
{
lockTaken = _handleLock.TryEnterWriteLock(Timeout.Infinite);
_ports.Add(serverPortHandle, objectFactory);
}
finally
{
if (lockTaken)
{
_handleLock.ExitWriteLock();
}
}
}
public void AddSessionObj(KServerSession serverSession, IpcService obj)
{
// Ensure that the sever loop is running.
InitDone.WaitOne();
_selfProcess.HandleTable.GenerateHandle(serverSession, out int serverSessionHandle);
AddSessionObj(serverSessionHandle, obj);
}
public void AddSessionObj(int serverSessionHandle, IpcService obj)
{
bool lockTaken = false;
try
{
lockTaken = _handleLock.TryEnterWriteLock(Timeout.Infinite);
_sessions.Add(serverSessionHandle, obj);
}
finally
{
if (lockTaken)
{
_handleLock.ExitWriteLock();
}
}
}
private IpcService GetSessionObj(int serverSessionHandle)
{
bool lockTaken = false;
try
{
lockTaken = _handleLock.TryEnterReadLock(Timeout.Infinite);
return _sessions[serverSessionHandle];
}
finally
{
if (lockTaken)
{
_handleLock.ExitReadLock();
}
}
}
private bool RemoveSessionObj(int serverSessionHandle, out IpcService obj)
{
bool lockTaken = false;
try
{
lockTaken = _handleLock.TryEnterWriteLock(Timeout.Infinite);
return _sessions.Remove(serverSessionHandle, out obj);
}
finally
{
if (lockTaken)
{
_handleLock.ExitWriteLock();
}
}
}
private void Main()
{
ServerLoop();
}
private void ServerLoop()
{
_selfProcess = KernelStatic.GetCurrentProcess();
_selfThread = KernelStatic.GetCurrentThread();
if (SmObjectFactory != null)
{
_context.Syscall.ManageNamedPort(out int serverPortHandle, "sm:", 50);
AddPort(serverPortHandle, SmObjectFactory);
}
InitDone.Set();
ulong messagePtr = _selfThread.TlsAddress;
_context.Syscall.SetHeapSize(out ulong heapAddr, 0x200000);
_selfProcess.CpuMemory.Write(messagePtr + 0x0, 0);
_selfProcess.CpuMemory.Write(messagePtr + 0x4, 2 << 10);
_selfProcess.CpuMemory.Write(messagePtr + 0x8, heapAddr | ((ulong)PointerBufferSize << 48));
int replyTargetHandle = 0;
while (true)
{
int portHandleCount;
int handleCount;
int[] handles;
bool handleLockTaken = false;
try
{
handleLockTaken = _handleLock.TryEnterReadLock(Timeout.Infinite);
portHandleCount = _ports.Count;
handleCount = portHandleCount + _sessions.Count;
handles = ArrayPool<int>.Shared.Rent(handleCount);
_ports.Keys.CopyTo(handles, 0);
_sessions.Keys.CopyTo(handles, portHandleCount);
}
finally
{
if (handleLockTaken)
{
_handleLock.ExitReadLock();
}
}
// We still need a timeout here to allow the service to pick up and listen new sessions...
var rc = _context.Syscall.ReplyAndReceive(out int signaledIndex, handles.AsSpan(0, handleCount), replyTargetHandle, 1000000L);
_selfThread.HandlePostSyscall();
if (!_selfThread.Context.Running)
{
break;
}
replyTargetHandle = 0;
if (rc == Result.Success && signaledIndex >= portHandleCount)
{
// We got a IPC request, process it, pass to the appropriate service if needed.
int signaledHandle = handles[signaledIndex];
if (Process(signaledHandle, heapAddr))
{
replyTargetHandle = signaledHandle;
}
}
else
{
if (rc == Result.Success)
{
// We got a new connection, accept the session to allow servicing future requests.
if (_context.Syscall.AcceptSession(out int serverSessionHandle, handles[signaledIndex]) == Result.Success)
{
bool handleWriteLockTaken = false;
try
{
handleWriteLockTaken = _handleLock.TryEnterWriteLock(Timeout.Infinite);
IpcService obj = _ports[handles[signaledIndex]].Invoke();
_sessions.Add(serverSessionHandle, obj);
}
finally
{
if (handleWriteLockTaken)
{
_handleLock.ExitWriteLock();
}
}
}
}
_selfProcess.CpuMemory.Write(messagePtr + 0x0, 0);
_selfProcess.CpuMemory.Write(messagePtr + 0x4, 2 << 10);
_selfProcess.CpuMemory.Write(messagePtr + 0x8, heapAddr | ((ulong)PointerBufferSize << 48));
}
ArrayPool<int>.Shared.Return(handles);
}
Dispose();
}
private bool Process(int serverSessionHandle, ulong recvListAddr)
{
IpcMessage request = ReadRequest();
IpcMessage response = new IpcMessage();
2018-02-04 23:08:20 +00:00
ulong tempAddr = recvListAddr;
int sizesOffset = request.RawData.Length - ((request.RecvListBuff.Count * 2 + 3) & ~3);
bool noReceive = true;
for (int i = 0; i < request.ReceiveBuff.Count; i++)
{
noReceive &= (request.ReceiveBuff[i].Position == 0);
}
if (noReceive)
{
Reducing Memory Allocations 202303 (#4624) * use ArrayPool, avoid 6000-7000 allocs/sec of runtime * use ArrayPool, avoid ~7k allocs/second during game execution * use ArrayPool, avoid ~3000 allocs/sec during game execution * use MemoryPool, reduce 0.5 MB/sec of new allocations during game execution * avoid over-allocation by setting List<> Capacity when known * remove LINQ in KTimeManager.UnscheduleFutureInvocation * KTimeManager - avoid spinning one more time when the time has arrived * KTimeManager - let SpinWait decide when to Thread.Yield(), and don't SpinOnce() immediately after Thread.Yield() * use MemoryPool, reduce ~175k bytes/sec allocation during game execution * IpcService - call commands via dynamic methods instead of reflection .Invoke(). Faster to call and with fewer allocations because parameters can be passed directly instead of as an array * Make ButtonMappingEntry a record struct to avoid allocations. Set the List<ButtonMappingEntry> capacity according to use. * add MemoryBuffer type for working with MemoryPool<byte> * update changes to use MemoryBuffer * make parameter ReadOnlySpan instead of Span * whitespace fix * Revert "IpcService - call commands via dynamic methods instead of reflection .Invoke(). Faster to call and with fewer allocations because parameters can be passed directly instead of as an array" This reverts commit f2c698bdf65f049e8481c9f2ec7138d9b9a8261d. * tweak KTimeManager spin behavior * replace MemoryBuffer with ByteMemoryPool modeled after System.Buffers.ArrayMemoryPool<T> * make ByteMemoryPoolBuffer responsible for renting memory
2023-04-24 02:06:23 +00:00
response.PtrBuff.EnsureCapacity(request.RecvListBuff.Count);
for (int i = 0; i < request.RecvListBuff.Count; i++)
{
ulong size = (ulong)BinaryPrimitives.ReadInt16LittleEndian(request.RawData.AsSpan(sizesOffset + i * 2, 2));
response.PtrBuff.Add(new IpcPtrBuffDesc(tempAddr, (uint)i, size));
request.RecvListBuff[i] = new IpcRecvListBuffDesc(tempAddr, size);
tempAddr += size;
}
}
bool shouldReply = true;
bool isTipcCommunication = false;
_requestDataStream.SetLength(0);
_requestDataStream.Write(request.RawData);
_requestDataStream.Position = 0;
if (request.Type == IpcMessageType.CmifRequest ||
request.Type == IpcMessageType.CmifRequestWithContext)
2018-02-04 23:08:20 +00:00
{
response.Type = IpcMessageType.CmifResponse;
2018-02-04 23:08:20 +00:00
_responseDataStream.SetLength(0);
2018-02-04 23:08:20 +00:00
ServiceCtx context = new ServiceCtx(
_context.Device,
_selfProcess,
_selfProcess.CpuMemory,
_selfThread,
request,
response,
_requestDataReader,
_responseDataWriter);
2018-02-04 23:08:20 +00:00
GetSessionObj(serverSessionHandle).CallCmifMethod(context);
2018-02-04 23:08:20 +00:00
response.RawData = _responseDataStream.ToArray();
}
else if (request.Type == IpcMessageType.CmifControl ||
request.Type == IpcMessageType.CmifControlWithContext)
{
uint magic = (uint)_requestDataReader.ReadUInt64();
uint cmdId = (uint)_requestDataReader.ReadUInt64();
2018-02-04 23:08:20 +00:00
switch (cmdId)
2018-02-04 23:08:20 +00:00
{
case 0:
FillHipcResponse(response, 0, GetSessionObj(serverSessionHandle).ConvertToDomain());
break;
2018-02-04 23:08:20 +00:00
case 3:
FillHipcResponse(response, 0, PointerBufferSize);
break;
// TODO: Whats the difference between IpcDuplicateSession/Ex?
case 2:
case 4:
{
_ = _requestDataReader.ReadInt32();
_context.Syscall.CreateSession(out int dupServerSessionHandle, out int dupClientSessionHandle, false, 0);
bool writeLockTaken = false;
try
{
writeLockTaken = _handleLock.TryEnterWriteLock(Timeout.Infinite);
_sessions[dupServerSessionHandle] = _sessions[serverSessionHandle];
}
finally
{
if (writeLockTaken)
{
_handleLock.ExitWriteLock();
}
}
response.HandleDesc = IpcHandleDesc.MakeMove(dupClientSessionHandle);
FillHipcResponse(response, 0);
break;
}
2018-02-04 23:08:20 +00:00
default: throw new NotImplementedException(cmdId.ToString());
2018-02-04 23:08:20 +00:00
}
}
else if (request.Type == IpcMessageType.CmifCloseSession || request.Type == IpcMessageType.TipcCloseSession)
{
_context.Syscall.CloseHandle(serverSessionHandle);
if (RemoveSessionObj(serverSessionHandle, out var session))
{
(session as IDisposable)?.Dispose();
}
shouldReply = false;
}
// If the type is past 0xF, we are using TIPC
else if (request.Type > IpcMessageType.TipcCloseSession)
{
isTipcCommunication = true;
// Response type is always the same as request on TIPC.
response.Type = request.Type;
_responseDataStream.SetLength(0);
ServiceCtx context = new ServiceCtx(
_context.Device,
_selfProcess,
_selfProcess.CpuMemory,
_selfThread,
request,
response,
_requestDataReader,
_responseDataWriter);
GetSessionObj(serverSessionHandle).CallTipcMethod(context);
response.RawData = _responseDataStream.ToArray();
2018-02-04 23:08:20 +00:00
using var responseStream = response.GetStreamTipc();
_selfProcess.CpuMemory.Write(_selfThread.TlsAddress, responseStream.GetReadOnlySequence());
}
else
{
throw new NotImplementedException(request.Type.ToString());
}
if (!isTipcCommunication)
{
using var responseStream = response.GetStream((long)_selfThread.TlsAddress, recvListAddr | ((ulong)PointerBufferSize << 48));
_selfProcess.CpuMemory.Write(_selfThread.TlsAddress, responseStream.GetReadOnlySequence());
2018-02-04 23:08:20 +00:00
}
return shouldReply;
2018-02-04 23:08:20 +00:00
}
private IpcMessage ReadRequest()
2018-02-04 23:08:20 +00:00
{
const int messageSize = 0x100;
2018-02-04 23:08:20 +00:00
[Ryujinx.Common] Address dotnet-format issues (#5358) * dotnet format style --severity info Some changes were manually reverted. * dotnet format analyzers --serverity info Some changes have been minimally adapted. * Restore a few unused methods and variables * Silence dotnet format IDE0060 warnings * Silence dotnet format IDE0059 warnings * Address or silence dotnet format IDE1006 warnings * Address dotnet format CA1816 warnings * Address or silence dotnet format CA2211 warnings * Silence CA1806 and CA1834 issues * Fix formatting for switch expressions * Address most dotnet format whitespace warnings * Apply dotnet format whitespace formatting A few of them have been manually reverted and the corresponding warning was silenced * Revert formatting changes for while and for-loops * Format if-blocks correctly * Run dotnet format whitespace after rebase * Run dotnet format style after rebase * Run dotnet format analyzers after rebase * Run dotnet format after rebase and remove unused usings - analyzers - style - whitespace * Add comments to disabled warnings * Remove a few unused parameters * Replace MmeShadowScratch with Array256<uint> * Simplify properties and array initialization, Use const when possible, Remove trailing commas * Run dotnet format after rebase * Address IDE0251 warnings * Revert "Simplify properties and array initialization, Use const when possible, Remove trailing commas" This reverts commit 9462e4136c0a2100dc28b20cf9542e06790aa67e. * dotnet format whitespace after rebase * First dotnet format pass * Second dotnet format pass * Fix build issues * Fix StructArrayHelpers.cs * Apply suggestions from code review Co-authored-by: Ac_K <Acoustik666@gmail.com> * Fix return statements * Fix naming rule violations * Update src/Ryujinx.Common/Utilities/StreamUtils.cs Co-authored-by: Ac_K <Acoustik666@gmail.com> * Add trailing commas * Address review feedback * Address review feedback * Rename remaining type parameters to TKey and TValue * Fix manual formatting for logging levels * Fix spacing before comments --------- Co-authored-by: Ac_K <Acoustik666@gmail.com>
2023-06-28 16:41:38 +00:00
using IMemoryOwner<byte> reqDataOwner = ByteMemoryPool.Rent(messageSize);
2018-02-04 23:08:20 +00:00
Span<byte> reqDataSpan = reqDataOwner.Memory.Span;
_selfProcess.CpuMemory.Read(_selfThread.TlsAddress, reqDataSpan);
IpcMessage request = new IpcMessage(reqDataSpan, (long)_selfThread.TlsAddress);
return request;
2018-02-04 23:08:20 +00:00
}
private void FillHipcResponse(IpcMessage response, long result)
2018-02-04 23:08:20 +00:00
{
FillHipcResponse(response, result, ReadOnlySpan<byte>.Empty);
}
2018-02-04 23:08:20 +00:00
private void FillHipcResponse(IpcMessage response, long result, int value)
{
Span<byte> span = stackalloc byte[sizeof(int)];
BinaryPrimitives.WriteInt32LittleEndian(span, value);
FillHipcResponse(response, result, span);
}
2018-02-04 23:08:20 +00:00
private void FillHipcResponse(IpcMessage response, long result, ReadOnlySpan<byte> data)
{
response.Type = IpcMessageType.CmifResponse;
2018-02-04 23:08:20 +00:00
_responseDataStream.SetLength(0);
2018-02-04 23:08:20 +00:00
_responseDataStream.Write(IpcMagic.Sfco);
_responseDataStream.Write(result);
2018-02-04 23:08:20 +00:00
_responseDataStream.Write(data);
response.RawData = _responseDataStream.ToArray();
2018-02-04 23:08:20 +00:00
}
protected virtual void Dispose(bool disposing)
{
if (disposing && _selfThread != null)
{
if (_selfThread.HostThread.ManagedThreadId != Environment.CurrentManagedThreadId && _selfThread.HostThread.Join(ThreadJoinTimeout) == false)
{
Logger.Warning?.Print(LogClass.Service, $"The ServerBase thread didn't terminate within {ThreadJoinTimeout:g}, waiting longer.");
_selfThread.HostThread.Join(Timeout.Infinite);
}
if (Interlocked.Exchange(ref _isDisposed, 1) == 0)
{
foreach (IpcService service in _sessions.Values)
{
(service as IDisposable)?.Dispose();
service.DestroyAtExit();
}
_sessions.Clear();
_ports.Clear();
_handleLock.Dispose();
_requestDataReader.Dispose();
_requestDataStream.Dispose();
_responseDataWriter.Dispose();
_responseDataStream.Dispose();
InitDone.Dispose();
}
}
}
public void Dispose()
{
Dispose(true);
}
2018-02-04 23:08:20 +00:00
}
}