aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.Memory/Tracking/SmartMultiRegionHandle.cs
blob: 47fe72e5bc2e1fbc8a70a4b5011be7f51232ad6d (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
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
using System;
using System.Runtime.CompilerServices;

namespace Ryujinx.Memory.Tracking
{
    /// <summary>
    /// A MultiRegionHandle that attempts to segment a region's handles into the regions requested
    /// to avoid iterating over granular chunks for canonically large regions.
    /// If minimum granularity is to be expected, use MultiRegionHandle.
    /// </summary>
    public class SmartMultiRegionHandle : IMultiRegionHandle
    {
        /// <summary>
        /// A list of region handles starting at each granularity size increment.
        /// </summary>
        private readonly RegionHandle[] _handles;
        private readonly ulong _address;
        private readonly ulong _granularity;
        private readonly ulong _size;
        private MemoryTracking _tracking;

        public bool Dirty { get; private set; } = true;

        internal SmartMultiRegionHandle(MemoryTracking tracking, ulong address, ulong size, ulong granularity)
        {
            // For this multi-region handle, the handle list starts empty.
            // As regions are queried, they are added to the _handles array at their start index.
            // When a region being added overlaps another, the existing region is split.
            // A query can therefore scan multiple regions, though with no overlaps they can cover a large area.

            _tracking = tracking;
            _handles = new RegionHandle[size / granularity];
            _granularity = granularity;

            _address = address;
            _size = size;
        }

        public void SignalWrite()
        {
            Dirty = true;
        }

        public void ForceDirty(ulong address, ulong size)
        {
            foreach (var handle in _handles)
            {
                if (handle != null && handle.OverlapsWith(address, size))
                {
                    handle.ForceDirty();
                }
            }
        }

        public void RegisterAction(RegionSignal action)
        {
            foreach (var handle in _handles)
            {
                if (handle != null)
                {
                    handle?.RegisterAction((address, size) => action(handle.Address, handle.Size));
                }
            }
        }

        public void RegisterPreciseAction(PreciseRegionSignal action)
        {
            foreach (var handle in _handles)
            {
                if (handle != null)
                {
                    handle?.RegisterPreciseAction((address, size, write) => action(handle.Address, handle.Size, write));
                }
            }
        }

        public void QueryModified(Action<ulong, ulong> modifiedAction)
        {
            if (!Dirty)
            {
                return;
            }

            Dirty = false;

            QueryModified(_address, _size, modifiedAction);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private ulong HandlesToBytes(int handles)
        {
            return (ulong)handles * _granularity;
        }

        private void SplitHandle(int handleIndex, int splitIndex)
        {
            RegionHandle handle = _handles[handleIndex];
            ulong address = _address + HandlesToBytes(handleIndex);
            ulong size = HandlesToBytes(splitIndex - handleIndex);

            // First, the target handle must be removed. Its data can still be used to determine the new handles.
            RegionSignal signal = handle.PreAction;
            handle.Dispose();

            RegionHandle splitLow = _tracking.BeginTracking(address, size);
            splitLow.Parent = this;
            if (signal != null)
            {
                splitLow.RegisterAction(signal);
            }
            _handles[handleIndex] = splitLow;

            RegionHandle splitHigh = _tracking.BeginTracking(address + size, handle.Size - size);
            splitHigh.Parent = this;
            if (signal != null)
            {
                splitHigh.RegisterAction(signal);
            }
            _handles[splitIndex] = splitHigh;
        }

        private void CreateHandle(int startHandle, int lastHandle)
        {
            ulong startAddress = _address + HandlesToBytes(startHandle);

            // Scan for the first handle before us. If it's overlapping us, it must be split.
            for (int i = startHandle - 1; i >= 0; i--)
            {
                RegionHandle handle = _handles[i];
                if (handle != null)
                {
                    if (handle.EndAddress > startAddress)
                    {
                        SplitHandle(i, startHandle);
                        return; // The remainer of this handle should be filled in later on.
                    }
                    break;
                }
            }

            // Scan for handles after us. We should create a handle that goes up to this handle's start point, if present.
            for (int i = startHandle + 1; i <= lastHandle; i++)
            {
                RegionHandle handle = _handles[i];
                if (handle != null)
                {
                    // Fill up to the found handle.
                    handle = _tracking.BeginTracking(startAddress, HandlesToBytes(i - startHandle));
                    handle.Parent = this;
                    _handles[startHandle] = handle;
                    return;
                }
            }

            // Can fill the whole range.
            _handles[startHandle] = _tracking.BeginTracking(startAddress, HandlesToBytes(1 + lastHandle - startHandle));
            _handles[startHandle].Parent = this;
        }

        public void QueryModified(ulong address, ulong size, Action<ulong, ulong> modifiedAction)
        {
            int startHandle = (int)((address - _address) / _granularity);
            int lastHandle = (int)((address + (size - 1) - _address) / _granularity);

            ulong rgStart = _address + (ulong)startHandle * _granularity;
            ulong rgSize = 0;

            ulong endAddress = _address + ((ulong)lastHandle + 1) * _granularity;

            int i = startHandle;

            while (i <= lastHandle)
            {
                RegionHandle handle = _handles[i];
                if (handle == null)
                {
                    // Missing handle. A new handle must be created.
                    CreateHandle(i, lastHandle);
                    handle = _handles[i];
                }

                if (handle.EndAddress > endAddress)
                {
                    // End address of handle is beyond the end of the search. Force a split.
                    SplitHandle(i, lastHandle + 1);
                    handle = _handles[i];
                }

                if (handle.Dirty)
                {
                    rgSize += handle.Size;
                    handle.Reprotect();
                }
                else
                {
                    // Submit the region scanned so far as dirty
                    if (rgSize != 0)
                    {
                        modifiedAction(rgStart, rgSize);
                        rgSize = 0;
                    }
                    rgStart = handle.EndAddress;
                }

                i += (int)(handle.Size / _granularity);
            }

            if (rgSize != 0)
            {
                modifiedAction(rgStart, rgSize);
            }
        }

        public void QueryModified(ulong address, ulong size, Action<ulong, ulong> modifiedAction, int sequenceNumber)
        {
            int startHandle = (int)((address - _address) / _granularity);
            int lastHandle = (int)((address + (size - 1) - _address) / _granularity);

            ulong rgStart = _address + (ulong)startHandle * _granularity;
            ulong rgSize = 0;

            ulong endAddress = _address + ((ulong)lastHandle + 1) * _granularity;

            int i = startHandle;

            while (i <= lastHandle)
            {
                RegionHandle handle = _handles[i];
                if (handle == null)
                {
                    // Missing handle. A new handle must be created.
                    CreateHandle(i, lastHandle);
                    handle = _handles[i];
                }

                if (handle.EndAddress > endAddress)
                {
                    // End address of handle is beyond the end of the search. Force a split.
                    SplitHandle(i, lastHandle + 1);
                    handle = _handles[i];
                }

                if (handle.Dirty && sequenceNumber != handle.SequenceNumber)
                {
                    rgSize += handle.Size;
                    handle.Reprotect();
                }
                else
                {
                    // Submit the region scanned so far as dirty
                    if (rgSize != 0)
                    {
                        modifiedAction(rgStart, rgSize);
                        rgSize = 0;
                    }
                    rgStart = handle.EndAddress;
                }

                handle.SequenceNumber = sequenceNumber;

                i += (int)(handle.Size / _granularity);
            }

            if (rgSize != 0)
            {
                modifiedAction(rgStart, rgSize);
            }
        }

        public void Dispose()
        {
            foreach (var handle in _handles)
            {
                handle?.Dispose();
            }
        }
    }
}