aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Cpu/AppleHv/HvMemoryBlockAllocator.cs
blob: 86936c59292149b3d17a902d43f62b27c9bb490b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using Ryujinx.Memory;
using System.Runtime.Versioning;

namespace Ryujinx.Cpu.AppleHv
{
    [SupportedOSPlatform("macos")]
    class HvMemoryBlockAllocator : PrivateMemoryAllocatorImpl<HvMemoryBlockAllocator.Block>
    {
        public class Block : PrivateMemoryAllocator.Block
        {
            private readonly HvIpaAllocator _ipaAllocator;
            public ulong Ipa { get; }

            public Block(HvIpaAllocator ipaAllocator, MemoryBlock memory, ulong size) : base(memory, size)
            {
                _ipaAllocator = ipaAllocator;

                lock (ipaAllocator)
                {
                    Ipa = ipaAllocator.Allocate(size);
                }

                HvApi.hv_vm_map((ulong)Memory.Pointer, Ipa, size, HvMemoryFlags.Read | HvMemoryFlags.Write).ThrowOnError();
            }

            public override void Destroy()
            {
                HvApi.hv_vm_unmap(Ipa, Size).ThrowOnError();

                lock (_ipaAllocator)
                {
                    _ipaAllocator.Free(Ipa, Size);
                }

                base.Destroy();
            }
        }

        private readonly HvIpaAllocator _ipaAllocator;

        public HvMemoryBlockAllocator(HvIpaAllocator ipaAllocator, ulong blockAlignment) : base(blockAlignment, MemoryAllocationFlags.None)
        {
            _ipaAllocator = ipaAllocator;
        }

        public HvMemoryBlockAllocation Allocate(ulong size, ulong alignment)
        {
            var allocation = Allocate(size, alignment, CreateBlock);

            return new HvMemoryBlockAllocation(this, allocation.Block, allocation.Offset, allocation.Size);
        }

        private Block CreateBlock(MemoryBlock memory, ulong size)
        {
            return new Block(_ipaAllocator, memory, size);
        }
    }
}