aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.Graphics/Memory/NvGpuVmmCache.cs
blob: 56979e1f062a0029eb122bbd80de340d7b4bf0b7 (plain)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
using ChocolArm64.Memory;
using System;
using System.Collections.Generic;

namespace Ryujinx.Graphics.Memory
{
    class NvGpuVmmCache
    {
        private const long RamSize = 4L * 1024 * 1024 * 1024;

        private const int MaxCpCount     = 10000;
        private const int MaxCpTimeDelta = 60000;

        private class CachedPage
        {
            private struct Range
            {
                public long Start;
                public long End;

                public Range(long Start, long End)
                {
                    this.Start = Start;
                    this.End = End;
                }
            }

            private List<Range>[] Regions;

            private HashSet<long> ResidencyKeys;

            public LinkedListNode<long> Node { get; set; }

            public int Timestamp { get; private set; }

            public CachedPage()
            {
                Regions = new List<Range>[(int)NvGpuBufferType.Count];

                for (int Index = 0; Index < Regions.Length; Index++)
                {
                    Regions[Index] = new List<Range>();
                }

                ResidencyKeys = new HashSet<long>();
            }

            public void AddResidency(long Key)
            {
                ResidencyKeys.Add(Key);
            }

            public void RemoveResidency(HashSet<long>[] Residency, long PageSize)
            {
                for (int i = 0; i < (int)NvGpuBufferType.Count; i++)
                {
                    foreach (Range Region in Regions[i])
                    {
                        foreach (long Key in ResidencyKeys)
                        {
                            Residency[Region.Start / PageSize].Remove(Key);
                        }
                    }
                }
            }

            public bool AddRange(long Start, long End, NvGpuBufferType BufferType)
            {
                List<Range> BtRegions = Regions[(int)BufferType];

                for (int Index = 0; Index < BtRegions.Count; Index++)
                {
                    Range Rg = BtRegions[Index];

                    if (Start >= Rg.Start && End <= Rg.End)
                    {
                        return false;
                    }

                    if (Start <= Rg.End && Rg.Start <= End)
                    {
                        long MinStart = Math.Min(Rg.Start, Start);
                        long MaxEnd   = Math.Max(Rg.End,   End);

                        BtRegions[Index] = new Range(MinStart, MaxEnd);

                        Timestamp = Environment.TickCount;

                        return true;
                    }
                }

                BtRegions.Add(new Range(Start, End));

                Timestamp = Environment.TickCount;

                return true;
            }

            public int GetTotalCount()
            {
                int Count = 0;

                for (int Index = 0; Index < Regions.Length; Index++)
                {
                    Count += Regions[Index].Count;
                }

                return Count;
            }
        }

        private Dictionary<long, CachedPage> Cache;

        private LinkedList<long> SortedCache;

        private HashSet<long>[] Residency;

        private long ResidencyPageSize;

        private int CpCount;

        public NvGpuVmmCache()
        {
            Cache = new Dictionary<long, CachedPage>();

            SortedCache = new LinkedList<long>();
        }

        public bool IsRegionModified(AMemory Memory, NvGpuBufferType BufferType, long PA, long Size)
        {
            (bool[] Modified, long ModifiedCount) = Memory.IsRegionModified(PA, Size);

            PA = Memory.GetPhysicalAddress(PA);

            ClearCachedPagesIfNeeded();

            long PageSize = AMemory.PageSize;

            EnsureResidencyInitialized(PageSize);

            bool HasResidents = AddResidency(PA, Size);

            if (!HasResidents && ModifiedCount == 0)
            {
                return false;
            }

            long Mask = PageSize - 1;

            long ResidencyKey = PA;

            long PAEnd = PA + Size;

            bool RegMod = false;

            int Index = 0;

            while (PA < PAEnd)
            {
                long Key = PA & ~AMemory.PageMask;

                long PAPgEnd = Math.Min((PA + AMemory.PageSize) & ~AMemory.PageMask, PAEnd);

                bool IsCached = Cache.TryGetValue(Key, out CachedPage Cp);

                if (IsCached)
                {
                    CpCount -= Cp.GetTotalCount();

                    SortedCache.Remove(Cp.Node);
                }
                else
                {
                    Cp = new CachedPage();

                    Cache.Add(Key, Cp);
                }

                if (Modified[Index++] && IsCached)
                {
                    Cp = new CachedPage();

                    Cache[Key] = Cp;
                }

                Cp.AddResidency(ResidencyKey);

                Cp.Node = SortedCache.AddLast(Key);

                RegMod |= Cp.AddRange(PA, PAPgEnd, BufferType);

                CpCount += Cp.GetTotalCount();

                PA = PAPgEnd;
            }

            return RegMod;
        }

        private bool AddResidency(long PA, long Size)
        {
            long PageSize = ResidencyPageSize;

            long Mask = PageSize - 1;

            long Key = PA;

            bool ResidentFound = false;

            for (long Cursor = PA & ~Mask; Cursor < ((PA + Size + PageSize - 1) & ~Mask); Cursor += PageSize)
            {
                long PageIndex = Cursor / PageSize;

                Residency[PageIndex].Add(Key);

                if (Residency[PageIndex].Count > 1)
                {
                    ResidentFound = true;
                }
            }

            return ResidentFound;
        }

        private void EnsureResidencyInitialized(long PageSize)
        {
            if (Residency == null)
            {
                Residency = new HashSet<long>[RamSize / PageSize];

                for (int i = 0; i < Residency.Length; i++)
                {
                    Residency[i] = new HashSet<long>();
                }

                ResidencyPageSize = PageSize;
            }
            else
            {
                if (ResidencyPageSize != PageSize)
                {
                    throw new InvalidOperationException("Tried to change residency page size");
                }
            }
        }

        private void ClearCachedPagesIfNeeded()
        {
            if (CpCount <= MaxCpCount)
            {
                return;
            }

            int Timestamp = Environment.TickCount;

            int TimeDelta;

            do
            {
                if (!TryPopOldestCachedPageKey(Timestamp, out long Key))
                {
                    break;
                }

                CachedPage Cp = Cache[Key];

                Cp.RemoveResidency(Residency, ResidencyPageSize);

                Cache.Remove(Key);

                CpCount -= Cp.GetTotalCount();

                TimeDelta = RingDelta(Cp.Timestamp, Timestamp);
            }
            while (CpCount > (MaxCpCount >> 1) || (uint)TimeDelta > (uint)MaxCpTimeDelta);
        }

        private bool TryPopOldestCachedPageKey(int Timestamp, out long Key)
        {
            LinkedListNode<long> Node = SortedCache.First;

            if (Node == null)
            {
                Key = 0;

                return false;
            }

            SortedCache.Remove(Node);

            Key = Node.Value;

            return true;
        }

        private int RingDelta(int Old, int New)
        {
            if ((uint)New < (uint)Old)
            {
                return New + (~Old + 1);
            }
            else
            {
                return New - Old;
            }
        }
    }
}