aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Cpu/Jit/HostTracked/AddressSpacePartition.cs
blob: 224c5edc30da93cd646fb4c4c47be9c6410f259b (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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
using Ryujinx.Common;
using Ryujinx.Common.Collections;
using Ryujinx.Memory;
using System;
using System.Diagnostics;
using System.Threading;

namespace Ryujinx.Cpu.Jit.HostTracked
{
    readonly struct PrivateRange
    {
        public readonly MemoryBlock Memory;
        public readonly ulong Offset;
        public readonly ulong Size;

        public static PrivateRange Empty => new(null, 0, 0);

        public PrivateRange(MemoryBlock memory, ulong offset, ulong size)
        {
            Memory = memory;
            Offset = offset;
            Size = size;
        }
    }

    class AddressSpacePartition : IDisposable
    {
        public const ulong GuestPageSize = 0x1000;

        private const int DefaultBlockAlignment = 1 << 20;

        private enum MappingType : byte
        {
            None,
            Private,
        }

        private class Mapping : IntrusiveRedBlackTreeNode<Mapping>, IComparable<Mapping>, IComparable<ulong>
        {
            public ulong Address { get; private set; }
            public ulong Size { get; private set; }
            public ulong EndAddress => Address + Size;
            public MappingType Type { get; private set; }

            public Mapping(ulong address, ulong size, MappingType type)
            {
                Address = address;
                Size = size;
                Type = type;
            }

            public Mapping Split(ulong splitAddress)
            {
                ulong leftSize = splitAddress - Address;
                ulong rightSize = EndAddress - splitAddress;

                Mapping left = new(Address, leftSize, Type);

                Address = splitAddress;
                Size = rightSize;

                return left;
            }

            public void UpdateState(MappingType newType)
            {
                Type = newType;
            }

            public void Extend(ulong sizeDelta)
            {
                Size += sizeDelta;
            }

            public int CompareTo(Mapping other)
            {
                if (Address < other.Address)
                {
                    return -1;
                }
                else if (Address <= other.EndAddress - 1UL)
                {
                    return 0;
                }
                else
                {
                    return 1;
                }
            }

            public int CompareTo(ulong address)
            {
                if (address < Address)
                {
                    return -1;
                }
                else if (address <= EndAddress - 1UL)
                {
                    return 0;
                }
                else
                {
                    return 1;
                }
            }
        }

        private class PrivateMapping : IntrusiveRedBlackTreeNode<PrivateMapping>, IComparable<PrivateMapping>, IComparable<ulong>
        {
            public ulong Address { get; private set; }
            public ulong Size { get; private set; }
            public ulong EndAddress => Address + Size;
            public PrivateMemoryAllocation PrivateAllocation { get; private set; }

            public PrivateMapping(ulong address, ulong size, PrivateMemoryAllocation privateAllocation)
            {
                Address = address;
                Size = size;
                PrivateAllocation = privateAllocation;
            }

            public PrivateMapping Split(ulong splitAddress)
            {
                ulong leftSize = splitAddress - Address;
                ulong rightSize = EndAddress - splitAddress;

                Debug.Assert(leftSize > 0);
                Debug.Assert(rightSize > 0);

                (var leftAllocation, PrivateAllocation) = PrivateAllocation.Split(leftSize);

                PrivateMapping left = new(Address, leftSize, leftAllocation);

                Address = splitAddress;
                Size = rightSize;

                return left;
            }

            public void Map(AddressSpacePartitionMultiAllocation baseBlock, ulong baseAddress, PrivateMemoryAllocation newAllocation)
            {
                baseBlock.MapView(newAllocation.Memory, newAllocation.Offset, Address - baseAddress, Size);
                PrivateAllocation = newAllocation;
            }

            public void Unmap(AddressSpacePartitionMultiAllocation baseBlock, ulong baseAddress)
            {
                if (PrivateAllocation.IsValid)
                {
                    baseBlock.UnmapView(PrivateAllocation.Memory, Address - baseAddress, Size);
                    PrivateAllocation.Dispose();
                }

                PrivateAllocation = default;
            }

            public void Extend(ulong sizeDelta)
            {
                Size += sizeDelta;
            }

            public int CompareTo(PrivateMapping other)
            {
                if (Address < other.Address)
                {
                    return -1;
                }
                else if (Address <= other.EndAddress - 1UL)
                {
                    return 0;
                }
                else
                {
                    return 1;
                }
            }

            public int CompareTo(ulong address)
            {
                if (address < Address)
                {
                    return -1;
                }
                else if (address <= EndAddress - 1UL)
                {
                    return 0;
                }
                else
                {
                    return 1;
                }
            }
        }

        private readonly MemoryBlock _backingMemory;
        private readonly AddressSpacePartitionMultiAllocation _baseMemory;
        private readonly PrivateMemoryAllocator _privateMemoryAllocator;

        private readonly AddressIntrusiveRedBlackTree<Mapping> _mappingTree;
        private readonly AddressIntrusiveRedBlackTree<PrivateMapping> _privateTree;

        private readonly ReaderWriterLockSlim _treeLock;

        private readonly ulong _hostPageSize;

        private ulong? _firstPagePa;
        private ulong? _lastPagePa;
        private ulong _cachedFirstPagePa;
        private ulong _cachedLastPagePa;
        private MemoryBlock _firstPageMemoryForUnmap;
        private ulong _firstPageOffsetForLateMap;
        private MemoryPermission _firstPageMemoryProtection;

        public ulong Address { get; }
        public ulong Size { get; }
        public ulong EndAddress => Address + Size;

        public AddressSpacePartition(AddressSpacePartitionAllocation baseMemory, MemoryBlock backingMemory, ulong address, ulong size)
        {
            _privateMemoryAllocator = new PrivateMemoryAllocator(DefaultBlockAlignment, MemoryAllocationFlags.Mirrorable);
            _mappingTree = new AddressIntrusiveRedBlackTree<Mapping>();
            _privateTree = new AddressIntrusiveRedBlackTree<PrivateMapping>();
            _treeLock = new ReaderWriterLockSlim();

            _mappingTree.Add(new Mapping(address, size, MappingType.None));
            _privateTree.Add(new PrivateMapping(address, size, default));

            _hostPageSize = MemoryBlock.GetPageSize();

            _backingMemory = backingMemory;
            _baseMemory = new(baseMemory);

            _cachedFirstPagePa = ulong.MaxValue;
            _cachedLastPagePa = ulong.MaxValue;

            Address = address;
            Size = size;
        }

        public bool IsEmpty()
        {
            _treeLock.EnterReadLock();

            try
            {
                Mapping map = _mappingTree.GetNode(Address);

                return map != null && map.Address == Address && map.Size == Size && map.Type == MappingType.None;
            }
            finally
            {
                _treeLock.ExitReadLock();
            }
        }

        public void Map(ulong va, ulong pa, ulong size)
        {
            Debug.Assert(va >= Address);
            Debug.Assert(va + size <= EndAddress);

            if (va == Address)
            {
                _firstPagePa = pa;
            }

            if (va <= EndAddress - GuestPageSize && va + size > EndAddress - GuestPageSize)
            {
                _lastPagePa = pa + ((EndAddress - GuestPageSize) - va);
            }

            Update(va, pa, size, MappingType.Private);
        }

        public void Unmap(ulong va, ulong size)
        {
            Debug.Assert(va >= Address);
            Debug.Assert(va + size <= EndAddress);

            if (va == Address)
            {
                _firstPagePa = null;
            }

            if (va <= EndAddress - GuestPageSize && va + size > EndAddress - GuestPageSize)
            {
                _lastPagePa = null;
            }

            Update(va, 0UL, size, MappingType.None);
        }

        public void ReprotectAligned(ulong va, ulong size, MemoryPermission protection)
        {
            Debug.Assert(va >= Address);
            Debug.Assert(va + size <= EndAddress);

            _baseMemory.Reprotect(va - Address, size, protection, false);

            if (va == Address)
            {
                _firstPageMemoryProtection = protection;
            }
        }

        public void Reprotect(
            ulong va,
            ulong size,
            MemoryPermission protection,
            AddressSpacePartitioned addressSpace,
            Action<ulong, IntPtr, ulong> updatePtCallback)
        {
            if (_baseMemory.LazyInitMirrorForProtection(addressSpace, Address, Size, protection))
            {
                LateMap();
            }

            updatePtCallback(va, _baseMemory.GetPointerForProtection(va - Address, size, protection), size);
        }

        public IntPtr GetPointer(ulong va, ulong size)
        {
            Debug.Assert(va >= Address);
            Debug.Assert(va + size <= EndAddress);

            return _baseMemory.GetPointer(va - Address, size);
        }

        public void InsertBridgeAtEnd(AddressSpacePartition partitionAfter, bool useProtectionMirrors)
        {
            ulong firstPagePa = partitionAfter?._firstPagePa ?? ulong.MaxValue;
            ulong lastPagePa = _lastPagePa ?? ulong.MaxValue;

            if (firstPagePa != _cachedFirstPagePa || lastPagePa != _cachedLastPagePa)
            {
                if (partitionAfter != null && partitionAfter._firstPagePa.HasValue)
                {
                    (MemoryBlock firstPageMemory, ulong firstPageOffset) = partitionAfter.GetFirstPageMemoryAndOffset();

                    _baseMemory.MapView(firstPageMemory, firstPageOffset, Size, _hostPageSize);

                    if (!useProtectionMirrors)
                    {
                        _baseMemory.Reprotect(Size, _hostPageSize, partitionAfter._firstPageMemoryProtection, throwOnFail: false);
                    }

                    _firstPageMemoryForUnmap = firstPageMemory;
                    _firstPageOffsetForLateMap = firstPageOffset;
                }
                else
                {
                    MemoryBlock firstPageMemoryForUnmap = _firstPageMemoryForUnmap;

                    if (firstPageMemoryForUnmap != null)
                    {
                        _baseMemory.UnmapView(firstPageMemoryForUnmap, Size, _hostPageSize);
                        _firstPageMemoryForUnmap = null;
                    }
                }

                _cachedFirstPagePa = firstPagePa;
                _cachedLastPagePa = lastPagePa;
            }
        }

        public void ReprotectBridge(MemoryPermission protection)
        {
            if (_firstPageMemoryForUnmap != null)
            {
                _baseMemory.Reprotect(Size, _hostPageSize, protection, throwOnFail: false);
            }
        }

        private (MemoryBlock, ulong) GetFirstPageMemoryAndOffset()
        {
            _treeLock.EnterReadLock();

            try
            {
                PrivateMapping map = _privateTree.GetNode(Address);

                if (map != null && map.PrivateAllocation.IsValid)
                {
                    return (map.PrivateAllocation.Memory, map.PrivateAllocation.Offset + (Address - map.Address));
                }
            }
            finally
            {
                _treeLock.ExitReadLock();
            }

            return (_backingMemory, _firstPagePa.Value);
        }

        public PrivateRange GetPrivateAllocation(ulong va)
        {
            _treeLock.EnterReadLock();

            try
            {
                PrivateMapping map = _privateTree.GetNode(va);

                if (map != null && map.PrivateAllocation.IsValid)
                {
                    return new(map.PrivateAllocation.Memory, map.PrivateAllocation.Offset + (va - map.Address), map.Size - (va - map.Address));
                }
            }
            finally
            {
                _treeLock.ExitReadLock();
            }

            return PrivateRange.Empty;
        }

        private void Update(ulong va, ulong pa, ulong size, MappingType type)
        {
            _treeLock.EnterWriteLock();

            try
            {
                Mapping map = _mappingTree.GetNode(va);

                Update(map, va, pa, size, type);
            }
            finally
            {
                _treeLock.ExitWriteLock();
            }
        }

        private Mapping Update(Mapping map, ulong va, ulong pa, ulong size, MappingType type)
        {
            ulong endAddress = va + size;

            for (; map != null; map = map.Successor)
            {
                if (map.Address < va)
                {
                    _mappingTree.Add(map.Split(va));
                }

                if (map.EndAddress > endAddress)
                {
                    Mapping newMap = map.Split(endAddress);
                    _mappingTree.Add(newMap);
                    map = newMap;
                }

                switch (type)
                {
                    case MappingType.None:
                        ulong alignment = _hostPageSize;

                        bool unmappedBefore = map.Predecessor == null ||
                            (map.Predecessor.Type == MappingType.None && map.Predecessor.Address <= BitUtils.AlignDown(va, alignment));

                        bool unmappedAfter = map.Successor == null ||
                            (map.Successor.Type == MappingType.None && map.Successor.EndAddress >= BitUtils.AlignUp(endAddress, alignment));

                        UnmapPrivate(va, size, unmappedBefore, unmappedAfter);
                        break;
                    case MappingType.Private:
                        MapPrivate(va, size);
                        break;
                }

                map.UpdateState(type);
                map = TryCoalesce(map);

                if (map.EndAddress >= endAddress)
                {
                    break;
                }
            }

            return map;
        }

        private Mapping TryCoalesce(Mapping map)
        {
            Mapping previousMap = map.Predecessor;
            Mapping nextMap = map.Successor;

            if (previousMap != null && CanCoalesce(previousMap, map))
            {
                previousMap.Extend(map.Size);
                _mappingTree.Remove(map);
                map = previousMap;
            }

            if (nextMap != null && CanCoalesce(map, nextMap))
            {
                map.Extend(nextMap.Size);
                _mappingTree.Remove(nextMap);
            }

            return map;
        }

        private static bool CanCoalesce(Mapping left, Mapping right)
        {
            return left.Type == right.Type;
        }

        private void MapPrivate(ulong va, ulong size)
        {
            ulong endAddress = va + size;

            ulong alignment = _hostPageSize;

            // Expand the range outwards based on page size to ensure that at least the requested region is mapped.
            ulong vaAligned = BitUtils.AlignDown(va, alignment);
            ulong endAddressAligned = BitUtils.AlignUp(endAddress, alignment);

            PrivateMapping map = _privateTree.GetNode(va);

            for (; map != null; map = map.Successor)
            {
                if (!map.PrivateAllocation.IsValid)
                {
                    if (map.Address < vaAligned)
                    {
                        _privateTree.Add(map.Split(vaAligned));
                    }

                    if (map.EndAddress > endAddressAligned)
                    {
                        PrivateMapping newMap = map.Split(endAddressAligned);
                        _privateTree.Add(newMap);
                        map = newMap;
                    }

                    map.Map(_baseMemory, Address, _privateMemoryAllocator.Allocate(map.Size, _hostPageSize));
                }

                if (map.EndAddress >= endAddressAligned)
                {
                    break;
                }
            }
        }

        private void UnmapPrivate(ulong va, ulong size, bool unmappedBefore, bool unmappedAfter)
        {
            ulong endAddress = va + size;

            ulong alignment = _hostPageSize;

            // If the adjacent mappings are unmapped, expand the range outwards,
            // otherwise shrink it inwards. We must ensure we won't unmap pages that might still be in use.
            ulong vaAligned = unmappedBefore ? BitUtils.AlignDown(va, alignment) : BitUtils.AlignUp(va, alignment);
            ulong endAddressAligned = unmappedAfter ? BitUtils.AlignUp(endAddress, alignment) : BitUtils.AlignDown(endAddress, alignment);

            if (endAddressAligned <= vaAligned)
            {
                return;
            }

            PrivateMapping map = _privateTree.GetNode(vaAligned);

            for (; map != null; map = map.Successor)
            {
                if (map.PrivateAllocation.IsValid)
                {
                    if (map.Address < vaAligned)
                    {
                        _privateTree.Add(map.Split(vaAligned));
                    }

                    if (map.EndAddress > endAddressAligned)
                    {
                        PrivateMapping newMap = map.Split(endAddressAligned);
                        _privateTree.Add(newMap);
                        map = newMap;
                    }

                    map.Unmap(_baseMemory, Address);
                    map = TryCoalesce(map);
                }

                if (map.EndAddress >= endAddressAligned)
                {
                    break;
                }
            }
        }

        private PrivateMapping TryCoalesce(PrivateMapping map)
        {
            PrivateMapping previousMap = map.Predecessor;
            PrivateMapping nextMap = map.Successor;

            if (previousMap != null && CanCoalesce(previousMap, map))
            {
                previousMap.Extend(map.Size);
                _privateTree.Remove(map);
                map = previousMap;
            }

            if (nextMap != null && CanCoalesce(map, nextMap))
            {
                map.Extend(nextMap.Size);
                _privateTree.Remove(nextMap);
            }

            return map;
        }

        private static bool CanCoalesce(PrivateMapping left, PrivateMapping right)
        {
            return !left.PrivateAllocation.IsValid && !right.PrivateAllocation.IsValid;
        }

        private void LateMap()
        {
            // Map all existing private allocations.
            // This is necessary to ensure mirrors that are lazily created have the same mappings as the main one.

            PrivateMapping map = _privateTree.GetNode(Address);

            for (; map != null; map = map.Successor)
            {
                if (map.PrivateAllocation.IsValid)
                {
                    _baseMemory.LateMapView(map.PrivateAllocation.Memory, map.PrivateAllocation.Offset, map.Address - Address, map.Size);
                }
            }

            MemoryBlock firstPageMemory = _firstPageMemoryForUnmap;
            ulong firstPageOffset = _firstPageOffsetForLateMap;

            if (firstPageMemory != null)
            {
                _baseMemory.LateMapView(firstPageMemory, firstPageOffset, Size, _hostPageSize);
            }
        }

        public PrivateRange GetFirstPrivateAllocation(ulong va, ulong size, out ulong nextVa)
        {
            _treeLock.EnterReadLock();

            try
            {
                PrivateMapping map = _privateTree.GetNode(va);

                nextVa = map.EndAddress;

                if (map != null && map.PrivateAllocation.IsValid)
                {
                    ulong startOffset = va - map.Address;

                    return new(
                        map.PrivateAllocation.Memory,
                        map.PrivateAllocation.Offset + startOffset,
                        Math.Min(map.PrivateAllocation.Size - startOffset, size));
                }
            }
            finally
            {
                _treeLock.ExitReadLock();
            }

            return PrivateRange.Empty;
        }

        public bool HasPrivateAllocation(ulong va, ulong size, ulong startVa, ulong startSize, ref PrivateRange range)
        {
            ulong endVa = va + size;

            _treeLock.EnterReadLock();

            try
            {
                for (PrivateMapping map = _privateTree.GetNode(va); map != null && map.Address < endVa; map = map.Successor)
                {
                    if (map.PrivateAllocation.IsValid)
                    {
                        if (map.Address <= startVa && map.EndAddress >= startVa + startSize)
                        {
                            ulong startOffset = startVa - map.Address;

                            range = new(
                                map.PrivateAllocation.Memory,
                                map.PrivateAllocation.Offset + startOffset,
                                Math.Min(map.PrivateAllocation.Size - startOffset, startSize));
                        }

                        return true;
                    }
                }
            }
            finally
            {
                _treeLock.ExitReadLock();
            }

            return false;
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);

            _privateMemoryAllocator.Dispose();
            _baseMemory.Dispose();
        }
    }
}