Add a Multithreading layer for the GAL, multi-thread shader compilation at runtime (#2501)

* Initial Implementation

About as fast as nvidia GL multithreading, can be improved with faster command queuing.

* Struct based command list

Speeds up a bit. Still a lot of time lost to resource copy.

* Do shader init while the render thread is active.

* Introduce circular span pool V1

Ideally should be able to use structs instead of references for storing these spans on commands. Will try that next.

* Refactor SpanRef some more

Use a struct to represent SpanRef, rather than a reference.

* Flush buffers on background thread

* Use a span for UpdateRenderScale.

Much faster than copying the array.

* Calculate command size using reflection

* WIP parallel shaders

* Some minor optimisation

* Only 2 max refs per command now.

The command with 3 refs is gone. 😌

* Don't cast on the GPU side

* Remove redundant casts, force sync on window present

* Fix Shader Cache

* Fix host shader save.

* Fixup to work with new renderer stuff

* Make command Run static, use array of delegates as lookup

Profile says this takes less time than the previous way.

* Bring up to date

* Add settings toggle. Fix Muiltithreading Off mode.

* Fix warning.

* Release tracking lock for flushes

* Fix Conditional Render fast path with threaded gal

* Make handle iteration safe when releasing the lock

This is mostly temporary.

* Attempt to set backend threading on driver

Only really works on nvidia before launching a game.

* Fix race condition with BufferModifiedRangeList, exceptions in tracking actions

* Update buffer set commands

* Some cleanup

* Only use stutter workaround when using opengl renderer non-threaded

* Add host-conditional reservation of counter events

There has always been the possibility that conditional rendering could use a query object just as it is disposed by the counter queue. This change makes it so that when the host decides to use host conditional rendering, the query object is reserved so that it cannot be deleted. Counter events can optionally start reserved, as the threaded implementation can reserve them before the backend creates them, and there would otherwise be a short amount of time where the counter queue could dispose the event before a call to reserve it could be made.

* Address Feedback

* Make counter flush tracked again.

Hopefully does not cause any issues this time.

* Wait for FlushTo on the main queue thread.

Currently assumes only one thread will want to FlushTo (in this case, the GPU thread)

* Add SDL2 headless integration

* Add HLE macro commands.

Co-authored-by: Mary <mary@mary.zone>
This commit is contained in:
riperiperi
2021-08-26 23:31:29 +01:00
committed by GitHub
parent 501c3d5cea
commit ec3e848d79
143 changed files with 4491 additions and 200 deletions

View File

@ -0,0 +1,107 @@
using Ryujinx.Graphics.GAL.Multithreading.Resources.Programs;
using System;
using System.Collections.Generic;
using System.Threading;
namespace Ryujinx.Graphics.GAL.Multithreading.Resources
{
/// <summary>
/// A structure handling multithreaded compilation for programs.
/// </summary>
class ProgramQueue
{
private const int MaxConcurrentCompilations = 8;
private IRenderer _renderer;
private Queue<IProgramRequest> _toCompile;
private List<ThreadedProgram> _inProgress;
public ProgramQueue(IRenderer renderer)
{
_renderer = renderer;
_toCompile = new Queue<IProgramRequest>();
_inProgress = new List<ThreadedProgram>();
}
public void Add(IProgramRequest request)
{
lock (_toCompile)
{
_toCompile.Enqueue(request);
}
}
public void ProcessQueue()
{
for (int i = 0; i < _inProgress.Count; i++)
{
ThreadedProgram program = _inProgress[i];
ProgramLinkStatus status = program.Base.CheckProgramLink(false);
if (status != ProgramLinkStatus.Incomplete)
{
program.Compiled = true;
_inProgress.RemoveAt(i--);
}
}
int freeSpace = MaxConcurrentCompilations - _inProgress.Count;
for (int i = 0; i < freeSpace; i++)
{
// Begin compilation of some programs in the compile queue.
IProgramRequest program;
lock (_toCompile)
{
if (!_toCompile.TryDequeue(out program))
{
break;
}
}
if (program.Threaded.Base != null)
{
ProgramLinkStatus status = program.Threaded.Base.CheckProgramLink(false);
if (status != ProgramLinkStatus.Incomplete)
{
// This program is already compiled. Keep going through the queue.
program.Threaded.Compiled = true;
i--;
continue;
}
}
else
{
program.Threaded.Base = program.Create(_renderer);
}
_inProgress.Add(program.Threaded);
}
}
/// <summary>
/// Process the queue until the given program has finished compiling.
/// This will begin compilation of other programs on the queue as well.
/// </summary>
/// <param name="program">The program to wait for</param>
public void WaitForProgram(ThreadedProgram program)
{
Span<SpinWait> spinWait = stackalloc SpinWait[1];
while (!program.Compiled)
{
ProcessQueue();
if (!program.Compiled)
{
spinWait[0].SpinOnce(-1);
}
}
}
}
}

View File

@ -0,0 +1,21 @@
namespace Ryujinx.Graphics.GAL.Multithreading.Resources.Programs
{
class BinaryProgramRequest : IProgramRequest
{
public ThreadedProgram Threaded { get; set; }
private byte[] _data;
public BinaryProgramRequest(ThreadedProgram program, byte[] data)
{
Threaded = program;
_data = data;
}
public IProgram Create(IRenderer renderer)
{
return renderer.LoadProgramBinary(_data);
}
}
}

View File

@ -0,0 +1,8 @@
namespace Ryujinx.Graphics.GAL.Multithreading.Resources.Programs
{
interface IProgramRequest
{
ThreadedProgram Threaded { get; set; }
IProgram Create(IRenderer renderer);
}
}

View File

@ -0,0 +1,32 @@
using System.Linq;
namespace Ryujinx.Graphics.GAL.Multithreading.Resources.Programs
{
class SourceProgramRequest : IProgramRequest
{
public ThreadedProgram Threaded { get; set; }
private IShader[] _shaders;
private TransformFeedbackDescriptor[] _transformFeedbackDescriptors;
public SourceProgramRequest(ThreadedProgram program, IShader[] shaders, TransformFeedbackDescriptor[] transformFeedbackDescriptors)
{
Threaded = program;
_shaders = shaders;
_transformFeedbackDescriptors = transformFeedbackDescriptors;
}
public IProgram Create(IRenderer renderer)
{
IShader[] shaders = _shaders.Select(shader =>
{
var threaded = (ThreadedShader)shader;
threaded?.EnsureCreated();
return threaded?.Base;
}).ToArray();
return renderer.CreateProgram(shaders, _transformFeedbackDescriptors);
}
}
}

View File

@ -0,0 +1,80 @@
using Ryujinx.Graphics.GAL.Multithreading.Commands.CounterEvent;
using Ryujinx.Graphics.GAL.Multithreading.Model;
using System.Threading;
namespace Ryujinx.Graphics.GAL.Multithreading.Resources
{
class ThreadedCounterEvent : ICounterEvent
{
private ThreadedRenderer _renderer;
public ICounterEvent Base;
public bool Invalid { get; set; }
public CounterType Type { get; }
public bool ClearCounter { get; }
private bool _reserved;
private int _createLock;
public ThreadedCounterEvent(ThreadedRenderer renderer, CounterType type, bool clearCounter)
{
_renderer = renderer;
Type = type;
ClearCounter = clearCounter;
}
private TableRef<T> Ref<T>(T reference)
{
return new TableRef<T>(_renderer, reference);
}
public void Dispose()
{
_renderer.New<CounterEventDisposeCommand>().Set(Ref(this));
_renderer.QueueCommand();
}
public void Flush()
{
ThreadedHelpers.SpinUntilNonNull(ref Base);
Base.Flush();
}
public bool ReserveForHostAccess()
{
if (Base != null)
{
return Base.ReserveForHostAccess();
}
else
{
bool result = true;
// A very light lock, as this case is uncommon.
ThreadedHelpers.SpinUntilExchange(ref _createLock, 1, 0);
if (Base != null)
{
result = Base.ReserveForHostAccess();
}
else
{
_reserved = true;
}
Volatile.Write(ref _createLock, 0);
return result;
}
}
public void Create(IRenderer renderer, CounterType type, System.EventHandler<ulong> eventHandler, bool hostReserved)
{
ThreadedHelpers.SpinUntilExchange(ref _createLock, 1, 0);
Base = renderer.ReportCounter(type, eventHandler, hostReserved || _reserved);
Volatile.Write(ref _createLock, 0);
}
}
}

View File

@ -0,0 +1,48 @@
using Ryujinx.Graphics.GAL.Multithreading.Commands.Program;
using Ryujinx.Graphics.GAL.Multithreading.Model;
namespace Ryujinx.Graphics.GAL.Multithreading.Resources
{
class ThreadedProgram : IProgram
{
private ThreadedRenderer _renderer;
public IProgram Base;
internal bool Compiled;
public ThreadedProgram(ThreadedRenderer renderer)
{
_renderer = renderer;
}
private TableRef<T> Ref<T>(T reference)
{
return new TableRef<T>(_renderer, reference);
}
public void Dispose()
{
_renderer.New<ProgramDisposeCommand>().Set(Ref(this));
_renderer.QueueCommand();
}
public byte[] GetBinary()
{
ResultBox<byte[]> box = new ResultBox<byte[]>();
_renderer.New<ProgramGetBinaryCommand>().Set(Ref(this), Ref(box));
_renderer.InvokeCommand();
return box.Result;
}
public ProgramLinkStatus CheckProgramLink(bool blocking)
{
ResultBox<ProgramLinkStatus> box = new ResultBox<ProgramLinkStatus>();
_renderer.New<ProgramCheckLinkCommand>().Set(Ref(this), blocking, Ref(box));
_renderer.InvokeCommand();
return box.Result;
}
}
}

View File

@ -0,0 +1,22 @@
using Ryujinx.Graphics.GAL.Multithreading.Commands.Sampler;
using Ryujinx.Graphics.GAL.Multithreading.Model;
namespace Ryujinx.Graphics.GAL.Multithreading.Resources
{
class ThreadedSampler : ISampler
{
private ThreadedRenderer _renderer;
public ISampler Base;
public ThreadedSampler(ThreadedRenderer renderer)
{
_renderer = renderer;
}
public void Dispose()
{
_renderer.New<SamplerDisposeCommand>().Set(new TableRef<ThreadedSampler>(_renderer, this));
_renderer.QueueCommand();
}
}
}

View File

@ -0,0 +1,38 @@
using Ryujinx.Graphics.GAL.Multithreading.Commands.Shader;
using Ryujinx.Graphics.GAL.Multithreading.Model;
using Ryujinx.Graphics.Shader;
namespace Ryujinx.Graphics.GAL.Multithreading.Resources
{
class ThreadedShader : IShader
{
private ThreadedRenderer _renderer;
private ShaderStage _stage;
private string _code;
public IShader Base;
public ThreadedShader(ThreadedRenderer renderer, ShaderStage stage, string code)
{
_renderer = renderer;
_stage = stage;
_code = code;
}
internal void EnsureCreated()
{
if (_code != null && Base == null)
{
Base = _renderer.BaseRenderer.CompileShader(_stage, _code);
_code = null;
}
}
public void Dispose()
{
_renderer.New<ShaderDisposeCommand>().Set(new TableRef<ThreadedShader>(_renderer, this));
_renderer.QueueCommand();
}
}
}

View File

@ -0,0 +1,116 @@
using Ryujinx.Graphics.GAL.Multithreading.Commands.Texture;
using Ryujinx.Graphics.GAL.Multithreading.Model;
using System;
namespace Ryujinx.Graphics.GAL.Multithreading.Resources
{
/// <summary>
/// Threaded representation of a texture.
/// </summary>
class ThreadedTexture : ITexture
{
private ThreadedRenderer _renderer;
private TextureCreateInfo _info;
public ITexture Base;
public int Width => _info.Width;
public int Height => _info.Height;
public float ScaleFactor { get; }
public ThreadedTexture(ThreadedRenderer renderer, TextureCreateInfo info, float scale)
{
_renderer = renderer;
_info = info;
ScaleFactor = scale;
}
private TableRef<T> Ref<T>(T reference)
{
return new TableRef<T>(_renderer, reference);
}
public void CopyTo(ITexture destination, int firstLayer, int firstLevel)
{
_renderer.New<TextureCopyToCommand>().Set(Ref(this), Ref((ThreadedTexture)destination), firstLayer, firstLevel);
_renderer.QueueCommand();
}
public void CopyTo(ITexture destination, int srcLayer, int dstLayer, int srcLevel, int dstLevel)
{
_renderer.New<TextureCopyToSliceCommand>().Set(Ref(this), Ref((ThreadedTexture)destination), srcLayer, dstLayer, srcLevel, dstLevel);
_renderer.QueueCommand();
}
public void CopyTo(ITexture destination, Extents2D srcRegion, Extents2D dstRegion, bool linearFilter)
{
ThreadedTexture dest = (ThreadedTexture)destination;
if (_renderer.IsGpuThread())
{
_renderer.New<TextureCopyToScaledCommand>().Set(Ref(this), Ref(dest), srcRegion, dstRegion, linearFilter);
_renderer.QueueCommand();
}
else
{
// Scaled copy can happen on another thread for a res scale flush.
ThreadedHelpers.SpinUntilNonNull(ref Base);
ThreadedHelpers.SpinUntilNonNull(ref dest.Base);
Base.CopyTo(dest.Base, srcRegion, dstRegion, linearFilter);
}
}
public ITexture CreateView(TextureCreateInfo info, int firstLayer, int firstLevel)
{
ThreadedTexture newTex = new ThreadedTexture(_renderer, info, ScaleFactor);
_renderer.New<TextureCreateViewCommand>().Set(Ref(this), Ref(newTex), info, firstLayer, firstLevel);
_renderer.QueueCommand();
return newTex;
}
public ReadOnlySpan<byte> GetData()
{
if (_renderer.IsGpuThread())
{
ResultBox<PinnedSpan<byte>> box = new ResultBox<PinnedSpan<byte>>();
_renderer.New<TextureGetDataCommand>().Set(Ref(this), Ref(box));
_renderer.InvokeCommand();
return box.Result.Get();
}
else
{
ThreadedHelpers.SpinUntilNonNull(ref Base);
return Base.GetData();
}
}
public void SetData(ReadOnlySpan<byte> data)
{
_renderer.New<TextureSetDataCommand>().Set(Ref(this), Ref(data.ToArray()));
_renderer.QueueCommand();
}
public void SetData(ReadOnlySpan<byte> data, int layer, int level)
{
_renderer.New<TextureSetDataSliceCommand>().Set(Ref(this), Ref(data.ToArray()), layer, level);
_renderer.QueueCommand();
}
public void SetStorage(BufferRange buffer)
{
_renderer.New<TextureSetStorageCommand>().Set(Ref(this), buffer);
_renderer.QueueCommand();
}
public void Release()
{
_renderer.New<TextureReleaseCommand>().Set(Ref(this));
_renderer.QueueCommand();
}
}
}