Code style fixes and nits on the HLE project (#355)

* Some style fixes and nits on ITimeZoneService

* Remove some unneeded usings

* Remove the Ryujinx.HLE.OsHle.Handles namespace

* Remove hbmenu automatic load on process exit

* Rename Ns to Device, rename Os to System, rename SystemState to State

* Move Exceptions and Utilities out of OsHle

* Rename OsHle to HOS

* Rename OsHle folder to HOS

* IManagerDisplayService and ISystemDisplayService style fixes

* BsdError shouldn't be public

* Add a empty new line before using static

* Remove unused file

* Some style fixes on NPDM

* Exit gracefully when the application is closed

* Code style fixes on IGeneralService

* Add 0x prefix on values printed as hex

* Small improvements on finalization code

* Move ProcessId and ThreadId out of AThreadState

* Rename VFs to FileSystem

* FsAccessHeader shouldn't be public. Also fix file names casing

* More case changes on NPDM

* Remove unused files

* Move using to the correct place on NPDM

* Use properties on KernelAccessControlMmio

* Address PR feedback
This commit is contained in:
gdkchan 2018-08-16 20:47:36 -03:00 committed by GitHub
parent 182d716867
commit 521751795a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
258 changed files with 1574 additions and 1546 deletions

View file

@ -0,0 +1,231 @@
using ChocolArm64.Memory;
using Ryujinx.HLE.HOS.Ipc;
using Ryujinx.HLE.HOS.Kernel;
using Ryujinx.HLE.HOS.Services.Nv.NvGpuAS;
using Ryujinx.HLE.HOS.Services.Nv.NvGpuGpu;
using Ryujinx.HLE.HOS.Services.Nv.NvHostChannel;
using Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl;
using Ryujinx.HLE.HOS.Services.Nv.NvMap;
using Ryujinx.HLE.Logging;
using System;
using System.Collections.Generic;
namespace Ryujinx.HLE.HOS.Services.Nv
{
class INvDrvServices : IpcService, IDisposable
{
private delegate int IoctlProcessor(ServiceCtx Context, int Cmd);
private Dictionary<int, ServiceProcessRequest> m_Commands;
public override IReadOnlyDictionary<int, ServiceProcessRequest> Commands => m_Commands;
private static Dictionary<string, IoctlProcessor> IoctlProcessors =
new Dictionary<string, IoctlProcessor>()
{
{ "/dev/nvhost-as-gpu", ProcessIoctlNvGpuAS },
{ "/dev/nvhost-ctrl", ProcessIoctlNvHostCtrl },
{ "/dev/nvhost-ctrl-gpu", ProcessIoctlNvGpuGpu },
{ "/dev/nvhost-gpu", ProcessIoctlNvHostGpu },
{ "/dev/nvmap", ProcessIoctlNvMap }
};
public static GlobalStateTable Fds { get; private set; }
private KEvent Event;
public INvDrvServices()
{
m_Commands = new Dictionary<int, ServiceProcessRequest>()
{
{ 0, Open },
{ 1, Ioctl },
{ 2, Close },
{ 3, Initialize },
{ 4, QueryEvent },
{ 8, SetClientPid },
{ 11, Ioctl },
{ 13, FinishInitialize }
};
Event = new KEvent();
}
static INvDrvServices()
{
Fds = new GlobalStateTable();
}
public long Open(ServiceCtx Context)
{
long NamePtr = Context.Request.SendBuff[0].Position;
string Name = AMemoryHelper.ReadAsciiString(Context.Memory, NamePtr);
int Fd = Fds.Add(Context.Process, new NvFd(Name));
Context.ResponseData.Write(Fd);
Context.ResponseData.Write(0);
return 0;
}
public long Ioctl(ServiceCtx Context)
{
int Fd = Context.RequestData.ReadInt32();
int Cmd = Context.RequestData.ReadInt32();
NvFd FdData = Fds.GetData<NvFd>(Context.Process, Fd);
int Result;
if (IoctlProcessors.TryGetValue(FdData.Name, out IoctlProcessor Process))
{
Result = Process(Context, Cmd);
}
else
{
throw new NotImplementedException($"{FdData.Name} {Cmd:x4}");
}
//TODO: Verify if the error codes needs to be translated.
Context.ResponseData.Write(Result);
return 0;
}
public long Close(ServiceCtx Context)
{
int Fd = Context.RequestData.ReadInt32();
Fds.Delete(Context.Process, Fd);
Context.ResponseData.Write(0);
return 0;
}
public long Initialize(ServiceCtx Context)
{
long TransferMemSize = Context.RequestData.ReadInt64();
int TransferMemHandle = Context.Request.HandleDesc.ToCopy[0];
NvMapIoctl.InitializeNvMap(Context);
Context.ResponseData.Write(0);
return 0;
}
public long QueryEvent(ServiceCtx Context)
{
int Fd = Context.RequestData.ReadInt32();
int EventId = Context.RequestData.ReadInt32();
//TODO: Use Fd/EventId, different channels have different events.
int Handle = Context.Process.HandleTable.OpenHandle(Event);
Context.Response.HandleDesc = IpcHandleDesc.MakeCopy(Handle);
Context.ResponseData.Write(0);
return 0;
}
public long SetClientPid(ServiceCtx Context)
{
long Pid = Context.RequestData.ReadInt64();
Context.ResponseData.Write(0);
return 0;
}
public long FinishInitialize(ServiceCtx Context)
{
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return 0;
}
private static int ProcessIoctlNvGpuAS(ServiceCtx Context, int Cmd)
{
return ProcessIoctl(Context, Cmd, NvGpuASIoctl.ProcessIoctl);
}
private static int ProcessIoctlNvHostCtrl(ServiceCtx Context, int Cmd)
{
return ProcessIoctl(Context, Cmd, NvHostCtrlIoctl.ProcessIoctl);
}
private static int ProcessIoctlNvGpuGpu(ServiceCtx Context, int Cmd)
{
return ProcessIoctl(Context, Cmd, NvGpuGpuIoctl.ProcessIoctl);
}
private static int ProcessIoctlNvHostGpu(ServiceCtx Context, int Cmd)
{
return ProcessIoctl(Context, Cmd, NvHostChannelIoctl.ProcessIoctlGpu);
}
private static int ProcessIoctlNvMap(ServiceCtx Context, int Cmd)
{
return ProcessIoctl(Context, Cmd, NvMapIoctl.ProcessIoctl);
}
private static int ProcessIoctl(ServiceCtx Context, int Cmd, IoctlProcessor Processor)
{
if (CmdIn(Cmd) && Context.Request.GetBufferType0x21().Position == 0)
{
Context.Device.Log.PrintError(LogClass.ServiceNv, "Input buffer is null!");
return NvResult.InvalidInput;
}
if (CmdOut(Cmd) && Context.Request.GetBufferType0x22().Position == 0)
{
Context.Device.Log.PrintError(LogClass.ServiceNv, "Output buffer is null!");
return NvResult.InvalidInput;
}
return Processor(Context, Cmd);
}
private static bool CmdIn(int Cmd)
{
return ((Cmd >> 30) & 1) != 0;
}
private static bool CmdOut(int Cmd)
{
return ((Cmd >> 31) & 1) != 0;
}
public static void UnloadProcess(Process Process)
{
Fds.DeleteProcess(Process);
NvGpuASIoctl.UnloadProcess(Process);
NvHostChannelIoctl.UnloadProcess(Process);
NvHostCtrlIoctl.UnloadProcess(Process);
NvMapIoctl.UnloadProcess(Process);
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool Disposing)
{
if (Disposing)
{
Event.Dispose();
}
}
}
}

View file

@ -0,0 +1,12 @@
namespace Ryujinx.HLE.HOS.Services.Nv
{
class NvFd
{
public string Name { get; private set; }
public NvFd(string Name)
{
this.Name = Name;
}
}
}

View file

@ -0,0 +1,11 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS
{
struct NvGpuASAllocSpace
{
public int Pages;
public int PageSize;
public int Flags;
public int Padding;
public long Offset;
}
}

View file

@ -0,0 +1,197 @@
using Ryujinx.HLE.Gpu.Memory;
using System.Collections.Generic;
namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS
{
class NvGpuASCtx
{
public NvGpuVmm Vmm { get; private set; }
private class Range
{
public ulong Start { get; private set; }
public ulong End { get; private set; }
public Range(long Position, long Size)
{
Start = (ulong)Position;
End = (ulong)Size + Start;
}
}
private class MappedMemory : Range
{
public long PhysicalAddress { get; private set; }
public bool VaAllocated { get; private set; }
public MappedMemory(
long Position,
long Size,
long PhysicalAddress,
bool VaAllocated) : base(Position, Size)
{
this.PhysicalAddress = PhysicalAddress;
this.VaAllocated = VaAllocated;
}
}
private SortedList<long, Range> Maps;
private SortedList<long, Range> Reservations;
public NvGpuASCtx(ServiceCtx Context)
{
Vmm = new NvGpuVmm(Context.Memory);
Maps = new SortedList<long, Range>();
Reservations = new SortedList<long, Range>();
}
public bool ValidateFixedBuffer(long Position, long Size)
{
long MapEnd = Position + Size;
//Check if size is valid (0 is also not allowed).
if ((ulong)MapEnd <= (ulong)Position)
{
return false;
}
//Check if address is page aligned.
if ((Position & NvGpuVmm.PageMask) != 0)
{
return false;
}
//Check if region is reserved.
if (BinarySearch(Reservations, Position) == null)
{
return false;
}
//Check for overlap with already mapped buffers.
Range Map = BinarySearchLt(Maps, MapEnd);
if (Map != null && Map.End > (ulong)Position)
{
return false;
}
return true;
}
public void AddMap(
long Position,
long Size,
long PhysicalAddress,
bool VaAllocated)
{
Maps.Add(Position, new MappedMemory(Position, Size, PhysicalAddress, VaAllocated));
}
public bool RemoveMap(long Position, out long Size)
{
Size = 0;
if (Maps.Remove(Position, out Range Value))
{
MappedMemory Map = (MappedMemory)Value;
if (Map.VaAllocated)
{
Size = (long)(Map.End - Map.Start);
}
return true;
}
return false;
}
public bool TryGetMapPhysicalAddress(long Position, out long PhysicalAddress)
{
Range Map = BinarySearch(Maps, Position);
if (Map != null)
{
PhysicalAddress = ((MappedMemory)Map).PhysicalAddress;
return true;
}
PhysicalAddress = 0;
return false;
}
public void AddReservation(long Position, long Size)
{
Reservations.Add(Position, new Range(Position, Size));
}
public bool RemoveReservation(long Position)
{
return Reservations.Remove(Position);
}
private Range BinarySearch(SortedList<long, Range> Lst, long Position)
{
int Left = 0;
int Right = Lst.Count - 1;
while (Left <= Right)
{
int Size = Right - Left;
int Middle = Left + (Size >> 1);
Range Rg = Lst.Values[Middle];
if ((ulong)Position >= Rg.Start && (ulong)Position < Rg.End)
{
return Rg;
}
if ((ulong)Position < Rg.Start)
{
Right = Middle - 1;
}
else
{
Left = Middle + 1;
}
}
return null;
}
private Range BinarySearchLt(SortedList<long, Range> Lst, long Position)
{
Range LtRg = null;
int Left = 0;
int Right = Lst.Count - 1;
while (Left <= Right)
{
int Size = Right - Left;
int Middle = Left + (Size >> 1);
Range Rg = Lst.Values[Middle];
if ((ulong)Position < Rg.Start)
{
Right = Middle - 1;
}
else
{
Left = Middle + 1;
LtRg = Rg;
}
}
return LtRg;
}
}
}

View file

@ -0,0 +1,329 @@
using ChocolArm64.Memory;
using Ryujinx.HLE.Gpu.Memory;
using Ryujinx.HLE.HOS.Services.Nv.NvMap;
using Ryujinx.HLE.Logging;
using System;
using System.Collections.Concurrent;
namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS
{
class NvGpuASIoctl
{
private const int FlagFixedOffset = 1;
private const int FlagRemapSubRange = 0x100;
private static ConcurrentDictionary<Process, NvGpuASCtx> ASCtxs;
static NvGpuASIoctl()
{
ASCtxs = new ConcurrentDictionary<Process, NvGpuASCtx>();
}
public static int ProcessIoctl(ServiceCtx Context, int Cmd)
{
switch (Cmd & 0xffff)
{
case 0x4101: return BindChannel (Context);
case 0x4102: return AllocSpace (Context);
case 0x4103: return FreeSpace (Context);
case 0x4105: return UnmapBuffer (Context);
case 0x4106: return MapBufferEx (Context);
case 0x4108: return GetVaRegions(Context);
case 0x4109: return InitializeEx(Context);
case 0x4114: return Remap (Context, Cmd);
}
throw new NotImplementedException(Cmd.ToString("x8"));
}
private static int BindChannel(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int AllocSpace(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvGpuASAllocSpace Args = AMemoryHelper.Read<NvGpuASAllocSpace>(Context.Memory, InputPosition);
NvGpuASCtx ASCtx = GetASCtx(Context);
ulong Size = (ulong)Args.Pages *
(ulong)Args.PageSize;
int Result = NvResult.Success;
lock (ASCtx)
{
//Note: When the fixed offset flag is not set,
//the Offset field holds the alignment size instead.
if ((Args.Flags & FlagFixedOffset) != 0)
{
Args.Offset = ASCtx.Vmm.ReserveFixed(Args.Offset, (long)Size);
}
else
{
Args.Offset = ASCtx.Vmm.Reserve((long)Size, Args.Offset);
}
if (Args.Offset < 0)
{
Args.Offset = 0;
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Failed to allocate size {Size:x16}!");
Result = NvResult.OutOfMemory;
}
else
{
ASCtx.AddReservation(Args.Offset, (long)Size);
}
}
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return Result;
}
private static int FreeSpace(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvGpuASAllocSpace Args = AMemoryHelper.Read<NvGpuASAllocSpace>(Context.Memory, InputPosition);
NvGpuASCtx ASCtx = GetASCtx(Context);
int Result = NvResult.Success;
lock (ASCtx)
{
ulong Size = (ulong)Args.Pages *
(ulong)Args.PageSize;
if (ASCtx.RemoveReservation(Args.Offset))
{
ASCtx.Vmm.Free(Args.Offset, (long)Size);
}
else
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv,
$"Failed to free offset 0x{Args.Offset:x16} size 0x{Size:x16}!");
Result = NvResult.InvalidInput;
}
}
return Result;
}
private static int UnmapBuffer(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvGpuASUnmapBuffer Args = AMemoryHelper.Read<NvGpuASUnmapBuffer>(Context.Memory, InputPosition);
NvGpuASCtx ASCtx = GetASCtx(Context);
lock (ASCtx)
{
if (ASCtx.RemoveMap(Args.Offset, out long Size))
{
if (Size != 0)
{
ASCtx.Vmm.Free(Args.Offset, Size);
}
}
else
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Invalid buffer offset {Args.Offset:x16}!");
}
}
return NvResult.Success;
}
private static int MapBufferEx(ServiceCtx Context)
{
const string MapErrorMsg = "Failed to map fixed buffer with offset 0x{0:x16} and size 0x{1:x16}!";
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvGpuASMapBufferEx Args = AMemoryHelper.Read<NvGpuASMapBufferEx>(Context.Memory, InputPosition);
NvGpuASCtx ASCtx = GetASCtx(Context);
NvMapHandle Map = NvMapIoctl.GetNvMapWithFb(Context, Args.NvMapHandle);
if (Map == null)
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Invalid NvMap handle 0x{Args.NvMapHandle:x8}!");
return NvResult.InvalidInput;
}
long PA;
if ((Args.Flags & FlagRemapSubRange) != 0)
{
lock (ASCtx)
{
if (ASCtx.TryGetMapPhysicalAddress(Args.Offset, out PA))
{
long VA = Args.Offset + Args.BufferOffset;
PA += Args.BufferOffset;
if (ASCtx.Vmm.Map(PA, VA, Args.MappingSize) < 0)
{
string Msg = string.Format(MapErrorMsg, VA, Args.MappingSize);
Context.Device.Log.PrintWarning(LogClass.ServiceNv, Msg);
return NvResult.InvalidInput;
}
return NvResult.Success;
}
else
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Address 0x{Args.Offset:x16} not mapped!");
return NvResult.InvalidInput;
}
}
}
PA = Map.Address + Args.BufferOffset;
long Size = Args.MappingSize;
if (Size == 0)
{
Size = (uint)Map.Size;
}
int Result = NvResult.Success;
lock (ASCtx)
{
//Note: When the fixed offset flag is not set,
//the Offset field holds the alignment size instead.
bool VaAllocated = (Args.Flags & FlagFixedOffset) == 0;
if (!VaAllocated)
{
if (ASCtx.ValidateFixedBuffer(Args.Offset, Size))
{
Args.Offset = ASCtx.Vmm.Map(PA, Args.Offset, Size);
}
else
{
string Msg = string.Format(MapErrorMsg, Args.Offset, Size);
Context.Device.Log.PrintWarning(LogClass.ServiceNv, Msg);
Result = NvResult.InvalidInput;
}
}
else
{
Args.Offset = ASCtx.Vmm.Map(PA, Size);
}
if (Args.Offset < 0)
{
Args.Offset = 0;
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Failed to map size 0x{Size:x16}!");
Result = NvResult.InvalidInput;
}
else
{
ASCtx.AddMap(Args.Offset, Size, PA, VaAllocated);
}
}
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return Result;
}
private static int GetVaRegions(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int InitializeEx(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int Remap(ServiceCtx Context, int Cmd)
{
int Count = ((Cmd >> 16) & 0xff) / 0x14;
long InputPosition = Context.Request.GetBufferType0x21().Position;
for (int Index = 0; Index < Count; Index++, InputPosition += 0x14)
{
NvGpuASRemap Args = AMemoryHelper.Read<NvGpuASRemap>(Context.Memory, InputPosition);
NvGpuVmm Vmm = GetASCtx(Context).Vmm;
NvMapHandle Map = NvMapIoctl.GetNvMapWithFb(Context, Args.NvMapHandle);
if (Map == null)
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Invalid NvMap handle 0x{Args.NvMapHandle:x8}!");
return NvResult.InvalidInput;
}
long Result = Vmm.Map(Map.Address, (long)(uint)Args.Offset << 16,
(long)(uint)Args.Pages << 16);
if (Result < 0)
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv,
$"Page 0x{Args.Offset:x16} size 0x{Args.Pages:x16} not allocated!");
return NvResult.InvalidInput;
}
}
return NvResult.Success;
}
public static NvGpuASCtx GetASCtx(ServiceCtx Context)
{
return ASCtxs.GetOrAdd(Context.Process, (Key) => new NvGpuASCtx(Context));
}
public static void UnloadProcess(Process Process)
{
ASCtxs.TryRemove(Process, out _);
}
}
}

View file

@ -0,0 +1,13 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS
{
struct NvGpuASMapBufferEx
{
public int Flags;
public int Kind;
public int NvMapHandle;
public int PageSize;
public long BufferOffset;
public long MappingSize;
public long Offset;
}
}

View file

@ -0,0 +1,12 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS
{
struct NvGpuASRemap
{
public short Flags;
public short Kind;
public int NvMapHandle;
public int Padding;
public int Offset;
public int Pages;
}
}

View file

@ -0,0 +1,7 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS
{
struct NvGpuASUnmapBuffer
{
public long Offset;
}
}

View file

@ -0,0 +1,8 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuGpu
{
struct NvGpuGpuGetActiveSlotMask
{
public int Slot;
public int Mask;
}
}

View file

@ -0,0 +1,43 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuGpu
{
struct NvGpuGpuGetCharacteristics
{
public long BufferSize;
public long BufferAddress;
public int Arch;
public int Impl;
public int Rev;
public int NumGpc;
public long L2CacheSize;
public long OnBoardVideoMemorySize;
public int NumTpcPerGpc;
public int BusType;
public int BigPageSize;
public int CompressionPageSize;
public int PdeCoverageBitCount;
public int AvailableBigPageSizes;
public int GpcMask;
public int SmArchSmVersion;
public int SmArchSpaVersion;
public int SmArchWarpCount;
public int GpuVaBitCount;
public int Reserved;
public long Flags;
public int TwodClass;
public int ThreedClass;
public int ComputeClass;
public int GpfifoClass;
public int InlineToMemoryClass;
public int DmaCopyClass;
public int MaxFbpsCount;
public int FbpEnMask;
public int MaxLtcPerFbp;
public int MaxLtsPerLtc;
public int MaxTexPerTpc;
public int MaxGpcCount;
public int RopL2EnMask0;
public int RopL2EnMask1;
public long ChipName;
public long GrCompbitStoreBaseHw;
}
}

View file

@ -0,0 +1,11 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuGpu
{
struct NvGpuGpuGetTpcMasks
{
public int MaskBufferSize;
public int Reserved;
public long MaskBufferAddress;
public int TpcMask;
public int Padding;
}
}

View file

@ -0,0 +1,187 @@
using ChocolArm64.Memory;
using Ryujinx.HLE.Logging;
using System;
using System.Diagnostics;
namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuGpu
{
class NvGpuGpuIoctl
{
private static Stopwatch PTimer;
private static double TicksToNs;
static NvGpuGpuIoctl()
{
PTimer = new Stopwatch();
PTimer.Start();
TicksToNs = (1.0 / Stopwatch.Frequency) * 1_000_000_000;
}
public static int ProcessIoctl(ServiceCtx Context, int Cmd)
{
switch (Cmd & 0xffff)
{
case 0x4701: return ZcullGetCtxSize (Context);
case 0x4702: return ZcullGetInfo (Context);
case 0x4703: return ZbcSetTable (Context);
case 0x4705: return GetCharacteristics(Context);
case 0x4706: return GetTpcMasks (Context);
case 0x4714: return GetActiveSlotMask (Context);
case 0x471c: return GetGpuTime (Context);
}
throw new NotImplementedException(Cmd.ToString("x8"));
}
private static int ZcullGetCtxSize(ServiceCtx Context)
{
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvGpuGpuZcullGetCtxSize Args = new NvGpuGpuZcullGetCtxSize();
Args.Size = 1;
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int ZcullGetInfo(ServiceCtx Context)
{
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvGpuGpuZcullGetInfo Args = new NvGpuGpuZcullGetInfo();
Args.WidthAlignPixels = 0x20;
Args.HeightAlignPixels = 0x20;
Args.PixelSquaresByAliquots = 0x400;
Args.AliquotTotal = 0x800;
Args.RegionByteMultiplier = 0x20;
Args.RegionHeaderSize = 0x20;
Args.SubregionHeaderSize = 0xc0;
Args.SubregionWidthAlignPixels = 0x20;
Args.SubregionHeightAlignPixels = 0x40;
Args.SubregionCount = 0x10;
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int ZbcSetTable(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int GetCharacteristics(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvGpuGpuGetCharacteristics Args = AMemoryHelper.Read<NvGpuGpuGetCharacteristics>(Context.Memory, InputPosition);
Args.BufferSize = 0xa0;
Args.Arch = 0x120;
Args.Impl = 0xb;
Args.Rev = 0xa1;
Args.NumGpc = 0x1;
Args.L2CacheSize = 0x40000;
Args.OnBoardVideoMemorySize = 0x0;
Args.NumTpcPerGpc = 0x2;
Args.BusType = 0x20;
Args.BigPageSize = 0x20000;
Args.CompressionPageSize = 0x20000;
Args.PdeCoverageBitCount = 0x1b;
Args.AvailableBigPageSizes = 0x30000;
Args.GpcMask = 0x1;
Args.SmArchSmVersion = 0x503;
Args.SmArchSpaVersion = 0x503;
Args.SmArchWarpCount = 0x80;
Args.GpuVaBitCount = 0x28;
Args.Reserved = 0x0;
Args.Flags = 0x55;
Args.TwodClass = 0x902d;
Args.ThreedClass = 0xb197;
Args.ComputeClass = 0xb1c0;
Args.GpfifoClass = 0xb06f;
Args.InlineToMemoryClass = 0xa140;
Args.DmaCopyClass = 0xb0b5;
Args.MaxFbpsCount = 0x1;
Args.FbpEnMask = 0x0;
Args.MaxLtcPerFbp = 0x2;
Args.MaxLtsPerLtc = 0x1;
Args.MaxTexPerTpc = 0x0;
Args.MaxGpcCount = 0x1;
Args.RopL2EnMask0 = 0x21d70;
Args.RopL2EnMask1 = 0x0;
Args.ChipName = 0x6230326d67;
Args.GrCompbitStoreBaseHw = 0x0;
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return NvResult.Success;
}
private static int GetTpcMasks(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvGpuGpuGetTpcMasks Args = AMemoryHelper.Read<NvGpuGpuGetTpcMasks>(Context.Memory, InputPosition);
if (Args.MaskBufferSize != 0)
{
Args.TpcMask = 3;
}
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return NvResult.Success;
}
private static int GetActiveSlotMask(ServiceCtx Context)
{
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvGpuGpuGetActiveSlotMask Args = new NvGpuGpuGetActiveSlotMask();
Args.Slot = 0x07;
Args.Mask = 0x01;
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int GetGpuTime(ServiceCtx Context)
{
long OutputPosition = Context.Request.GetBufferType0x22().Position;
Context.Memory.WriteInt64(OutputPosition, GetPTimerNanoSeconds());
return NvResult.Success;
}
private static long GetPTimerNanoSeconds()
{
double Ticks = PTimer.ElapsedTicks;
return (long)(Ticks * TicksToNs) & 0xff_ffff_ffff_ffff;
}
}
}

View file

@ -0,0 +1,7 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuGpu
{
struct NvGpuGpuZcullGetCtxSize
{
public int Size;
}
}

View file

@ -0,0 +1,16 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuGpu
{
struct NvGpuGpuZcullGetInfo
{
public int WidthAlignPixels;
public int HeightAlignPixels;
public int PixelSquaresByAliquots;
public int AliquotTotal;
public int RegionByteMultiplier;
public int RegionHeaderSize;
public int SubregionHeaderSize;
public int SubregionWidthAlignPixels;
public int SubregionHeightAlignPixels;
public int SubregionCount;
}
}

View file

@ -0,0 +1,10 @@
namespace Ryujinx.HLE.HOS.Services.Nv
{
static class NvHelper
{
public static void Crash()
{
}
}
}

View file

@ -0,0 +1,7 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvHostChannel
{
class NvChannel
{
public int Timeout;
}
}

View file

@ -0,0 +1,7 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvHostChannel
{
enum NvChannelName
{
Gpu
}
}

View file

@ -0,0 +1,210 @@
using ChocolArm64.Memory;
using Ryujinx.HLE.Gpu.Memory;
using Ryujinx.HLE.HOS.Services.Nv.NvGpuAS;
using Ryujinx.HLE.Logging;
using System;
using System.Collections.Concurrent;
namespace Ryujinx.HLE.HOS.Services.Nv.NvHostChannel
{
class NvHostChannelIoctl
{
private class ChannelsPerProcess
{
public ConcurrentDictionary<NvChannelName, NvChannel> Channels { get; private set; }
public ChannelsPerProcess()
{
Channels = new ConcurrentDictionary<NvChannelName, NvChannel>();
Channels.TryAdd(NvChannelName.Gpu, new NvChannel());
}
}
private static ConcurrentDictionary<Process, ChannelsPerProcess> Channels;
static NvHostChannelIoctl()
{
Channels = new ConcurrentDictionary<Process, ChannelsPerProcess>();
}
public static int ProcessIoctlGpu(ServiceCtx Context, int Cmd)
{
return ProcessIoctl(Context, NvChannelName.Gpu, Cmd);
}
public static int ProcessIoctl(ServiceCtx Context, NvChannelName Channel, int Cmd)
{
switch (Cmd & 0xffff)
{
case 0x4714: return SetUserData (Context);
case 0x4801: return SetNvMap (Context);
case 0x4803: return SetTimeout (Context, Channel);
case 0x4808: return SubmitGpfifo (Context);
case 0x4809: return AllocObjCtx (Context);
case 0x480b: return ZcullBind (Context);
case 0x480c: return SetErrorNotifier (Context);
case 0x480d: return SetPriority (Context);
case 0x481a: return AllocGpfifoEx2 (Context);
case 0x481b: return KickoffPbWithAttr(Context);
}
throw new NotImplementedException(Cmd.ToString("x8"));
}
private static int SetUserData(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int SetNvMap(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int SetTimeout(ServiceCtx Context, NvChannelName Channel)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
GetChannel(Context, Channel).Timeout = Context.Memory.ReadInt32(InputPosition);
return NvResult.Success;
}
private static int SubmitGpfifo(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvHostChannelSubmitGpfifo Args = AMemoryHelper.Read<NvHostChannelSubmitGpfifo>(Context.Memory, InputPosition);
NvGpuVmm Vmm = NvGpuASIoctl.GetASCtx(Context).Vmm;;
for (int Index = 0; Index < Args.NumEntries; Index++)
{
long Gpfifo = Context.Memory.ReadInt64(InputPosition + 0x18 + Index * 8);
PushGpfifo(Context, Vmm, Gpfifo);
}
Args.SyncptId = 0;
Args.SyncptValue = 0;
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return NvResult.Success;
}
private static int AllocObjCtx(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int ZcullBind(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int SetErrorNotifier(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int SetPriority(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int AllocGpfifoEx2(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int KickoffPbWithAttr(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvHostChannelSubmitGpfifo Args = AMemoryHelper.Read<NvHostChannelSubmitGpfifo>(Context.Memory, InputPosition);
NvGpuVmm Vmm = NvGpuASIoctl.GetASCtx(Context).Vmm;;
for (int Index = 0; Index < Args.NumEntries; Index++)
{
long Gpfifo = Context.Memory.ReadInt64(Args.Address + Index * 8);
PushGpfifo(Context, Vmm, Gpfifo);
}
Args.SyncptId = 0;
Args.SyncptValue = 0;
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return NvResult.Success;
}
private static void PushGpfifo(ServiceCtx Context, NvGpuVmm Vmm, long Gpfifo)
{
long VA = Gpfifo & 0xff_ffff_ffff;
int Size = (int)(Gpfifo >> 40) & 0x7ffffc;
byte[] Data = Vmm.ReadBytes(VA, Size);
NvGpuPBEntry[] PushBuffer = NvGpuPushBuffer.Decode(Data);
Context.Device.Gpu.Fifo.PushBuffer(Vmm, PushBuffer);
}
public static NvChannel GetChannel(ServiceCtx Context, NvChannelName Channel)
{
ChannelsPerProcess Cpp = Channels.GetOrAdd(Context.Process, (Key) =>
{
return new ChannelsPerProcess();
});
return Cpp.Channels[Channel];
}
public static void UnloadProcess(Process Process)
{
Channels.TryRemove(Process, out _);
}
}
}

View file

@ -0,0 +1,11 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvHostChannel
{
struct NvHostChannelSubmitGpfifo
{
public long Address;
public int NumEntries;
public int Flags;
public int SyncptId;
public int SyncptValue;
}
}

View file

@ -0,0 +1,398 @@
using ChocolArm64.Memory;
using Ryujinx.HLE.Logging;
using System;
using System.Collections.Concurrent;
using System.Text;
using System.Threading;
namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl
{
class NvHostCtrlIoctl
{
private static ConcurrentDictionary<Process, NvHostCtrlUserCtx> UserCtxs;
private static bool IsProductionMode = true;
static NvHostCtrlIoctl()
{
UserCtxs = new ConcurrentDictionary<Process, NvHostCtrlUserCtx>();
if (Set.NxSettings.Settings.TryGetValue("nv!rmos_set_production_mode", out object ProductionModeSetting))
{
IsProductionMode = ((string)ProductionModeSetting) != "0"; // Default value is ""
}
}
public static int ProcessIoctl(ServiceCtx Context, int Cmd)
{
switch (Cmd & 0xffff)
{
case 0x0014: return SyncptRead (Context);
case 0x0015: return SyncptIncr (Context);
case 0x0016: return SyncptWait (Context);
case 0x0019: return SyncptWaitEx (Context);
case 0x001a: return SyncptReadMax (Context);
case 0x001b: return GetConfig (Context);
case 0x001d: return EventWait (Context);
case 0x001e: return EventWaitAsync(Context);
case 0x001f: return EventRegister (Context);
}
throw new NotImplementedException(Cmd.ToString("x8"));
}
private static int SyncptRead(ServiceCtx Context)
{
return SyncptReadMinOrMax(Context, Max: false);
}
private static int SyncptIncr(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
int Id = Context.Memory.ReadInt32(InputPosition);
if ((uint)Id >= NvHostSyncpt.SyncptsCount)
{
return NvResult.InvalidInput;
}
GetUserCtx(Context).Syncpt.Increment(Id);
return NvResult.Success;
}
private static int SyncptWait(ServiceCtx Context)
{
return SyncptWait(Context, Extended: false);
}
private static int SyncptWaitEx(ServiceCtx Context)
{
return SyncptWait(Context, Extended: true);
}
private static int SyncptReadMax(ServiceCtx Context)
{
return SyncptReadMinOrMax(Context, Max: true);
}
private static int GetConfig(ServiceCtx Context)
{
if (!IsProductionMode)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
string Domain = AMemoryHelper.ReadAsciiString(Context.Memory, InputPosition + 0, 0x41);
string Name = AMemoryHelper.ReadAsciiString(Context.Memory, InputPosition + 0x41, 0x41);
if (Set.NxSettings.Settings.TryGetValue($"{Domain}!{Name}", out object NvSetting))
{
byte[] SettingBuffer = new byte[0x101];
if (NvSetting is string StringValue)
{
if (StringValue.Length > 0x100)
{
Context.Device.Log.PrintError(Logging.LogClass.ServiceNv, $"{Domain}!{Name} String value size is too big!");
}
else
{
SettingBuffer = Encoding.ASCII.GetBytes(StringValue + "\0");
}
}
if (NvSetting is int IntValue)
{
SettingBuffer = BitConverter.GetBytes(IntValue);
}
else if (NvSetting is bool BoolValue)
{
SettingBuffer[0] = BoolValue ? (byte)1 : (byte)0;
}
else
{
throw new NotImplementedException(NvSetting.GetType().Name);
}
Context.Memory.WriteBytes(OutputPosition + 0x82, SettingBuffer);
Context.Device.Log.PrintDebug(Logging.LogClass.ServiceNv, $"Got setting {Domain}!{Name}");
}
return NvResult.Success;
}
return NvResult.NotAvailableInProduction;
}
private static int EventWait(ServiceCtx Context)
{
return EventWait(Context, Async: false);
}
private static int EventWaitAsync(ServiceCtx Context)
{
return EventWait(Context, Async: true);
}
private static int EventRegister(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
int EventId = Context.Memory.ReadInt32(InputPosition);
Context.Device.Log.PrintStub(LogClass.ServiceNv, "Stubbed.");
return NvResult.Success;
}
private static int SyncptReadMinOrMax(ServiceCtx Context, bool Max)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvHostCtrlSyncptRead Args = AMemoryHelper.Read<NvHostCtrlSyncptRead>(Context.Memory, InputPosition);
if ((uint)Args.Id >= NvHostSyncpt.SyncptsCount)
{
return NvResult.InvalidInput;
}
if (Max)
{
Args.Value = GetUserCtx(Context).Syncpt.GetMax(Args.Id);
}
else
{
Args.Value = GetUserCtx(Context).Syncpt.GetMin(Args.Id);
}
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return NvResult.Success;
}
private static int SyncptWait(ServiceCtx Context, bool Extended)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvHostCtrlSyncptWait Args = AMemoryHelper.Read<NvHostCtrlSyncptWait>(Context.Memory, InputPosition);
NvHostSyncpt Syncpt = GetUserCtx(Context).Syncpt;
if ((uint)Args.Id >= NvHostSyncpt.SyncptsCount)
{
return NvResult.InvalidInput;
}
int Result;
if (Syncpt.MinCompare(Args.Id, Args.Thresh))
{
Result = NvResult.Success;
}
else if (Args.Timeout == 0)
{
Result = NvResult.TryAgain;
}
else
{
Context.Device.Log.PrintDebug(LogClass.ServiceNv, "Waiting syncpt with timeout of " + Args.Timeout + "ms...");
using (ManualResetEvent WaitEvent = new ManualResetEvent(false))
{
Syncpt.AddWaiter(Args.Thresh, WaitEvent);
//Note: Negative (> INT_MAX) timeouts aren't valid on .NET,
//in this case we just use the maximum timeout possible.
int Timeout = Args.Timeout;
if (Timeout < -1)
{
Timeout = int.MaxValue;
}
if (Timeout == -1)
{
WaitEvent.WaitOne();
Result = NvResult.Success;
}
else if (WaitEvent.WaitOne(Timeout))
{
Result = NvResult.Success;
}
else
{
Result = NvResult.TimedOut;
}
}
Context.Device.Log.PrintDebug(LogClass.ServiceNv, "Resuming...");
}
if (Extended)
{
Context.Memory.WriteInt32(OutputPosition + 0xc, Syncpt.GetMin(Args.Id));
}
return Result;
}
private static int EventWait(ServiceCtx Context, bool Async)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvHostCtrlSyncptWaitEx Args = AMemoryHelper.Read<NvHostCtrlSyncptWaitEx>(Context.Memory, InputPosition);
if ((uint)Args.Id >= NvHostSyncpt.SyncptsCount)
{
return NvResult.InvalidInput;
}
void WriteArgs()
{
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
}
NvHostSyncpt Syncpt = GetUserCtx(Context).Syncpt;
if (Syncpt.MinCompare(Args.Id, Args.Thresh))
{
Args.Value = Syncpt.GetMin(Args.Id);
WriteArgs();
return NvResult.Success;
}
if (!Async)
{
Args.Value = 0;
}
if (Args.Timeout == 0)
{
WriteArgs();
return NvResult.TryAgain;
}
NvHostEvent Event;
int Result, EventIndex;
if (Async)
{
EventIndex = Args.Value;
if ((uint)EventIndex >= NvHostCtrlUserCtx.EventsCount)
{
return NvResult.InvalidInput;
}
Event = GetUserCtx(Context).Events[EventIndex];
}
else
{
Event = GetFreeEvent(Context, Syncpt, Args.Id, out EventIndex);
}
if (Event != null &&
(Event.State == NvHostEventState.Registered ||
Event.State == NvHostEventState.Free))
{
Event.Id = Args.Id;
Event.Thresh = Args.Thresh;
Event.State = NvHostEventState.Waiting;
if (!Async)
{
Args.Value = ((Args.Id & 0xfff) << 16) | 0x10000000;
}
else
{
Args.Value = Args.Id << 4;
}
Args.Value |= EventIndex;
Result = NvResult.TryAgain;
}
else
{
Result = NvResult.InvalidInput;
}
WriteArgs();
return Result;
}
private static NvHostEvent GetFreeEvent(
ServiceCtx Context,
NvHostSyncpt Syncpt,
int Id,
out int EventIndex)
{
NvHostEvent[] Events = GetUserCtx(Context).Events;
EventIndex = NvHostCtrlUserCtx.EventsCount;
int NullIndex = NvHostCtrlUserCtx.EventsCount;
for (int Index = 0; Index < NvHostCtrlUserCtx.EventsCount; Index++)
{
NvHostEvent Event = Events[Index];
if (Event != null)
{
if (Event.State == NvHostEventState.Registered ||
Event.State == NvHostEventState.Free)
{
EventIndex = Index;
if (Event.Id == Id)
{
return Event;
}
}
}
else if (NullIndex == NvHostCtrlUserCtx.EventsCount)
{
NullIndex = Index;
}
}
if (NullIndex < NvHostCtrlUserCtx.EventsCount)
{
EventIndex = NullIndex;
return Events[NullIndex] = new NvHostEvent();
}
if (EventIndex < NvHostCtrlUserCtx.EventsCount)
{
return Events[EventIndex];
}
return null;
}
public static NvHostCtrlUserCtx GetUserCtx(ServiceCtx Context)
{
return UserCtxs.GetOrAdd(Context.Process, (Key) => new NvHostCtrlUserCtx());
}
public static void UnloadProcess(Process Process)
{
UserCtxs.TryRemove(Process, out _);
}
}
}

View file

@ -0,0 +1,8 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl
{
struct NvHostCtrlSyncptRead
{
public int Id;
public int Value;
}
}

View file

@ -0,0 +1,9 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl
{
struct NvHostCtrlSyncptWait
{
public int Id;
public int Thresh;
public int Timeout;
}
}

View file

@ -0,0 +1,10 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl
{
struct NvHostCtrlSyncptWaitEx
{
public int Id;
public int Thresh;
public int Timeout;
public int Value;
}
}

View file

@ -0,0 +1,19 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl
{
class NvHostCtrlUserCtx
{
public const int LocksCount = 16;
public const int EventsCount = 64;
public NvHostSyncpt Syncpt { get; private set; }
public NvHostEvent[] Events { get; private set; }
public NvHostCtrlUserCtx()
{
Syncpt = new NvHostSyncpt();
Events = new NvHostEvent[EventsCount];
}
}
}

View file

@ -0,0 +1,10 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl
{
class NvHostEvent
{
public int Id;
public int Thresh;
public NvHostEventState State;
}
}

View file

@ -0,0 +1,10 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl
{
enum NvHostEventState
{
Registered = 0,
Waiting = 1,
Busy = 2,
Free = 5
}
}

View file

@ -0,0 +1,107 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl
{
class NvHostSyncpt
{
public const int SyncptsCount = 192;
private int[] CounterMin;
private int[] CounterMax;
private long EventMask;
private ConcurrentDictionary<EventWaitHandle, int> Waiters;
public NvHostSyncpt()
{
CounterMin = new int[SyncptsCount];
CounterMax = new int[SyncptsCount];
Waiters = new ConcurrentDictionary<EventWaitHandle, int>();
}
public int GetMin(int Id)
{
return CounterMin[Id];
}
public int GetMax(int Id)
{
return CounterMax[Id];
}
public int Increment(int Id)
{
if (((EventMask >> Id) & 1) != 0)
{
Interlocked.Increment(ref CounterMax[Id]);
}
return IncrementMin(Id);
}
public int IncrementMin(int Id)
{
int Value = Interlocked.Increment(ref CounterMin[Id]);
WakeUpWaiters(Id, Value);
return Value;
}
public int IncrementMax(int Id)
{
return Interlocked.Increment(ref CounterMax[Id]);
}
public void AddWaiter(int Threshold, EventWaitHandle WaitEvent)
{
if (!Waiters.TryAdd(WaitEvent, Threshold))
{
throw new InvalidOperationException();
}
}
public bool RemoveWaiter(EventWaitHandle WaitEvent)
{
return Waiters.TryRemove(WaitEvent, out _);
}
private void WakeUpWaiters(int Id, int NewValue)
{
foreach (KeyValuePair<EventWaitHandle, int> KV in Waiters)
{
if (MinCompare(Id, NewValue, CounterMax[Id], KV.Value))
{
KV.Key.Set();
Waiters.TryRemove(KV.Key, out _);
}
}
}
public bool MinCompare(int Id, int Threshold)
{
return MinCompare(Id, CounterMin[Id], CounterMax[Id], Threshold);
}
private bool MinCompare(int Id, int Min, int Max, int Threshold)
{
int MinDiff = Min - Threshold;
int MaxDiff = Max - Threshold;
if (((EventMask >> Id) & 1) != 0)
{
return MinDiff >= 0;
}
else
{
return (uint)MaxDiff >= (uint)MinDiff;
}
}
}
}

View file

@ -0,0 +1,12 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvMap
{
struct NvMapAlloc
{
public int Handle;
public int HeapMask;
public int Flags;
public int Align;
public long Kind;
public long Address;
}
}

View file

@ -0,0 +1,8 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvMap
{
struct NvMapCreate
{
public int Size;
public int Handle;
}
}

View file

@ -0,0 +1,11 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvMap
{
struct NvMapFree
{
public int Handle;
public int Padding;
public long Address;
public int Size;
public int Flags;
}
}

View file

@ -0,0 +1,8 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvMap
{
struct NvMapFromId
{
public int Id;
public int Handle;
}
}

View file

@ -0,0 +1,8 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvMap
{
struct NvMapGetId
{
public int Id;
public int Handle;
}
}

View file

@ -0,0 +1,37 @@
using System.Threading;
namespace Ryujinx.HLE.HOS.Services.Nv.NvMap
{
class NvMapHandle
{
public int Handle;
public int Id;
public int Size;
public int Align;
public int Kind;
public long Address;
public bool Allocated;
private long Dupes;
public NvMapHandle()
{
Dupes = 1;
}
public NvMapHandle(int Size) : this()
{
this.Size = Size;
}
public void IncrementRefCount()
{
Interlocked.Increment(ref Dupes);
}
public long DecrementRefCount()
{
return Interlocked.Decrement(ref Dupes);
}
}
}

View file

@ -0,0 +1,12 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvMap
{
enum NvMapHandleParam
{
Size = 1,
Align = 2,
Base = 3,
Heap = 4,
Kind = 5,
Compr = 6
}
}

View file

@ -0,0 +1,302 @@
using ChocolArm64.Memory;
using Ryujinx.HLE.Gpu.Memory;
using Ryujinx.HLE.Logging;
using Ryujinx.HLE.Utilities;
using System.Collections.Concurrent;
namespace Ryujinx.HLE.HOS.Services.Nv.NvMap
{
class NvMapIoctl
{
private const int FlagNotFreedYet = 1;
private static ConcurrentDictionary<Process, IdDictionary> Maps;
static NvMapIoctl()
{
Maps = new ConcurrentDictionary<Process, IdDictionary>();
}
public static int ProcessIoctl(ServiceCtx Context, int Cmd)
{
switch (Cmd & 0xffff)
{
case 0x0101: return Create(Context);
case 0x0103: return FromId(Context);
case 0x0104: return Alloc (Context);
case 0x0105: return Free (Context);
case 0x0109: return Param (Context);
case 0x010e: return GetId (Context);
}
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Unsupported Ioctl command 0x{Cmd:x8}!");
return NvResult.NotSupported;
}
private static int Create(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvMapCreate Args = AMemoryHelper.Read<NvMapCreate>(Context.Memory, InputPosition);
if (Args.Size == 0)
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Invalid size 0x{Args.Size:x8}!");
return NvResult.InvalidInput;
}
int Size = IntUtils.AlignUp(Args.Size, NvGpuVmm.PageSize);
Args.Handle = AddNvMap(Context, new NvMapHandle(Size));
Context.Device.Log.PrintInfo(LogClass.ServiceNv, $"Created map {Args.Handle} with size 0x{Size:x8}!");
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return NvResult.Success;
}
private static int FromId(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvMapFromId Args = AMemoryHelper.Read<NvMapFromId>(Context.Memory, InputPosition);
NvMapHandle Map = GetNvMap(Context, Args.Id);
if (Map == null)
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{Args.Handle:x8}!");
return NvResult.InvalidInput;
}
Map.IncrementRefCount();
Args.Handle = Args.Id;
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return NvResult.Success;
}
private static int Alloc(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvMapAlloc Args = AMemoryHelper.Read<NvMapAlloc>(Context.Memory, InputPosition);
NvMapHandle Map = GetNvMap(Context, Args.Handle);
if (Map == null)
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{Args.Handle:x8}!");
return NvResult.InvalidInput;
}
if ((Args.Align & (Args.Align - 1)) != 0)
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Invalid alignment 0x{Args.Align:x8}!");
return NvResult.InvalidInput;
}
if ((uint)Args.Align < NvGpuVmm.PageSize)
{
Args.Align = NvGpuVmm.PageSize;
}
int Result = NvResult.Success;
if (!Map.Allocated)
{
Map.Allocated = true;
Map.Align = Args.Align;
Map.Kind = (byte)Args.Kind;
int Size = IntUtils.AlignUp(Map.Size, NvGpuVmm.PageSize);
long Address = Args.Address;
if (Address == 0)
{
//When the address is zero, we need to allocate
//our own backing memory for the NvMap.
//TODO: Is this allocation inside the transfer memory?
if (!Context.Device.Memory.Allocator.TryAllocate((uint)Size, out Address))
{
Result = NvResult.OutOfMemory;
}
}
if (Result == NvResult.Success)
{
Map.Size = Size;
Map.Address = Address;
}
}
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return Result;
}
private static int Free(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvMapFree Args = AMemoryHelper.Read<NvMapFree>(Context.Memory, InputPosition);
NvMapHandle Map = GetNvMap(Context, Args.Handle);
if (Map == null)
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{Args.Handle:x8}!");
return NvResult.InvalidInput;
}
if (Map.DecrementRefCount() <= 0)
{
DeleteNvMap(Context, Args.Handle);
Context.Device.Log.PrintInfo(LogClass.ServiceNv, $"Deleted map {Args.Handle}!");
Args.Address = Map.Address;
Args.Flags = 0;
}
else
{
Args.Address = 0;
Args.Flags = FlagNotFreedYet;
}
Args.Size = Map.Size;
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return NvResult.Success;
}
private static int Param(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvMapParam Args = AMemoryHelper.Read<NvMapParam>(Context.Memory, InputPosition);
NvMapHandle Map = GetNvMap(Context, Args.Handle);
if (Map == null)
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{Args.Handle:x8}!");
return NvResult.InvalidInput;
}
switch ((NvMapHandleParam)Args.Param)
{
case NvMapHandleParam.Size: Args.Result = Map.Size; break;
case NvMapHandleParam.Align: Args.Result = Map.Align; break;
case NvMapHandleParam.Heap: Args.Result = 0x40000000; break;
case NvMapHandleParam.Kind: Args.Result = Map.Kind; break;
case NvMapHandleParam.Compr: Args.Result = 0; break;
//Note: Base is not supported and returns an error.
//Any other value also returns an error.
default: return NvResult.InvalidInput;
}
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return NvResult.Success;
}
private static int GetId(ServiceCtx Context)
{
long InputPosition = Context.Request.GetBufferType0x21().Position;
long OutputPosition = Context.Request.GetBufferType0x22().Position;
NvMapGetId Args = AMemoryHelper.Read<NvMapGetId>(Context.Memory, InputPosition);
NvMapHandle Map = GetNvMap(Context, Args.Handle);
if (Map == null)
{
Context.Device.Log.PrintWarning(LogClass.ServiceNv, $"Invalid handle 0x{Args.Handle:x8}!");
return NvResult.InvalidInput;
}
Args.Id = Args.Handle;
AMemoryHelper.Write(Context.Memory, OutputPosition, Args);
return NvResult.Success;
}
private static int AddNvMap(ServiceCtx Context, NvMapHandle Map)
{
IdDictionary Dict = Maps.GetOrAdd(Context.Process, (Key) =>
{
IdDictionary NewDict = new IdDictionary();
NewDict.Add(0, new NvMapHandle());
return NewDict;
});
return Dict.Add(Map);
}
private static bool DeleteNvMap(ServiceCtx Context, int Handle)
{
if (Maps.TryGetValue(Context.Process, out IdDictionary Dict))
{
return Dict.Delete(Handle) != null;
}
return false;
}
public static void InitializeNvMap(ServiceCtx Context)
{
IdDictionary Dict = Maps.GetOrAdd(Context.Process, (Key) =>new IdDictionary());
Dict.Add(0, new NvMapHandle());
}
public static NvMapHandle GetNvMapWithFb(ServiceCtx Context, int Handle)
{
if (Maps.TryGetValue(Context.Process, out IdDictionary Dict))
{
return Dict.GetData<NvMapHandle>(Handle);
}
return null;
}
public static NvMapHandle GetNvMap(ServiceCtx Context, int Handle)
{
if (Handle != 0 && Maps.TryGetValue(Context.Process, out IdDictionary Dict))
{
return Dict.GetData<NvMapHandle>(Handle);
}
return null;
}
public static void UnloadProcess(Process Process)
{
Maps.TryRemove(Process, out _);
}
}
}

View file

@ -0,0 +1,9 @@
namespace Ryujinx.HLE.HOS.Services.Nv.NvMap
{
struct NvMapParam
{
public int Handle;
public int Param;
public int Result;
}
}

View file

@ -0,0 +1,14 @@
namespace Ryujinx.HLE.HOS.Services.Nv
{
static class NvResult
{
public const int NotAvailableInProduction = 196614;
public const int Success = 0;
public const int TryAgain = -11;
public const int OutOfMemory = -12;
public const int InvalidInput = -22;
public const int NotSupported = -25;
public const int Restart = -85;
public const int TimedOut = -110;
}
}