aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.HLE/HOS/Kernel/Memory/KMemoryRegionBlock.cs
blob: 9a77349522d7634e82b5d4dbc0835ff42f3d7c1a (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
namespace Ryujinx.HLE.HOS.Kernel.Memory
{
    class KMemoryRegionBlock
    {
        public long[][] Masks;

        public ulong FreeCount;
        public int   MaxLevel;
        public ulong StartAligned;
        public ulong SizeInBlocksTruncated;
        public ulong SizeInBlocksRounded;
        public int   Order;
        public int   NextOrder;

        public bool TryCoalesce(int index, int count)
        {
            long mask = ((1L << count) - 1) << (index & 63);

            index /= 64;

            if (count >= 64)
            {
                int remaining = count;
                int tempIdx = index;

                do
                {
                    if (Masks[MaxLevel - 1][tempIdx++] != -1L)
                    {
                        return false;
                    }

                    remaining -= 64;
                }
                while (remaining != 0);

                remaining = count;
                tempIdx = index;

                do
                {
                    Masks[MaxLevel - 1][tempIdx] = 0;

                    ClearMaskBit(MaxLevel - 2, tempIdx++);

                    remaining -= 64;
                }
                while (remaining != 0);
            }
            else
            {
                long value = Masks[MaxLevel - 1][index];

                if ((mask & ~value) != 0)
                {
                    return false;
                }

                value &= ~mask;

                Masks[MaxLevel - 1][index] = value;

                if (value == 0)
                {
                    ClearMaskBit(MaxLevel - 2, index);
                }
            }

            FreeCount -= (ulong)count;

            return true;
        }

        public void ClearMaskBit(int startLevel, int index)
        {
            for (int level = startLevel; level >= 0; level--, index /= 64)
            {
                Masks[level][index / 64] &= ~(1L << (index & 63));

                if (Masks[level][index / 64] != 0)
                {
                    break;
                }
            }
        }
    }
}