aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.HLE/HOS/Kernel/Memory/KPageTableBase.cs
blob: 2b00f802aed6ffb99b7f3d8ed2e7a31c38585b69 (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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
using Ryujinx.Common;
using Ryujinx.HLE.HOS.Kernel.Common;
using Ryujinx.HLE.HOS.Kernel.Process;
using Ryujinx.Horizon.Common;
using Ryujinx.Memory;
using Ryujinx.Memory.Range;
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Ryujinx.HLE.HOS.Kernel.Memory
{
    abstract class KPageTableBase
    {
        private static readonly int[] _mappingUnitSizes = {
            0x1000,
            0x10000,
            0x200000,
            0x400000,
            0x2000000,
            0x40000000,
        };

        private const ulong RegionAlignment = 0x200000;

        public const int PageSize = 0x1000;

        private const int KMemoryBlockSize = 0x40;

        // We need 2 blocks for the case where a big block
        // needs to be split in 2, plus one block that will be the new one inserted.
        private const int MaxBlocksNeededForInsertion = 2;

        protected readonly KernelContext Context;
        protected virtual bool Supports4KBPages => true;

        public ulong AddrSpaceStart { get; private set; }
        public ulong AddrSpaceEnd { get; private set; }

        public ulong CodeRegionStart { get; private set; }
        public ulong CodeRegionEnd { get; private set; }

        public ulong HeapRegionStart { get; private set; }
        public ulong HeapRegionEnd { get; private set; }

        private ulong _currentHeapAddr;

        public ulong AliasRegionStart { get; private set; }
        public ulong AliasRegionEnd { get; private set; }

        public ulong StackRegionStart { get; private set; }
        public ulong StackRegionEnd { get; private set; }

        public ulong TlsIoRegionStart { get; private set; }
        public ulong TlsIoRegionEnd { get; private set; }

        public ulong AslrRegionStart { get; private set; }
        public ulong AslrRegionEnd { get; private set; }

#pragma warning disable IDE0052 // Remove unread private member
        private ulong _heapCapacity;
#pragma warning restore IDE0052

        public ulong PhysicalMemoryUsage { get; private set; }

        private readonly KMemoryBlockManager _blockManager;

        private MemoryRegion _memRegion;

        private bool _allocateFromBack;
        private readonly bool _isKernel;

        private bool _aslrEnabled;

        private KMemoryBlockSlabManager _slabManager;

        private int _contextId;

        private MersenneTwister _randomNumberGenerator;

        private readonly MemoryFillValue _heapFillValue;
        private readonly MemoryFillValue _ipcFillValue;

        private readonly ulong _reservedAddressSpaceSize;

        public KPageTableBase(KernelContext context, ulong reservedAddressSpaceSize)
        {
            Context = context;

            _blockManager = new KMemoryBlockManager();

            _isKernel = false;

            _heapFillValue = MemoryFillValue.Zero;
            _ipcFillValue = MemoryFillValue.Zero;

            _reservedAddressSpaceSize = reservedAddressSpaceSize;
        }

        private static readonly int[] _addrSpaceSizes = { 32, 36, 32, 39 };

        public Result InitializeForProcess(
            AddressSpaceType addrSpaceType,
            bool aslrEnabled,
            bool fromBack,
            MemoryRegion memRegion,
            ulong address,
            ulong size,
            KMemoryBlockSlabManager slabManager)
        {
            if ((uint)addrSpaceType > (uint)AddressSpaceType.Addr39Bits)
            {
                throw new ArgumentException($"AddressSpaceType bigger than {(uint)AddressSpaceType.Addr39Bits}: {(uint)addrSpaceType}", nameof(addrSpaceType));
            }

            _contextId = Context.ContextIdManager.GetId();

            ulong addrSpaceBase = 0;
            ulong addrSpaceSize = 1UL << _addrSpaceSizes[(int)addrSpaceType];

            Result result = CreateUserAddressSpace(
                addrSpaceType,
                aslrEnabled,
                fromBack,
                addrSpaceBase,
                addrSpaceSize,
                memRegion,
                address,
                size,
                slabManager);

            if (result != Result.Success)
            {
                Context.ContextIdManager.PutId(_contextId);
            }

            return result;
        }

        private struct Region
        {
            public ulong Start;
            public ulong End;
            public ulong Size;
            public ulong AslrOffset;
        }

        private Result CreateUserAddressSpace(
            AddressSpaceType addrSpaceType,
            bool aslrEnabled,
            bool fromBack,
            ulong addrSpaceStart,
            ulong addrSpaceEnd,
            MemoryRegion memRegion,
            ulong address,
            ulong size,
            KMemoryBlockSlabManager slabManager)
        {
            ulong endAddr = address + size;

            Region aliasRegion = new();
            Region heapRegion = new();
            Region stackRegion = new();
            Region tlsIoRegion = new();

            ulong codeRegionSize;
            ulong stackAndTlsIoStart;
            ulong stackAndTlsIoEnd;

            switch (addrSpaceType)
            {
                case AddressSpaceType.Addr32Bits:
                    aliasRegion.Size = 0x40000000;
                    heapRegion.Size = 0x40000000;
                    stackRegion.Size = 0;
                    tlsIoRegion.Size = 0;
                    CodeRegionStart = 0x200000;
                    codeRegionSize = 0x3fe00000;
                    AslrRegionStart = 0x200000;
                    AslrRegionEnd = AslrRegionStart + 0xffe00000;
                    stackAndTlsIoStart = 0x200000;
                    stackAndTlsIoEnd = 0x40000000;
                    break;

                case AddressSpaceType.Addr36Bits:
                    aliasRegion.Size = 0x180000000;
                    heapRegion.Size = 0x180000000;
                    stackRegion.Size = 0;
                    tlsIoRegion.Size = 0;
                    CodeRegionStart = 0x8000000;
                    codeRegionSize = 0x78000000;
                    AslrRegionStart = 0x8000000;
                    AslrRegionEnd = AslrRegionStart + 0xff8000000;
                    stackAndTlsIoStart = 0x8000000;
                    stackAndTlsIoEnd = 0x80000000;
                    break;

                case AddressSpaceType.Addr32BitsNoMap:
                    aliasRegion.Size = 0;
                    heapRegion.Size = 0x80000000;
                    stackRegion.Size = 0;
                    tlsIoRegion.Size = 0;
                    CodeRegionStart = 0x200000;
                    codeRegionSize = 0x3fe00000;
                    AslrRegionStart = 0x200000;
                    AslrRegionEnd = AslrRegionStart + 0xffe00000;
                    stackAndTlsIoStart = 0x200000;
                    stackAndTlsIoEnd = 0x40000000;
                    break;

                case AddressSpaceType.Addr39Bits:
                    if (_reservedAddressSpaceSize < addrSpaceEnd)
                    {
                        int addressSpaceWidth = (int)ulong.Log2(_reservedAddressSpaceSize);

                        aliasRegion.Size = 1UL << (addressSpaceWidth - 3);
                        heapRegion.Size = 0x180000000;
                        stackRegion.Size = 1UL << (addressSpaceWidth - 8);
                        tlsIoRegion.Size = 1UL << (addressSpaceWidth - 3);
                        CodeRegionStart = BitUtils.AlignDown<ulong>(address, RegionAlignment);
                        codeRegionSize = BitUtils.AlignUp<ulong>(endAddr, RegionAlignment) - CodeRegionStart;
                        stackAndTlsIoStart = 0;
                        stackAndTlsIoEnd = 0;
                        AslrRegionStart = 0x8000000;
                        addrSpaceEnd = 1UL << addressSpaceWidth;
                        AslrRegionEnd = addrSpaceEnd;
                    }
                    else
                    {
                        aliasRegion.Size = 0x1000000000;
                        heapRegion.Size = 0x180000000;
                        stackRegion.Size = 0x80000000;
                        tlsIoRegion.Size = 0x1000000000;
                        CodeRegionStart = BitUtils.AlignDown(address, RegionAlignment);
                        codeRegionSize = BitUtils.AlignUp(endAddr, RegionAlignment) - CodeRegionStart;
                        AslrRegionStart = 0x8000000;
                        AslrRegionEnd = AslrRegionStart + 0x7ff8000000;
                        stackAndTlsIoStart = 0;
                        stackAndTlsIoEnd = 0;
                    }
                    break;
                default:
                    throw new ArgumentException($"AddressSpaceType bigger than {(uint)AddressSpaceType.Addr39Bits}: {(uint)addrSpaceType}", nameof(addrSpaceType));
            }

            CodeRegionEnd = CodeRegionStart + codeRegionSize;

            ulong mapBaseAddress;
            ulong mapAvailableSize;

            if (CodeRegionStart - AslrRegionStart >= addrSpaceEnd - CodeRegionEnd)
            {
                // Has more space before the start of the code region.
                mapBaseAddress = AslrRegionStart;
                mapAvailableSize = CodeRegionStart - AslrRegionStart;
            }
            else
            {
                // Has more space after the end of the code region.
                mapBaseAddress = CodeRegionEnd;
                mapAvailableSize = addrSpaceEnd - CodeRegionEnd;
            }

            ulong mapTotalSize = aliasRegion.Size + heapRegion.Size + stackRegion.Size + tlsIoRegion.Size;

            ulong aslrMaxOffset = mapAvailableSize - mapTotalSize;

            _aslrEnabled = aslrEnabled;

            AddrSpaceStart = addrSpaceStart;
            AddrSpaceEnd = addrSpaceEnd;

            _slabManager = slabManager;

            if (mapAvailableSize < mapTotalSize)
            {
                return KernelResult.OutOfMemory;
            }

            if (aslrEnabled)
            {
                aliasRegion.AslrOffset = GetRandomValue(0, aslrMaxOffset / RegionAlignment) * RegionAlignment;
                heapRegion.AslrOffset = GetRandomValue(0, aslrMaxOffset / RegionAlignment) * RegionAlignment;
                stackRegion.AslrOffset = GetRandomValue(0, aslrMaxOffset / RegionAlignment) * RegionAlignment;
                tlsIoRegion.AslrOffset = GetRandomValue(0, aslrMaxOffset / RegionAlignment) * RegionAlignment;
            }

            // Regions are sorted based on ASLR offset.
            // When ASLR is disabled, the order is Alias, Heap, Stack and TlsIo.
            aliasRegion.Start = mapBaseAddress + aliasRegion.AslrOffset;
            aliasRegion.End = aliasRegion.Start + aliasRegion.Size;
            heapRegion.Start = mapBaseAddress + heapRegion.AslrOffset;
            heapRegion.End = heapRegion.Start + heapRegion.Size;
            stackRegion.Start = mapBaseAddress + stackRegion.AslrOffset;
            stackRegion.End = stackRegion.Start + stackRegion.Size;
            tlsIoRegion.Start = mapBaseAddress + tlsIoRegion.AslrOffset;
            tlsIoRegion.End = tlsIoRegion.Start + tlsIoRegion.Size;

            SortRegion(ref aliasRegion, ref heapRegion, true);

            if (stackRegion.Size != 0)
            {
                stackRegion.Start = mapBaseAddress + stackRegion.AslrOffset;
                stackRegion.End = stackRegion.Start + stackRegion.Size;

                SortRegion(ref aliasRegion, ref stackRegion);
                SortRegion(ref heapRegion, ref stackRegion);
            }
            else
            {
                stackRegion.Start = stackAndTlsIoStart;
                stackRegion.End = stackAndTlsIoEnd;
            }

            if (tlsIoRegion.Size != 0)
            {
                tlsIoRegion.Start = mapBaseAddress + tlsIoRegion.AslrOffset;
                tlsIoRegion.End = tlsIoRegion.Start + tlsIoRegion.Size;

                SortRegion(ref aliasRegion, ref tlsIoRegion);
                SortRegion(ref heapRegion, ref tlsIoRegion);

                if (stackRegion.Size != 0)
                {
                    SortRegion(ref stackRegion, ref tlsIoRegion);
                }
            }
            else
            {
                tlsIoRegion.Start = stackAndTlsIoStart;
                tlsIoRegion.End = stackAndTlsIoEnd;
            }

            AliasRegionStart = aliasRegion.Start;
            AliasRegionEnd = aliasRegion.End;
            HeapRegionStart = heapRegion.Start;
            HeapRegionEnd = heapRegion.End;
            StackRegionStart = stackRegion.Start;
            StackRegionEnd = stackRegion.End;
            TlsIoRegionStart = tlsIoRegion.Start;
            TlsIoRegionEnd = tlsIoRegion.End;

            // TODO: Check kernel configuration via secure monitor call when implemented to set memory fill values.

            _currentHeapAddr = HeapRegionStart;
            _heapCapacity = 0;
            PhysicalMemoryUsage = 0;

            _memRegion = memRegion;
            _allocateFromBack = fromBack;

            return _blockManager.Initialize(addrSpaceStart, addrSpaceEnd, slabManager);
        }

        private static void SortRegion(ref Region lhs, ref Region rhs, bool checkForEquality = false)
        {
            bool res = checkForEquality ? lhs.AslrOffset <= rhs.AslrOffset : lhs.AslrOffset < rhs.AslrOffset;

            if (res)
            {
                rhs.Start += lhs.Size;
                rhs.End += lhs.Size;
            }
            else
            {
                lhs.Start += rhs.Size;
                lhs.End += rhs.Size;
            }
        }

        private ulong GetRandomValue(ulong min, ulong max)
        {
            return (ulong)GetRandomValue((long)min, (long)max);
        }

        private long GetRandomValue(long min, long max)
        {
            _randomNumberGenerator ??= new MersenneTwister(0);

            return _randomNumberGenerator.GenRandomNumber(min, max);
        }

        public Result MapPages(ulong address, KPageList pageList, MemoryState state, KMemoryPermission permission)
        {
            ulong pagesCount = pageList.GetPagesCount();

            ulong size = pagesCount * PageSize;

            if (!CanContain(address, size, state))
            {
                return KernelResult.InvalidMemState;
            }

            lock (_blockManager)
            {
                if (!IsUnmapped(address, pagesCount * PageSize))
                {
                    return KernelResult.InvalidMemState;
                }

                if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                {
                    return KernelResult.OutOfResource;
                }

                Result result = MapPages(address, pageList, permission, MemoryMapFlags.None);

                if (result == Result.Success)
                {
                    _blockManager.InsertBlock(address, pagesCount, state, permission);
                }

                return result;
            }
        }

        public Result UnmapPages(ulong address, KPageList pageList, MemoryState stateExpected)
        {
            ulong pagesCount = pageList.GetPagesCount();
            ulong size = pagesCount * PageSize;

            ulong endAddr = address + size;

            ulong addrSpacePagesCount = (AddrSpaceEnd - AddrSpaceStart) / PageSize;

            if (AddrSpaceStart > address)
            {
                return KernelResult.InvalidMemState;
            }

            if (addrSpacePagesCount < pagesCount)
            {
                return KernelResult.InvalidMemState;
            }

            if (endAddr - 1 > AddrSpaceEnd - 1)
            {
                return KernelResult.InvalidMemState;
            }

            lock (_blockManager)
            {
                KPageList currentPageList = new();

                GetPhysicalRegions(address, size, currentPageList);

                if (!currentPageList.IsEqual(pageList))
                {
                    return KernelResult.InvalidMemRange;
                }

                if (CheckRange(
                    address,
                    size,
                    MemoryState.Mask,
                    stateExpected,
                    KMemoryPermission.None,
                    KMemoryPermission.None,
                    MemoryAttribute.Mask,
                    MemoryAttribute.None,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out MemoryState state,
                    out _,
                    out _))
                {
                    if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                    {
                        return KernelResult.OutOfResource;
                    }

                    Result result = Unmap(address, pagesCount);

                    if (result == Result.Success)
                    {
                        _blockManager.InsertBlock(address, pagesCount, MemoryState.Unmapped);
                    }

                    return result;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public static Result MapNormalMemory(long address, long size, KMemoryPermission permission)
        {
            // TODO.
            return Result.Success;
        }

        public static Result MapIoMemory(long address, long size, KMemoryPermission permission)
        {
            // TODO.
            return Result.Success;
        }

        public Result MapPages(
            ulong pagesCount,
            int alignment,
            ulong srcPa,
            bool paIsValid,
            ulong regionStart,
            ulong regionPagesCount,
            MemoryState state,
            KMemoryPermission permission,
            out ulong address)
        {
            address = 0;

            ulong regionSize = regionPagesCount * PageSize;

            if (!CanContain(regionStart, regionSize, state))
            {
                return KernelResult.InvalidMemState;
            }

            if (regionPagesCount <= pagesCount)
            {
                return KernelResult.OutOfMemory;
            }

            lock (_blockManager)
            {
                address = AllocateVa(regionStart, regionPagesCount, pagesCount, alignment);

                if (address == 0)
                {
                    return KernelResult.OutOfMemory;
                }

                if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                {
                    return KernelResult.OutOfResource;
                }

                Result result;

                if (paIsValid)
                {
                    result = MapPages(address, pagesCount, srcPa, permission, MemoryMapFlags.Private);
                }
                else
                {
                    result = AllocateAndMapPages(address, pagesCount, permission);
                }

                if (result != Result.Success)
                {
                    return result;
                }

                _blockManager.InsertBlock(address, pagesCount, state, permission);
            }

            return Result.Success;
        }

        public Result MapPages(ulong address, ulong pagesCount, MemoryState state, KMemoryPermission permission)
        {
            ulong size = pagesCount * PageSize;

            if (!CanContain(address, size, state))
            {
                return KernelResult.InvalidMemState;
            }

            lock (_blockManager)
            {
                if (!IsUnmapped(address, size))
                {
                    return KernelResult.InvalidMemState;
                }

                if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                {
                    return KernelResult.OutOfResource;
                }

                Result result = AllocateAndMapPages(address, pagesCount, permission);

                if (result == Result.Success)
                {
                    _blockManager.InsertBlock(address, pagesCount, state, permission);
                }

                return result;
            }
        }

        private Result AllocateAndMapPages(ulong address, ulong pagesCount, KMemoryPermission permission)
        {
            KMemoryRegionManager region = GetMemoryRegionManager();

            Result result = region.AllocatePages(out KPageList pageList, pagesCount);

            if (result != Result.Success)
            {
                return result;
            }

            using var _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager));

            return MapPages(address, pageList, permission, MemoryMapFlags.Private);
        }

        public Result MapProcessCodeMemory(ulong dst, ulong src, ulong size)
        {
            lock (_blockManager)
            {
                bool success = CheckRange(
                    src,
                    size,
                    MemoryState.Mask,
                    MemoryState.Heap,
                    KMemoryPermission.Mask,
                    KMemoryPermission.ReadAndWrite,
                    MemoryAttribute.Mask,
                    MemoryAttribute.None,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out MemoryState state,
                    out KMemoryPermission permission,
                    out _);

                success &= IsUnmapped(dst, size);

                if (success)
                {
                    if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion * 2))
                    {
                        return KernelResult.OutOfResource;
                    }

                    ulong pagesCount = size / PageSize;

                    Result result = MapMemory(src, dst, pagesCount, permission, KMemoryPermission.None);

                    _blockManager.InsertBlock(src, pagesCount, state, KMemoryPermission.None, MemoryAttribute.Borrowed);
                    _blockManager.InsertBlock(dst, pagesCount, MemoryState.ModCodeStatic);

                    return Result.Success;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public Result UnmapProcessCodeMemory(ulong dst, ulong src, ulong size)
        {
            lock (_blockManager)
            {
                bool success = CheckRange(
                    src,
                    size,
                    MemoryState.Mask,
                    MemoryState.Heap,
                    KMemoryPermission.None,
                    KMemoryPermission.None,
                    MemoryAttribute.Mask,
                    MemoryAttribute.Borrowed,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out _,
                    out _,
                    out _);

                success &= CheckRange(
                    dst,
                    PageSize,
                    MemoryState.UnmapProcessCodeMemoryAllowed,
                    MemoryState.UnmapProcessCodeMemoryAllowed,
                    KMemoryPermission.None,
                    KMemoryPermission.None,
                    MemoryAttribute.Mask,
                    MemoryAttribute.None,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out MemoryState state,
                    out _,
                    out _);

                success &= CheckRange(
                    dst,
                    size,
                    MemoryState.Mask,
                    state,
                    KMemoryPermission.None,
                    KMemoryPermission.None,
                    MemoryAttribute.Mask,
                    MemoryAttribute.None);

                if (success)
                {
                    ulong pagesCount = size / PageSize;

                    Result result = Unmap(dst, pagesCount);

                    if (result != Result.Success)
                    {
                        return result;
                    }

                    // TODO: Missing some checks here.

                    if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion * 2))
                    {
                        return KernelResult.OutOfResource;
                    }

                    _blockManager.InsertBlock(dst, pagesCount, MemoryState.Unmapped);
                    _blockManager.InsertBlock(src, pagesCount, MemoryState.Heap, KMemoryPermission.ReadAndWrite);

                    return Result.Success;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public Result SetHeapSize(ulong size, out ulong address)
        {
            address = 0;

            if (size > HeapRegionEnd - HeapRegionStart)
            {
                return KernelResult.OutOfMemory;
            }

            KProcess currentProcess = KernelStatic.GetCurrentProcess();

            lock (_blockManager)
            {
                ulong currentHeapSize = GetHeapSize();

                if (currentHeapSize <= size)
                {
                    // Expand.
                    ulong sizeDelta = size - currentHeapSize;

                    if (currentProcess.ResourceLimit != null && sizeDelta != 0 &&
                        !currentProcess.ResourceLimit.Reserve(LimitableResource.Memory, sizeDelta))
                    {
                        return KernelResult.ResLimitExceeded;
                    }

                    ulong pagesCount = sizeDelta / PageSize;

                    KMemoryRegionManager region = GetMemoryRegionManager();

                    Result result = region.AllocatePages(out KPageList pageList, pagesCount);

                    using var _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager));

                    void CleanUpForError()
                    {
                        if (currentProcess.ResourceLimit != null && sizeDelta != 0)
                        {
                            currentProcess.ResourceLimit.Release(LimitableResource.Memory, sizeDelta);
                        }
                    }

                    if (result != Result.Success)
                    {
                        CleanUpForError();

                        return result;
                    }

                    if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                    {
                        CleanUpForError();

                        return KernelResult.OutOfResource;
                    }

                    if (!IsUnmapped(_currentHeapAddr, sizeDelta))
                    {
                        CleanUpForError();

                        return KernelResult.InvalidMemState;
                    }

                    result = MapPages(_currentHeapAddr, pageList, KMemoryPermission.ReadAndWrite, MemoryMapFlags.Private, true, (byte)_heapFillValue);

                    if (result != Result.Success)
                    {
                        CleanUpForError();

                        return result;
                    }

                    _blockManager.InsertBlock(_currentHeapAddr, pagesCount, MemoryState.Heap, KMemoryPermission.ReadAndWrite);
                }
                else
                {
                    // Shrink.
                    ulong freeAddr = HeapRegionStart + size;
                    ulong sizeDelta = currentHeapSize - size;

                    if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                    {
                        return KernelResult.OutOfResource;
                    }

                    if (!CheckRange(
                        freeAddr,
                        sizeDelta,
                        MemoryState.Mask,
                        MemoryState.Heap,
                        KMemoryPermission.Mask,
                        KMemoryPermission.ReadAndWrite,
                        MemoryAttribute.Mask,
                        MemoryAttribute.None,
                        MemoryAttribute.IpcAndDeviceMapped,
                        out _,
                        out _,
                        out _))
                    {
                        return KernelResult.InvalidMemState;
                    }

                    ulong pagesCount = sizeDelta / PageSize;

                    Result result = Unmap(freeAddr, pagesCount);

                    if (result != Result.Success)
                    {
                        return result;
                    }

                    currentProcess.ResourceLimit?.Release(LimitableResource.Memory, sizeDelta);

                    _blockManager.InsertBlock(freeAddr, pagesCount, MemoryState.Unmapped);
                }

                _currentHeapAddr = HeapRegionStart + size;
            }

            address = HeapRegionStart;

            return Result.Success;
        }

        public Result SetMemoryPermission(ulong address, ulong size, KMemoryPermission permission)
        {
            lock (_blockManager)
            {
                if (CheckRange(
                    address,
                    size,
                    MemoryState.PermissionChangeAllowed,
                    MemoryState.PermissionChangeAllowed,
                    KMemoryPermission.None,
                    KMemoryPermission.None,
                    MemoryAttribute.Mask,
                    MemoryAttribute.None,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out MemoryState oldState,
                    out KMemoryPermission oldPermission,
                    out _))
                {
                    if (permission != oldPermission)
                    {
                        if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                        {
                            return KernelResult.OutOfResource;
                        }

                        ulong pagesCount = size / PageSize;

                        Result result = Reprotect(address, pagesCount, permission);

                        if (result != Result.Success)
                        {
                            return result;
                        }

                        _blockManager.InsertBlock(address, pagesCount, oldState, permission);
                    }

                    return Result.Success;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public ulong GetTotalHeapSize()
        {
            lock (_blockManager)
            {
                return GetHeapSize() + PhysicalMemoryUsage;
            }
        }

        private ulong GetHeapSize()
        {
            return _currentHeapAddr - HeapRegionStart;
        }

        public Result SetHeapCapacity(ulong capacity)
        {
            lock (_blockManager)
            {
                _heapCapacity = capacity;
            }

            return Result.Success;
        }

        public Result SetMemoryAttribute(
            ulong address,
            ulong size,
            MemoryAttribute attributeMask,
            MemoryAttribute attributeValue)
        {
            lock (_blockManager)
            {
                if (CheckRange(
                    address,
                    size,
                    MemoryState.AttributeChangeAllowed,
                    MemoryState.AttributeChangeAllowed,
                    KMemoryPermission.None,
                    KMemoryPermission.None,
                    MemoryAttribute.BorrowedAndIpcMapped,
                    MemoryAttribute.None,
                    MemoryAttribute.DeviceMappedAndUncached,
                    out MemoryState state,
                    out KMemoryPermission permission,
                    out MemoryAttribute attribute))
                {
                    if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                    {
                        return KernelResult.OutOfResource;
                    }

                    ulong pagesCount = size / PageSize;

                    attribute &= ~attributeMask;
                    attribute |= attributeMask & attributeValue;

                    _blockManager.InsertBlock(address, pagesCount, state, permission, attribute);

                    return Result.Success;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public KMemoryInfo QueryMemory(ulong address)
        {
            if (address >= AddrSpaceStart &&
                address < AddrSpaceEnd)
            {
                lock (_blockManager)
                {
                    return _blockManager.FindBlock(address).GetInfo();
                }
            }
            else
            {
                return new KMemoryInfo(
                    AddrSpaceEnd,
                    ~AddrSpaceEnd + 1,
                    MemoryState.Reserved,
                    KMemoryPermission.None,
                    MemoryAttribute.None,
                    KMemoryPermission.None,
                    0,
                    0);
            }
        }

        public Result Map(ulong dst, ulong src, ulong size)
        {
            bool success;

            lock (_blockManager)
            {
                success = CheckRange(
                    src,
                    size,
                    MemoryState.MapAllowed,
                    MemoryState.MapAllowed,
                    KMemoryPermission.Mask,
                    KMemoryPermission.ReadAndWrite,
                    MemoryAttribute.Mask,
                    MemoryAttribute.None,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out MemoryState srcState,
                    out _,
                    out _);

                success &= IsUnmapped(dst, size);

                if (success)
                {
                    if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion * 2))
                    {
                        return KernelResult.OutOfResource;
                    }

                    ulong pagesCount = size / PageSize;

                    Result result = MapMemory(src, dst, pagesCount, KMemoryPermission.ReadAndWrite, KMemoryPermission.ReadAndWrite);

                    if (result != Result.Success)
                    {
                        return result;
                    }

                    _blockManager.InsertBlock(src, pagesCount, srcState, KMemoryPermission.None, MemoryAttribute.Borrowed);
                    _blockManager.InsertBlock(dst, pagesCount, MemoryState.Stack, KMemoryPermission.ReadAndWrite);

                    return Result.Success;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public Result UnmapForKernel(ulong address, ulong pagesCount, MemoryState stateExpected)
        {
            ulong size = pagesCount * PageSize;

            lock (_blockManager)
            {
                if (CheckRange(
                    address,
                    size,
                    MemoryState.Mask,
                    stateExpected,
                    KMemoryPermission.None,
                    KMemoryPermission.None,
                    MemoryAttribute.Mask,
                    MemoryAttribute.None,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out _,
                    out _,
                    out _))
                {
                    if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                    {
                        return KernelResult.OutOfResource;
                    }

                    Result result = Unmap(address, pagesCount);

                    if (result == Result.Success)
                    {
                        _blockManager.InsertBlock(address, pagesCount, MemoryState.Unmapped);
                    }

                    return Result.Success;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public Result Unmap(ulong dst, ulong src, ulong size)
        {
            bool success;

            lock (_blockManager)
            {
                success = CheckRange(
                    src,
                    size,
                    MemoryState.MapAllowed,
                    MemoryState.MapAllowed,
                    KMemoryPermission.Mask,
                    KMemoryPermission.None,
                    MemoryAttribute.Mask,
                    MemoryAttribute.Borrowed,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out MemoryState srcState,
                    out _,
                    out _);

                success &= CheckRange(
                    dst,
                    size,
                    MemoryState.Mask,
                    MemoryState.Stack,
                    KMemoryPermission.None,
                    KMemoryPermission.None,
                    MemoryAttribute.Mask,
                    MemoryAttribute.None,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out _,
                    out KMemoryPermission dstPermission,
                    out _);

                if (success)
                {
                    if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion * 2))
                    {
                        return KernelResult.OutOfResource;
                    }

                    ulong pagesCount = size / PageSize;

                    Result result = UnmapMemory(dst, src, pagesCount, dstPermission, KMemoryPermission.ReadAndWrite);

                    if (result != Result.Success)
                    {
                        return result;
                    }

                    _blockManager.InsertBlock(src, pagesCount, srcState, KMemoryPermission.ReadAndWrite);
                    _blockManager.InsertBlock(dst, pagesCount, MemoryState.Unmapped);

                    return Result.Success;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public Result UnmapProcessMemory(ulong dst, ulong size, KPageTableBase srcPageTable, ulong src)
        {
            lock (_blockManager)
            {
                lock (srcPageTable._blockManager)
                {
                    bool success = CheckRange(
                        dst,
                        size,
                        MemoryState.Mask,
                        MemoryState.ProcessMemory,
                        KMemoryPermission.ReadAndWrite,
                        KMemoryPermission.ReadAndWrite,
                        MemoryAttribute.Mask,
                        MemoryAttribute.None,
                        MemoryAttribute.IpcAndDeviceMapped,
                        out _,
                        out _,
                        out _);

                    success &= srcPageTable.CheckRange(
                        src,
                        size,
                        MemoryState.MapProcessAllowed,
                        MemoryState.MapProcessAllowed,
                        KMemoryPermission.None,
                        KMemoryPermission.None,
                        MemoryAttribute.Mask,
                        MemoryAttribute.None,
                        MemoryAttribute.IpcAndDeviceMapped,
                        out _,
                        out _,
                        out _);

                    if (!success)
                    {
                        return KernelResult.InvalidMemState;
                    }

                    KPageList srcPageList = new();
                    KPageList dstPageList = new();

                    srcPageTable.GetPhysicalRegions(src, size, srcPageList);
                    GetPhysicalRegions(dst, size, dstPageList);

                    if (!dstPageList.IsEqual(srcPageList))
                    {
                        return KernelResult.InvalidMemRange;
                    }
                }

                if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                {
                    return KernelResult.OutOfResource;
                }

                ulong pagesCount = size / PageSize;

                Result result = Unmap(dst, pagesCount);

                if (result != Result.Success)
                {
                    return result;
                }

                _blockManager.InsertBlock(dst, pagesCount, MemoryState.Unmapped);

                return Result.Success;
            }
        }

        public Result SetProcessMemoryPermission(ulong address, ulong size, KMemoryPermission permission)
        {
            lock (_blockManager)
            {
                if (CheckRange(
                    address,
                    size,
                    MemoryState.ProcessPermissionChangeAllowed,
                    MemoryState.ProcessPermissionChangeAllowed,
                    KMemoryPermission.None,
                    KMemoryPermission.None,
                    MemoryAttribute.Mask,
                    MemoryAttribute.None,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out MemoryState oldState,
                    out KMemoryPermission oldPermission,
                    out _))
                {
                    MemoryState newState = oldState;

                    // If writing into the code region is allowed, then we need
                    // to change it to mutable.
                    if ((permission & KMemoryPermission.Write) != 0)
                    {
                        if (oldState == MemoryState.CodeStatic)
                        {
                            newState = MemoryState.CodeMutable;
                        }
                        else if (oldState == MemoryState.ModCodeStatic)
                        {
                            newState = MemoryState.ModCodeMutable;
                        }
                        else
                        {
                            throw new InvalidOperationException($"Memory state \"{oldState}\" not valid for this operation.");
                        }
                    }

                    if (newState != oldState || permission != oldPermission)
                    {
                        if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                        {
                            return KernelResult.OutOfResource;
                        }

                        ulong pagesCount = size / PageSize;

                        Result result;

                        if ((oldPermission & KMemoryPermission.Execute) != 0)
                        {
                            result = ReprotectWithAttributes(address, pagesCount, permission);
                        }
                        else
                        {
                            result = Reprotect(address, pagesCount, permission);
                        }

                        if (result != Result.Success)
                        {
                            return result;
                        }

                        _blockManager.InsertBlock(address, pagesCount, newState, permission);
                    }

                    return Result.Success;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public Result MapPhysicalMemory(ulong address, ulong size)
        {
            ulong endAddr = address + size;

            lock (_blockManager)
            {
                ulong mappedSize = 0;

                foreach (KMemoryInfo info in IterateOverRange(address, endAddr))
                {
                    if (info.State != MemoryState.Unmapped)
                    {
                        mappedSize += GetSizeInRange(info, address, endAddr);
                    }
                }

                if (mappedSize == size)
                {
                    return Result.Success;
                }

                ulong remainingSize = size - mappedSize;

                ulong remainingPages = remainingSize / PageSize;

                KProcess currentProcess = KernelStatic.GetCurrentProcess();

                if (currentProcess.ResourceLimit != null &&
                   !currentProcess.ResourceLimit.Reserve(LimitableResource.Memory, remainingSize))
                {
                    return KernelResult.ResLimitExceeded;
                }

                KMemoryRegionManager region = GetMemoryRegionManager();

                Result result = region.AllocatePages(out KPageList pageList, remainingPages);

                using var _ = new OnScopeExit(() => pageList.DecrementPagesReferenceCount(Context.MemoryManager));

                void CleanUpForError()
                {
                    currentProcess.ResourceLimit?.Release(LimitableResource.Memory, remainingSize);
                }

                if (result != Result.Success)
                {
                    CleanUpForError();

                    return result;
                }

                if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                {
                    CleanUpForError();

                    return KernelResult.OutOfResource;
                }

                LinkedListNode<KPageNode> pageListNode = pageList.Nodes.First;

                KPageNode pageNode = pageListNode.Value;

                ulong srcPa = pageNode.Address;
                ulong srcPaPages = pageNode.PagesCount;

                foreach (KMemoryInfo info in IterateOverRange(address, endAddr))
                {
                    if (info.State != MemoryState.Unmapped)
                    {
                        continue;
                    }

                    ulong blockSize = GetSizeInRange(info, address, endAddr);

                    ulong dstVaPages = blockSize / PageSize;

                    ulong dstVa = GetAddrInRange(info, address);

                    while (dstVaPages > 0)
                    {
                        if (srcPaPages == 0)
                        {
                            pageListNode = pageListNode.Next;

                            pageNode = pageListNode.Value;

                            srcPa = pageNode.Address;
                            srcPaPages = pageNode.PagesCount;
                        }

                        ulong currentPagesCount = Math.Min(srcPaPages, dstVaPages);

                        MapPages(dstVa, currentPagesCount, srcPa, KMemoryPermission.ReadAndWrite, MemoryMapFlags.Private);

                        dstVa += currentPagesCount * PageSize;
                        srcPa += currentPagesCount * PageSize;
                        srcPaPages -= currentPagesCount;
                        dstVaPages -= currentPagesCount;
                    }
                }

                PhysicalMemoryUsage += remainingSize;

                ulong pagesCount = size / PageSize;

                _blockManager.InsertBlock(
                    address,
                    pagesCount,
                    MemoryState.Unmapped,
                    KMemoryPermission.None,
                    MemoryAttribute.None,
                    MemoryState.Heap,
                    KMemoryPermission.ReadAndWrite,
                    MemoryAttribute.None);
            }

            return Result.Success;
        }

        public Result UnmapPhysicalMemory(ulong address, ulong size)
        {
            ulong endAddr = address + size;

            lock (_blockManager)
            {
                // Scan, ensure that the region can be unmapped (all blocks are heap or
                // already unmapped), fill pages list for freeing memory.
                ulong heapMappedSize = 0;

                foreach (KMemoryInfo info in IterateOverRange(address, endAddr))
                {
                    if (info.State == MemoryState.Heap)
                    {
                        if (info.Attribute != MemoryAttribute.None)
                        {
                            return KernelResult.InvalidMemState;
                        }

                        ulong blockSize = GetSizeInRange(info, address, endAddr);

                        heapMappedSize += blockSize;
                    }
                    else if (info.State != MemoryState.Unmapped)
                    {
                        return KernelResult.InvalidMemState;
                    }
                }

                if (heapMappedSize == 0)
                {
                    return Result.Success;
                }

                if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                {
                    return KernelResult.OutOfResource;
                }

                // Try to unmap all the heap mapped memory inside range.
                Result result = Result.Success;

                foreach (KMemoryInfo info in IterateOverRange(address, endAddr))
                {
                    if (info.State == MemoryState.Heap)
                    {
                        ulong blockSize = GetSizeInRange(info, address, endAddr);
                        ulong blockAddress = GetAddrInRange(info, address);

                        ulong blockPagesCount = blockSize / PageSize;

                        result = Unmap(blockAddress, blockPagesCount);

                        // The kernel would attempt to remap if this fails, but we don't because:
                        // - The implementation may not support remapping if memory aliasing is not supported on the platform.
                        // - Unmap can't ever fail here anyway.
                        Debug.Assert(result == Result.Success);
                    }
                }

                if (result == Result.Success)
                {
                    PhysicalMemoryUsage -= heapMappedSize;

                    KProcess currentProcess = KernelStatic.GetCurrentProcess();

                    currentProcess.ResourceLimit?.Release(LimitableResource.Memory, heapMappedSize);

                    ulong pagesCount = size / PageSize;

                    _blockManager.InsertBlock(address, pagesCount, MemoryState.Unmapped);
                }

                return result;
            }
        }

        public Result CopyDataToCurrentProcess(
            ulong dst,
            ulong size,
            ulong src,
            MemoryState stateMask,
            MemoryState stateExpected,
            KMemoryPermission permission,
            MemoryAttribute attributeMask,
            MemoryAttribute attributeExpected)
        {
            // Client -> server.
            return CopyDataFromOrToCurrentProcess(
                size,
                src,
                dst,
                stateMask,
                stateExpected,
                permission,
                attributeMask,
                attributeExpected,
                toServer: true);
        }

        public Result CopyDataFromCurrentProcess(
            ulong dst,
            ulong size,
            MemoryState stateMask,
            MemoryState stateExpected,
            KMemoryPermission permission,
            MemoryAttribute attributeMask,
            MemoryAttribute attributeExpected,
            ulong src)
        {
            // Server -> client.
            return CopyDataFromOrToCurrentProcess(
                size,
                dst,
                src,
                stateMask,
                stateExpected,
                permission,
                attributeMask,
                attributeExpected,
                toServer: false);
        }

        private Result CopyDataFromOrToCurrentProcess(
            ulong size,
            ulong clientAddress,
            ulong serverAddress,
            MemoryState stateMask,
            MemoryState stateExpected,
            KMemoryPermission permission,
            MemoryAttribute attributeMask,
            MemoryAttribute attributeExpected,
            bool toServer)
        {
            if (AddrSpaceStart > clientAddress)
            {
                return KernelResult.InvalidMemState;
            }

            ulong srcEndAddr = clientAddress + size;

            if (srcEndAddr <= clientAddress || srcEndAddr - 1 > AddrSpaceEnd - 1)
            {
                return KernelResult.InvalidMemState;
            }

            lock (_blockManager)
            {
                if (CheckRange(
                    clientAddress,
                    size,
                    stateMask,
                    stateExpected,
                    permission,
                    permission,
                    attributeMask | MemoryAttribute.Uncached,
                    attributeExpected))
                {
                    KProcess currentProcess = KernelStatic.GetCurrentProcess();

                    while (size > 0)
                    {
                        ulong copySize = 0x100000; // Copy chunck size. Any value will do, moderate sizes are recommended.

                        if (copySize > size)
                        {
                            copySize = size;
                        }

                        if (toServer)
                        {
                            currentProcess.CpuMemory.Write(serverAddress, GetSpan(clientAddress, (int)copySize));
                        }
                        else
                        {
                            Write(clientAddress, currentProcess.CpuMemory.GetSpan(serverAddress, (int)copySize));
                        }

                        serverAddress += copySize;
                        clientAddress += copySize;
                        size -= copySize;
                    }

                    return Result.Success;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public Result MapBufferFromClientProcess(
            ulong size,
            ulong src,
            KPageTableBase srcPageTable,
            KMemoryPermission permission,
            MemoryState state,
            bool send,
            out ulong dst)
        {
            dst = 0;

            lock (srcPageTable._blockManager)
            {
                lock (_blockManager)
                {
                    Result result = srcPageTable.ReprotectClientProcess(
                        src,
                        size,
                        permission,
                        state,
                        out int blocksNeeded);

                    if (result != Result.Success)
                    {
                        return result;
                    }

                    if (!srcPageTable._slabManager.CanAllocate(blocksNeeded))
                    {
                        return KernelResult.OutOfResource;
                    }

                    ulong srcMapAddress = BitUtils.AlignUp<ulong>(src, PageSize);
                    ulong srcMapEndAddr = BitUtils.AlignDown<ulong>(src + size, PageSize);
                    ulong srcMapSize = srcMapEndAddr - srcMapAddress;

                    result = MapPagesFromClientProcess(size, src, permission, state, srcPageTable, send, out ulong va);

                    if (result != Result.Success)
                    {
                        if (srcMapEndAddr > srcMapAddress)
                        {
                            srcPageTable.UnmapIpcRestorePermission(src, size, state);
                        }

                        return result;
                    }

                    if (srcMapAddress < srcMapEndAddr)
                    {
                        KMemoryPermission permissionMask = permission == KMemoryPermission.ReadAndWrite
                            ? KMemoryPermission.None
                            : KMemoryPermission.Read;

                        srcPageTable._blockManager.InsertBlock(srcMapAddress, srcMapSize / PageSize, SetIpcMappingPermissions, permissionMask);
                    }

                    dst = va;
                }
            }

            return Result.Success;
        }

        private Result ReprotectClientProcess(
            ulong address,
            ulong size,
            KMemoryPermission permission,
            MemoryState state,
            out int blocksNeeded)
        {
            blocksNeeded = 0;

            if (AddrSpaceStart > address)
            {
                return KernelResult.InvalidMemState;
            }

            ulong endAddr = address + size;

            if (endAddr <= address || endAddr - 1 > AddrSpaceEnd - 1)
            {
                return KernelResult.InvalidMemState;
            }

            MemoryState stateMask;

            switch (state)
            {
                case MemoryState.IpcBuffer0:
                    stateMask = MemoryState.IpcSendAllowedType0;
                    break;
                case MemoryState.IpcBuffer1:
                    stateMask = MemoryState.IpcSendAllowedType1;
                    break;
                case MemoryState.IpcBuffer3:
                    stateMask = MemoryState.IpcSendAllowedType3;
                    break;
                default:
                    return KernelResult.InvalidCombination;
            }

            KMemoryPermission permissionMask = permission == KMemoryPermission.ReadAndWrite
                ? KMemoryPermission.None
                : KMemoryPermission.Read;

            MemoryAttribute attributeMask = MemoryAttribute.Borrowed | MemoryAttribute.Uncached;

            if (state == MemoryState.IpcBuffer0)
            {
                attributeMask |= MemoryAttribute.DeviceMapped;
            }

            ulong addressRounded = BitUtils.AlignUp<ulong>(address, PageSize);
            ulong addressTruncated = BitUtils.AlignDown<ulong>(address, PageSize);
            ulong endAddrRounded = BitUtils.AlignUp<ulong>(endAddr, PageSize);
            ulong endAddrTruncated = BitUtils.AlignDown<ulong>(endAddr, PageSize);

            if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
            {
                return KernelResult.OutOfResource;
            }

            ulong visitedSize = 0;

            void CleanUpForError()
            {
                if (visitedSize == 0)
                {
                    return;
                }

                ulong endAddrVisited = address + visitedSize;

                foreach (KMemoryInfo info in IterateOverRange(addressRounded, endAddrVisited))
                {
                    if ((info.Permission & KMemoryPermission.ReadAndWrite) != permissionMask && info.IpcRefCount == 0)
                    {
                        ulong blockAddress = GetAddrInRange(info, addressRounded);
                        ulong blockSize = GetSizeInRange(info, addressRounded, endAddrVisited);

                        ulong blockPagesCount = blockSize / PageSize;

                        Result reprotectResult = Reprotect(blockAddress, blockPagesCount, info.Permission);
                        Debug.Assert(reprotectResult == Result.Success);
                    }
                }
            }

            // Signal a read for any resources tracking reads in the region, as the other process is likely to use their data.
            SignalMemoryTracking(addressTruncated, endAddrRounded - addressTruncated, false);

            // Reprotect the aligned pages range on the client to make them inaccessible from the client process.
            Result result;

            if (addressRounded < endAddrTruncated)
            {
                foreach (KMemoryInfo info in IterateOverRange(addressRounded, endAddrTruncated))
                {
                    // Check if the block state matches what we expect.
                    if ((info.State & stateMask) != stateMask ||
                        (info.Permission & permission) != permission ||
                        (info.Attribute & attributeMask) != MemoryAttribute.None)
                    {
                        CleanUpForError();

                        return KernelResult.InvalidMemState;
                    }

                    ulong blockAddress = GetAddrInRange(info, addressRounded);
                    ulong blockSize = GetSizeInRange(info, addressRounded, endAddrTruncated);

                    ulong blockPagesCount = blockSize / PageSize;

                    // If the first block starts before the aligned range, it will need to be split.
                    if (info.Address < addressRounded)
                    {
                        blocksNeeded++;
                    }

                    // If the last block ends after the aligned range, it will need to be split.
                    if (endAddrTruncated - 1 < info.Address + info.Size - 1)
                    {
                        blocksNeeded++;
                    }

                    if ((info.Permission & KMemoryPermission.ReadAndWrite) != permissionMask && info.IpcRefCount == 0)
                    {
                        result = Reprotect(blockAddress, blockPagesCount, permissionMask);

                        if (result != Result.Success)
                        {
                            CleanUpForError();

                            return result;
                        }
                    }

                    visitedSize += blockSize;
                }
            }

            return Result.Success;
        }

        private Result MapPagesFromClientProcess(
            ulong size,
            ulong address,
            KMemoryPermission permission,
            MemoryState state,
            KPageTableBase srcPageTable,
            bool send,
            out ulong dst)
        {
            dst = 0;

            if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
            {
                return KernelResult.OutOfResource;
            }

            ulong endAddr = address + size;

            ulong addressTruncated = BitUtils.AlignDown<ulong>(address, PageSize);
            ulong addressRounded = BitUtils.AlignUp<ulong>(address, PageSize);
            ulong endAddrTruncated = BitUtils.AlignDown<ulong>(endAddr, PageSize);
            ulong endAddrRounded = BitUtils.AlignUp<ulong>(endAddr, PageSize);

            ulong neededSize = endAddrRounded - addressTruncated;

            ulong neededPagesCount = neededSize / PageSize;

            ulong regionPagesCount = (AliasRegionEnd - AliasRegionStart) / PageSize;

            ulong va = 0;

            for (int unit = _mappingUnitSizes.Length - 1; unit >= 0 && va == 0; unit--)
            {
                int alignment = _mappingUnitSizes[unit];

                va = AllocateVa(AliasRegionStart, regionPagesCount, neededPagesCount, alignment);
            }

            if (va == 0)
            {
                return KernelResult.OutOfVaSpace;
            }

            ulong dstFirstPagePa = 0;
            ulong dstLastPagePa = 0;
            ulong currentVa = va;

            using var _ = new OnScopeExit(() =>
            {
                if (dstFirstPagePa != 0)
                {
                    Context.MemoryManager.DecrementPagesReferenceCount(dstFirstPagePa, 1);
                }

                if (dstLastPagePa != 0)
                {
                    Context.MemoryManager.DecrementPagesReferenceCount(dstLastPagePa, 1);
                }
            });

            void CleanUpForError()
            {
                if (currentVa != va)
                {
                    Unmap(va, (currentVa - va) / PageSize);
                }
            }

            // Is the first page address aligned?
            // If not, allocate a new page and copy the unaligned chunck.
            if (addressTruncated < addressRounded)
            {
                dstFirstPagePa = GetMemoryRegionManager().AllocatePagesContiguous(Context, 1, _allocateFromBack);

                if (dstFirstPagePa == 0)
                {
                    CleanUpForError();

                    return KernelResult.OutOfMemory;
                }
            }

            // Is the last page end address aligned?
            // If not, allocate a new page and copy the unaligned chunck.
            if (endAddrTruncated < endAddrRounded && (addressTruncated == addressRounded || addressTruncated < endAddrTruncated))
            {
                dstLastPagePa = GetMemoryRegionManager().AllocatePagesContiguous(Context, 1, _allocateFromBack);

                if (dstLastPagePa == 0)
                {
                    CleanUpForError();

                    return KernelResult.OutOfMemory;
                }
            }

            if (dstFirstPagePa != 0)
            {
                ulong firstPageFillAddress = dstFirstPagePa;
                ulong unusedSizeAfter;

                if (send)
                {
                    ulong unusedSizeBefore = address - addressTruncated;

                    Context.Memory.Fill(GetDramAddressFromPa(dstFirstPagePa), unusedSizeBefore, (byte)_ipcFillValue);

                    ulong copySize = addressRounded <= endAddr ? addressRounded - address : size;
                    var data = srcPageTable.GetSpan(addressTruncated + unusedSizeBefore, (int)copySize);

                    Context.Memory.Write(GetDramAddressFromPa(dstFirstPagePa + unusedSizeBefore), data);

                    firstPageFillAddress += unusedSizeBefore + copySize;

                    unusedSizeAfter = addressRounded > endAddr ? addressRounded - endAddr : 0;
                }
                else
                {
                    unusedSizeAfter = PageSize;
                }

                if (unusedSizeAfter != 0)
                {
                    Context.Memory.Fill(GetDramAddressFromPa(firstPageFillAddress), unusedSizeAfter, (byte)_ipcFillValue);
                }

                Result result = MapPages(currentVa, 1, dstFirstPagePa, permission, MemoryMapFlags.Private);

                if (result != Result.Success)
                {
                    CleanUpForError();

                    return result;
                }

                currentVa += PageSize;
            }

            if (endAddrTruncated > addressRounded)
            {
                ulong alignedSize = endAddrTruncated - addressRounded;

                Result result;

                if (srcPageTable.Supports4KBPages)
                {
                    KPageList pageList = new();
                    srcPageTable.GetPhysicalRegions(addressRounded, alignedSize, pageList);

                    result = MapPages(currentVa, pageList, permission, MemoryMapFlags.None);
                }
                else
                {
                    result = MapForeign(srcPageTable.GetHostRegions(addressRounded, alignedSize), currentVa, alignedSize);
                }

                if (result != Result.Success)
                {
                    CleanUpForError();

                    return result;
                }

                currentVa += alignedSize;
            }

            if (dstLastPagePa != 0)
            {
                ulong lastPageFillAddr = dstLastPagePa;
                ulong unusedSizeAfter;

                if (send)
                {
                    ulong copySize = endAddr - endAddrTruncated;
                    var data = srcPageTable.GetSpan(endAddrTruncated, (int)copySize);

                    Context.Memory.Write(GetDramAddressFromPa(dstLastPagePa), data);

                    lastPageFillAddr += copySize;

                    unusedSizeAfter = PageSize - copySize;
                }
                else
                {
                    unusedSizeAfter = PageSize;
                }

                Context.Memory.Fill(GetDramAddressFromPa(lastPageFillAddr), unusedSizeAfter, (byte)_ipcFillValue);

                Result result = MapPages(currentVa, 1, dstLastPagePa, permission, MemoryMapFlags.Private);

                if (result != Result.Success)
                {
                    CleanUpForError();

                    return result;
                }
            }

            _blockManager.InsertBlock(va, neededPagesCount, state, permission);

            dst = va + (address - addressTruncated);

            return Result.Success;
        }

        public Result UnmapNoAttributeIfStateEquals(ulong address, ulong size, MemoryState state)
        {
            if (AddrSpaceStart > address)
            {
                return KernelResult.InvalidMemState;
            }

            ulong endAddr = address + size;

            if (endAddr <= address || endAddr - 1 > AddrSpaceEnd - 1)
            {
                return KernelResult.InvalidMemState;
            }

            lock (_blockManager)
            {
                if (CheckRange(
                    address,
                    size,
                    MemoryState.Mask,
                    state,
                    KMemoryPermission.Read,
                    KMemoryPermission.Read,
                    MemoryAttribute.Mask,
                    MemoryAttribute.None,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out _,
                    out _,
                    out _))
                {
                    if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                    {
                        return KernelResult.OutOfResource;
                    }

                    ulong addressTruncated = BitUtils.AlignDown<ulong>(address, PageSize);
                    ulong addressRounded = BitUtils.AlignUp<ulong>(address, PageSize);
                    ulong endAddrTruncated = BitUtils.AlignDown<ulong>(endAddr, PageSize);
                    ulong endAddrRounded = BitUtils.AlignUp<ulong>(endAddr, PageSize);

                    ulong pagesCount = (endAddrRounded - addressTruncated) / PageSize;

                    Result result = Unmap(addressTruncated, pagesCount);

                    if (result == Result.Success)
                    {
                        _blockManager.InsertBlock(addressTruncated, pagesCount, MemoryState.Unmapped);
                    }

                    return result;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public Result UnmapIpcRestorePermission(ulong address, ulong size, MemoryState state)
        {
            ulong endAddr = address + size;

            ulong addressRounded = BitUtils.AlignUp<ulong>(address, PageSize);
            ulong addressTruncated = BitUtils.AlignDown<ulong>(address, PageSize);
            ulong endAddrRounded = BitUtils.AlignUp<ulong>(endAddr, PageSize);
            ulong endAddrTruncated = BitUtils.AlignDown<ulong>(endAddr, PageSize);

            ulong pagesCount = addressRounded < endAddrTruncated ? (endAddrTruncated - addressRounded) / PageSize : 0;

            if (pagesCount == 0)
            {
                return Result.Success;
            }

            MemoryState stateMask;

            switch (state)
            {
                case MemoryState.IpcBuffer0:
                    stateMask = MemoryState.IpcSendAllowedType0;
                    break;
                case MemoryState.IpcBuffer1:
                    stateMask = MemoryState.IpcSendAllowedType1;
                    break;
                case MemoryState.IpcBuffer3:
                    stateMask = MemoryState.IpcSendAllowedType3;
                    break;
                default:
                    return KernelResult.InvalidCombination;
            }

            MemoryAttribute attributeMask =
                MemoryAttribute.Borrowed |
                MemoryAttribute.IpcMapped |
                MemoryAttribute.Uncached;

            if (state == MemoryState.IpcBuffer0)
            {
                attributeMask |= MemoryAttribute.DeviceMapped;
            }

            if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
            {
                return KernelResult.OutOfResource;
            }

            // Anything on the client side should see this memory as modified.
            SignalMemoryTracking(addressTruncated, endAddrRounded - addressTruncated, true);

            lock (_blockManager)
            {
                foreach (KMemoryInfo info in IterateOverRange(addressRounded, endAddrTruncated))
                {
                    // Check if the block state matches what we expect.
                    if ((info.State & stateMask) != stateMask ||
                        (info.Attribute & attributeMask) != MemoryAttribute.IpcMapped)
                    {
                        return KernelResult.InvalidMemState;
                    }

                    if (info.Permission != info.SourcePermission && info.IpcRefCount == 1)
                    {
                        ulong blockAddress = GetAddrInRange(info, addressRounded);
                        ulong blockSize = GetSizeInRange(info, addressRounded, endAddrTruncated);

                        ulong blockPagesCount = blockSize / PageSize;

                        Result result = Reprotect(blockAddress, blockPagesCount, info.SourcePermission);

                        if (result != Result.Success)
                        {
                            return result;
                        }
                    }
                }

                _blockManager.InsertBlock(addressRounded, pagesCount, RestoreIpcMappingPermissions);

                return Result.Success;
            }
        }

        private static void SetIpcMappingPermissions(KMemoryBlock block, KMemoryPermission permission)
        {
            block.SetIpcMappingPermission(permission);
        }

        private static void RestoreIpcMappingPermissions(KMemoryBlock block, KMemoryPermission permission)
        {
            block.RestoreIpcMappingPermission();
        }

        public Result GetPagesIfStateEquals(
            ulong address,
            ulong size,
            MemoryState stateMask,
            MemoryState stateExpected,
            KMemoryPermission permissionMask,
            KMemoryPermission permissionExpected,
            MemoryAttribute attributeMask,
            MemoryAttribute attributeExpected,
            KPageList pageList)
        {
            if (!InsideAddrSpace(address, size))
            {
                return KernelResult.InvalidMemState;
            }

            lock (_blockManager)
            {
                if (CheckRange(
                    address,
                    size,
                    stateMask | MemoryState.IsPoolAllocated,
                    stateExpected | MemoryState.IsPoolAllocated,
                    permissionMask,
                    permissionExpected,
                    attributeMask,
                    attributeExpected,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out _,
                    out _,
                    out _))
                {
                    GetPhysicalRegions(address, size, pageList);

                    return Result.Success;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public Result BorrowIpcBuffer(ulong address, ulong size)
        {
            return SetAttributesAndChangePermission(
                address,
                size,
                MemoryState.IpcBufferAllowed,
                MemoryState.IpcBufferAllowed,
                KMemoryPermission.Mask,
                KMemoryPermission.ReadAndWrite,
                MemoryAttribute.Mask,
                MemoryAttribute.None,
                KMemoryPermission.None,
                MemoryAttribute.Borrowed);
        }

        public Result BorrowTransferMemory(KPageList pageList, ulong address, ulong size, KMemoryPermission permission)
        {
            return SetAttributesAndChangePermission(
                address,
                size,
                MemoryState.TransferMemoryAllowed,
                MemoryState.TransferMemoryAllowed,
                KMemoryPermission.Mask,
                KMemoryPermission.ReadAndWrite,
                MemoryAttribute.Mask,
                MemoryAttribute.None,
                permission,
                MemoryAttribute.Borrowed,
                pageList);
        }

        public Result BorrowCodeMemory(KPageList pageList, ulong address, ulong size)
        {
            return SetAttributesAndChangePermission(
                address,
                size,
                MemoryState.CodeMemoryAllowed,
                MemoryState.CodeMemoryAllowed,
                KMemoryPermission.Mask,
                KMemoryPermission.ReadAndWrite,
                MemoryAttribute.Mask,
                MemoryAttribute.None,
                KMemoryPermission.None,
                MemoryAttribute.Borrowed,
                pageList);
        }

        private Result SetAttributesAndChangePermission(
            ulong address,
            ulong size,
            MemoryState stateMask,
            MemoryState stateExpected,
            KMemoryPermission permissionMask,
            KMemoryPermission permissionExpected,
            MemoryAttribute attributeMask,
            MemoryAttribute attributeExpected,
            KMemoryPermission newPermission,
            MemoryAttribute attributeSetMask,
            KPageList pageList = null)
        {
            if (address + size <= address || !InsideAddrSpace(address, size))
            {
                return KernelResult.InvalidMemState;
            }

            lock (_blockManager)
            {
                if (CheckRange(
                    address,
                    size,
                    stateMask | MemoryState.IsPoolAllocated,
                    stateExpected | MemoryState.IsPoolAllocated,
                    permissionMask,
                    permissionExpected,
                    attributeMask,
                    attributeExpected,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out MemoryState oldState,
                    out KMemoryPermission oldPermission,
                    out MemoryAttribute oldAttribute))
                {
                    ulong pagesCount = size / PageSize;

                    if (pageList != null)
                    {
                        GetPhysicalRegions(address, pagesCount * PageSize, pageList);
                    }

                    if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                    {
                        return KernelResult.OutOfResource;
                    }

                    if (newPermission == KMemoryPermission.None)
                    {
                        newPermission = oldPermission;
                    }

                    if (newPermission != oldPermission)
                    {
                        Result result = Reprotect(address, pagesCount, newPermission);

                        if (result != Result.Success)
                        {
                            return result;
                        }
                    }

                    MemoryAttribute newAttribute = oldAttribute | attributeSetMask;

                    _blockManager.InsertBlock(address, pagesCount, oldState, newPermission, newAttribute);

                    return Result.Success;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        public Result UnborrowIpcBuffer(ulong address, ulong size)
        {
            return ClearAttributesAndChangePermission(
                address,
                size,
                MemoryState.IpcBufferAllowed,
                MemoryState.IpcBufferAllowed,
                KMemoryPermission.None,
                KMemoryPermission.None,
                MemoryAttribute.Mask,
                MemoryAttribute.Borrowed,
                KMemoryPermission.ReadAndWrite,
                MemoryAttribute.Borrowed);
        }

        public Result UnborrowTransferMemory(ulong address, ulong size, KPageList pageList)
        {
            return ClearAttributesAndChangePermission(
                address,
                size,
                MemoryState.TransferMemoryAllowed,
                MemoryState.TransferMemoryAllowed,
                KMemoryPermission.None,
                KMemoryPermission.None,
                MemoryAttribute.Mask,
                MemoryAttribute.Borrowed,
                KMemoryPermission.ReadAndWrite,
                MemoryAttribute.Borrowed,
                pageList);
        }

        public Result UnborrowCodeMemory(ulong address, ulong size, KPageList pageList)
        {
            return ClearAttributesAndChangePermission(
                address,
                size,
                MemoryState.CodeMemoryAllowed,
                MemoryState.CodeMemoryAllowed,
                KMemoryPermission.None,
                KMemoryPermission.None,
                MemoryAttribute.Mask,
                MemoryAttribute.Borrowed,
                KMemoryPermission.ReadAndWrite,
                MemoryAttribute.Borrowed,
                pageList);
        }

        private Result ClearAttributesAndChangePermission(
            ulong address,
            ulong size,
            MemoryState stateMask,
            MemoryState stateExpected,
            KMemoryPermission permissionMask,
            KMemoryPermission permissionExpected,
            MemoryAttribute attributeMask,
            MemoryAttribute attributeExpected,
            KMemoryPermission newPermission,
            MemoryAttribute attributeClearMask,
            KPageList pageList = null)
        {
            if (address + size <= address || !InsideAddrSpace(address, size))
            {
                return KernelResult.InvalidMemState;
            }

            lock (_blockManager)
            {
                if (CheckRange(
                    address,
                    size,
                    stateMask | MemoryState.IsPoolAllocated,
                    stateExpected | MemoryState.IsPoolAllocated,
                    permissionMask,
                    permissionExpected,
                    attributeMask,
                    attributeExpected,
                    MemoryAttribute.IpcAndDeviceMapped,
                    out MemoryState oldState,
                    out KMemoryPermission oldPermission,
                    out MemoryAttribute oldAttribute))
                {
                    ulong pagesCount = size / PageSize;

                    if (pageList != null)
                    {
                        KPageList currentPageList = new();

                        GetPhysicalRegions(address, pagesCount * PageSize, currentPageList);

                        if (!currentPageList.IsEqual(pageList))
                        {
                            return KernelResult.InvalidMemRange;
                        }
                    }

                    if (!_slabManager.CanAllocate(MaxBlocksNeededForInsertion))
                    {
                        return KernelResult.OutOfResource;
                    }

                    if (newPermission == KMemoryPermission.None)
                    {
                        newPermission = oldPermission;
                    }

                    if (newPermission != oldPermission)
                    {
                        Result result = Reprotect(address, pagesCount, newPermission);

                        if (result != Result.Success)
                        {
                            return result;
                        }
                    }

                    MemoryAttribute newAttribute = oldAttribute & ~attributeClearMask;

                    _blockManager.InsertBlock(address, pagesCount, oldState, newPermission, newAttribute);

                    return Result.Success;
                }
                else
                {
                    return KernelResult.InvalidMemState;
                }
            }
        }

        private static ulong GetAddrInRange(KMemoryInfo info, ulong start)
        {
            if (info.Address < start)
            {
                return start;
            }

            return info.Address;
        }

        private static ulong GetSizeInRange(KMemoryInfo info, ulong start, ulong end)
        {
            ulong endAddr = info.Size + info.Address;
            ulong size = info.Size;

            if (info.Address < start)
            {
                size -= start - info.Address;
            }

            if (endAddr > end)
            {
                size -= endAddr - end;
            }

            return size;
        }

        private bool IsUnmapped(ulong address, ulong size)
        {
            return CheckRange(
                address,
                size,
                MemoryState.Mask,
                MemoryState.Unmapped,
                KMemoryPermission.Mask,
                KMemoryPermission.None,
                MemoryAttribute.Mask,
                MemoryAttribute.None,
                MemoryAttribute.IpcAndDeviceMapped,
                out _,
                out _,
                out _);
        }

        private bool CheckRange(
            ulong address,
            ulong size,
            MemoryState stateMask,
            MemoryState stateExpected,
            KMemoryPermission permissionMask,
            KMemoryPermission permissionExpected,
            MemoryAttribute attributeMask,
            MemoryAttribute attributeExpected,
            MemoryAttribute attributeIgnoreMask,
            out MemoryState outState,
            out KMemoryPermission outPermission,
            out MemoryAttribute outAttribute)
        {
            ulong endAddr = address + size;

            KMemoryBlock currBlock = _blockManager.FindBlock(address);

            KMemoryInfo info = currBlock.GetInfo();

            MemoryState firstState = info.State;
            KMemoryPermission firstPermission = info.Permission;
            MemoryAttribute firstAttribute = info.Attribute;

            do
            {
                info = currBlock.GetInfo();

                // Check if the block state matches what we expect.
                if (firstState != info.State ||
                     firstPermission != info.Permission ||
                    (info.Attribute & attributeMask) != attributeExpected ||
                    (firstAttribute | attributeIgnoreMask) != (info.Attribute | attributeIgnoreMask) ||
                    (firstState & stateMask) != stateExpected ||
                    (firstPermission & permissionMask) != permissionExpected)
                {
                    outState = MemoryState.Unmapped;
                    outPermission = KMemoryPermission.None;
                    outAttribute = MemoryAttribute.None;

                    return false;
                }
            }
            while (info.Address + info.Size - 1 < endAddr - 1 && (currBlock = currBlock.Successor) != null);

            outState = firstState;
            outPermission = firstPermission;
            outAttribute = firstAttribute & ~attributeIgnoreMask;

            return true;
        }

        private bool CheckRange(
            ulong address,
            ulong size,
            MemoryState stateMask,
            MemoryState stateExpected,
            KMemoryPermission permissionMask,
            KMemoryPermission permissionExpected,
            MemoryAttribute attributeMask,
            MemoryAttribute attributeExpected)
        {
            foreach (KMemoryInfo info in IterateOverRange(address, address + size))
            {
                // Check if the block state matches what we expect.
                if ((info.State & stateMask) != stateExpected ||
                    (info.Permission & permissionMask) != permissionExpected ||
                    (info.Attribute & attributeMask) != attributeExpected)
                {
                    return false;
                }
            }

            return true;
        }

        private IEnumerable<KMemoryInfo> IterateOverRange(ulong start, ulong end)
        {
            KMemoryBlock currBlock = _blockManager.FindBlock(start);

            KMemoryInfo info;

            do
            {
                info = currBlock.GetInfo();

                yield return info;
            }
            while (info.Address + info.Size - 1 < end - 1 && (currBlock = currBlock.Successor) != null);
        }

        private ulong AllocateVa(ulong regionStart, ulong regionPagesCount, ulong neededPagesCount, int alignment)
        {
            ulong address = 0;

            ulong regionEndAddr = regionStart + regionPagesCount * PageSize;

            ulong reservedPagesCount = _isKernel ? 1UL : 4UL;

            if (_aslrEnabled)
            {
                ulong totalNeededSize = (reservedPagesCount + neededPagesCount) * PageSize;

                ulong remainingPages = regionPagesCount - neededPagesCount;

                ulong aslrMaxOffset = ((remainingPages + reservedPagesCount) * PageSize) / (ulong)alignment;

                for (int attempt = 0; attempt < 8; attempt++)
                {
                    ulong aslrAddress = BitUtils.AlignDown(regionStart + GetRandomValue(0, aslrMaxOffset) * (ulong)alignment, (ulong)alignment);
                    ulong aslrEndAddr = aslrAddress + totalNeededSize;

                    KMemoryInfo info = _blockManager.FindBlock(aslrAddress).GetInfo();

                    if (info.State != MemoryState.Unmapped)
                    {
                        continue;
                    }

                    ulong currBaseAddr = info.Address + reservedPagesCount * PageSize;
                    ulong currEndAddr = info.Address + info.Size;

                    if (aslrAddress >= regionStart &&
                        aslrAddress >= currBaseAddr &&
                        aslrEndAddr - 1 <= regionEndAddr - 1 &&
                        aslrEndAddr - 1 <= currEndAddr - 1)
                    {
                        address = aslrAddress;
                        break;
                    }
                }

                if (address == 0)
                {
                    ulong aslrPage = GetRandomValue(0, aslrMaxOffset);

                    address = FindFirstFit(
                        regionStart + aslrPage * PageSize,
                        regionPagesCount - aslrPage,
                        neededPagesCount,
                        alignment,
                        0,
                        reservedPagesCount);
                }
            }

            if (address == 0)
            {
                address = FindFirstFit(
                    regionStart,
                    regionPagesCount,
                    neededPagesCount,
                    alignment,
                    0,
                    reservedPagesCount);
            }

            return address;
        }

        private ulong FindFirstFit(
            ulong regionStart,
            ulong regionPagesCount,
            ulong neededPagesCount,
            int alignment,
            ulong reservedStart,
            ulong reservedPagesCount)
        {
            ulong reservedSize = reservedPagesCount * PageSize;

            ulong totalNeededSize = reservedSize + neededPagesCount * PageSize;

            ulong regionEndAddr = (regionStart + regionPagesCount * PageSize) - 1;

            KMemoryBlock currBlock = _blockManager.FindBlock(regionStart);

            KMemoryInfo info = currBlock.GetInfo();

            while (regionEndAddr >= info.Address)
            {
                if (info.State == MemoryState.Unmapped)
                {
                    ulong currBaseAddr = info.Address <= regionStart ? regionStart : info.Address;
                    ulong currEndAddr = info.Address + info.Size - 1;

                    currBaseAddr += reservedSize;

                    ulong address = BitUtils.AlignDown<ulong>(currBaseAddr, (ulong)alignment) + reservedStart;

                    if (currBaseAddr > address)
                    {
                        address += (ulong)alignment;
                    }

                    ulong allocationEndAddr = address + totalNeededSize - 1;

                    if (info.Address <= address &&
                        address < allocationEndAddr &&
                        allocationEndAddr <= regionEndAddr &&
                        allocationEndAddr <= currEndAddr)
                    {
                        return address;
                    }
                }

                currBlock = currBlock.Successor;

                if (currBlock == null)
                {
                    break;
                }

                info = currBlock.GetInfo();
            }

            return 0;
        }

        public bool CanContain(ulong address, ulong size, MemoryState state)
        {
            ulong endAddr = address + size;

            ulong regionBaseAddr = GetBaseAddress(state);
            ulong regionEndAddr = regionBaseAddr + GetSize(state);

            bool InsideRegion()
            {
                return regionBaseAddr <= address &&
                       endAddr > address &&
                       endAddr - 1 <= regionEndAddr - 1;
            }

            bool OutsideHeapRegion()
            {
                return endAddr <= HeapRegionStart || address >= HeapRegionEnd;
            }

            bool OutsideAliasRegion()
            {
                return endAddr <= AliasRegionStart || address >= AliasRegionEnd;
            }

            switch (state)
            {
                case MemoryState.Io:
                case MemoryState.Normal:
                case MemoryState.CodeStatic:
                case MemoryState.CodeMutable:
                case MemoryState.SharedMemory:
                case MemoryState.ModCodeStatic:
                case MemoryState.ModCodeMutable:
                case MemoryState.Stack:
                case MemoryState.ThreadLocal:
                case MemoryState.TransferMemoryIsolated:
                case MemoryState.TransferMemory:
                case MemoryState.ProcessMemory:
                case MemoryState.CodeReadOnly:
                case MemoryState.CodeWritable:
                    return InsideRegion() && OutsideHeapRegion() && OutsideAliasRegion();

                case MemoryState.Heap:
                    return InsideRegion() && OutsideAliasRegion();

                case MemoryState.IpcBuffer0:
                case MemoryState.IpcBuffer1:
                case MemoryState.IpcBuffer3:
                    return InsideRegion() && OutsideHeapRegion();

                case MemoryState.KernelStack:
                    return InsideRegion();
            }

            throw new ArgumentException($"Invalid state value \"{state}\".");
        }

        private ulong GetBaseAddress(MemoryState state)
        {
            switch (state)
            {
                case MemoryState.Io:
                case MemoryState.Normal:
                case MemoryState.ThreadLocal:
                    return TlsIoRegionStart;

                case MemoryState.CodeStatic:
                case MemoryState.CodeMutable:
                case MemoryState.SharedMemory:
                case MemoryState.ModCodeStatic:
                case MemoryState.ModCodeMutable:
                case MemoryState.TransferMemoryIsolated:
                case MemoryState.TransferMemory:
                case MemoryState.ProcessMemory:
                case MemoryState.CodeReadOnly:
                case MemoryState.CodeWritable:
                    return GetAddrSpaceBaseAddr();

                case MemoryState.Heap:
                    return HeapRegionStart;

                case MemoryState.IpcBuffer0:
                case MemoryState.IpcBuffer1:
                case MemoryState.IpcBuffer3:
                    return AliasRegionStart;

                case MemoryState.Stack:
                    return StackRegionStart;

                case MemoryState.KernelStack:
                    return AddrSpaceStart;
            }

            throw new ArgumentException($"Invalid state value \"{state}\".");
        }

        private ulong GetSize(MemoryState state)
        {
            switch (state)
            {
                case MemoryState.Io:
                case MemoryState.Normal:
                case MemoryState.ThreadLocal:
                    return TlsIoRegionEnd - TlsIoRegionStart;

                case MemoryState.CodeStatic:
                case MemoryState.CodeMutable:
                case MemoryState.SharedMemory:
                case MemoryState.ModCodeStatic:
                case MemoryState.ModCodeMutable:
                case MemoryState.TransferMemoryIsolated:
                case MemoryState.TransferMemory:
                case MemoryState.ProcessMemory:
                case MemoryState.CodeReadOnly:
                case MemoryState.CodeWritable:
                    return GetAddrSpaceSize();

                case MemoryState.Heap:
                    return HeapRegionEnd - HeapRegionStart;

                case MemoryState.IpcBuffer0:
                case MemoryState.IpcBuffer1:
                case MemoryState.IpcBuffer3:
                    return AliasRegionEnd - AliasRegionStart;

                case MemoryState.Stack:
                    return StackRegionEnd - StackRegionStart;

                case MemoryState.KernelStack:
                    return AddrSpaceEnd - AddrSpaceStart;
            }

            throw new ArgumentException($"Invalid state value \"{state}\".");
        }

        public ulong GetAddrSpaceBaseAddr()
        {
            return AslrRegionStart;
        }

        public ulong GetAddrSpaceSize()
        {
            return AslrRegionEnd - AslrRegionStart;
        }

        private static ulong GetDramAddressFromPa(ulong pa)
        {
            return pa - DramMemoryMap.DramBase;
        }

        protected KMemoryRegionManager GetMemoryRegionManager()
        {
            return Context.MemoryManager.MemoryRegions[(int)_memRegion];
        }

        public ulong GetMmUsedPages()
        {
            lock (_blockManager)
            {
                return BitUtils.DivRoundUp<ulong>(GetMmUsedSize(), PageSize);
            }
        }

        private ulong GetMmUsedSize()
        {
            return (ulong)(_blockManager.BlocksCount * KMemoryBlockSize);
        }

        public bool IsInvalidRegion(ulong address, ulong size)
        {
            return address + size - 1 > GetAddrSpaceBaseAddr() + GetAddrSpaceSize() - 1;
        }

        public bool InsideAddrSpace(ulong address, ulong size)
        {
            return AddrSpaceStart <= address && address + size - 1 <= AddrSpaceEnd - 1;
        }

        public bool InsideAliasRegion(ulong address, ulong size)
        {
            return address + size > AliasRegionStart && AliasRegionEnd > address;
        }

        public bool InsideHeapRegion(ulong address, ulong size)
        {
            return address + size > HeapRegionStart && HeapRegionEnd > address;
        }

        public bool InsideStackRegion(ulong address, ulong size)
        {
            return address + size > StackRegionStart && StackRegionEnd > address;
        }

        public bool OutsideAliasRegion(ulong address, ulong size)
        {
            return AliasRegionStart > address || address + size - 1 > AliasRegionEnd - 1;
        }

        public bool OutsideAddrSpace(ulong address, ulong size)
        {
            return AddrSpaceStart > address || address + size - 1 > AddrSpaceEnd - 1;
        }

        public bool OutsideStackRegion(ulong address, ulong size)
        {
            return StackRegionStart > address || address + size - 1 > StackRegionEnd - 1;
        }

        /// <summary>
        /// Gets the host regions that make up the given virtual address region.
        /// If any part of the virtual region is unmapped, null is returned.
        /// </summary>
        /// <param name="va">Virtual address of the range</param>
        /// <param name="size">Size of the range</param>
        /// <returns>The host regions</returns>
        /// <exception cref="Ryujinx.Memory.InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
        protected abstract IEnumerable<HostMemoryRange> GetHostRegions(ulong va, ulong size);

        /// <summary>
        /// Gets the physical regions that make up the given virtual address region.
        /// If any part of the virtual region is unmapped, null is returned.
        /// </summary>
        /// <param name="va">Virtual address of the range</param>
        /// <param name="size">Size of the range</param>
        /// <param name="pageList">Page list where the ranges will be added</param>
        protected abstract void GetPhysicalRegions(ulong va, ulong size, KPageList pageList);

        /// <summary>
        /// Gets a read-only span of data from CPU mapped memory.
        /// </summary>
        /// <remarks>
        /// This may perform a allocation if the data is not contiguous in memory.
        /// For this reason, the span is read-only, you can't modify the data.
        /// </remarks>
        /// <param name="va">Virtual address of the data</param>
        /// <param name="size">Size of the data</param>
        /// <param name="tracked">True if read tracking is triggered on the span</param>
        /// <returns>A read-only span of the data</returns>
        /// <exception cref="Ryujinx.Memory.InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
        protected abstract ReadOnlySpan<byte> GetSpan(ulong va, int size);

        /// <summary>
        /// Maps a new memory region with the contents of a existing memory region.
        /// </summary>
        /// <param name="src">Source memory region where the data will be taken from</param>
        /// <param name="dst">Destination memory region to map</param>
        /// <param name="pagesCount">Number of pages to map</param>
        /// <param name="oldSrcPermission">Current protection of the source memory region</param>
        /// <param name="newDstPermission">Desired protection for the destination memory region</param>
        /// <returns>Result of the mapping operation</returns>
        protected abstract Result MapMemory(ulong src, ulong dst, ulong pagesCount, KMemoryPermission oldSrcPermission, KMemoryPermission newDstPermission);

        /// <summary>
        /// Unmaps a region of memory that was previously mapped with <see cref="MapMemory"/>.
        /// </summary>
        /// <param name="dst">Destination memory region to be unmapped</param>
        /// <param name="src">Source memory region that was originally remapped</param>
        /// <param name="pagesCount">Number of pages to unmap</param>
        /// <param name="oldDstPermission">Current protection of the destination memory region</param>
        /// <param name="newSrcPermission">Desired protection of the source memory region</param>
        /// <returns>Result of the unmapping operation</returns>
        protected abstract Result UnmapMemory(ulong dst, ulong src, ulong pagesCount, KMemoryPermission oldDstPermission, KMemoryPermission newSrcPermission);

        /// <summary>
        /// Maps a region of memory into the specified physical memory region.
        /// </summary>
        /// <param name="dstVa">Destination virtual address that should be mapped</param>
        /// <param name="pagesCount">Number of pages to map</param>
        /// <param name="srcPa">Physical address where the pages should be mapped. May be ignored if aliasing is not supported</param>
        /// <param name="permission">Permission of the region to be mapped</param>
        /// <param name="flags">Flags controlling the memory map operation</param>
        /// <param name="shouldFillPages">Indicate if the pages should be filled with the <paramref name="fillValue"/> value</param>
        /// <param name="fillValue">The value used to fill pages when <paramref name="shouldFillPages"/> is set to true</param>
        /// <returns>Result of the mapping operation</returns>
        protected abstract Result MapPages(
            ulong dstVa,
            ulong pagesCount,
            ulong srcPa,
            KMemoryPermission permission,
            MemoryMapFlags flags,
            bool shouldFillPages = false,
            byte fillValue = 0);

        /// <summary>
        /// Maps a region of memory into the specified physical memory region.
        /// </summary>
        /// <param name="address">Destination virtual address that should be mapped</param>
        /// <param name="pageList">List of physical memory pages where the pages should be mapped. May be ignored if aliasing is not supported</param>
        /// <param name="permission">Permission of the region to be mapped</param>
        /// <param name="flags">Flags controlling the memory map operation</param>
        /// <param name="shouldFillPages">Indicate if the pages should be filled with the <paramref name="fillValue"/> value</param>
        /// <param name="fillValue">The value used to fill pages when <paramref name="shouldFillPages"/> is set to true</param>
        /// <returns>Result of the mapping operation</returns>
        protected abstract Result MapPages(
            ulong address,
            KPageList pageList,
            KMemoryPermission permission,
            MemoryMapFlags flags,
            bool shouldFillPages = false,
            byte fillValue = 0);

        /// <summary>
        /// Maps pages into an arbitrary host memory location.
        /// </summary>
        /// <param name="regions">Host regions to be mapped into the specified virtual memory region</param>
        /// <param name="va">Destination virtual address of the range on this page table</param>
        /// <param name="size">Size of the range</param>
        /// <returns>Result of the mapping operation</returns>
        protected abstract Result MapForeign(IEnumerable<HostMemoryRange> regions, ulong va, ulong size);

        /// <summary>
        /// Unmaps a region of memory that was previously mapped with one of the page mapping methods.
        /// </summary>
        /// <param name="address">Virtual address of the region to unmap</param>
        /// <param name="pagesCount">Number of pages to unmap</param>
        /// <returns>Result of the unmapping operation</returns>
        protected abstract Result Unmap(ulong address, ulong pagesCount);

        /// <summary>
        /// Changes the permissions of a given virtual memory region.
        /// </summary>
        /// <param name="address">Virtual address of the region to have the permission changes</param>
        /// <param name="pagesCount">Number of pages to have their permissions changed</param>
        /// <param name="permission">New permission</param>
        /// <returns>Result of the permission change operation</returns>
        protected abstract Result Reprotect(ulong address, ulong pagesCount, KMemoryPermission permission);

        /// <summary>
        /// Changes the permissions of a given virtual memory region.
        /// </summary>
        /// <param name="address">Virtual address of the region to have the permission changes</param>
        /// <param name="pagesCount">Number of pages to have their permissions changed</param>
        /// <param name="permission">New permission</param>
        /// <returns>Result of the permission change operation</returns>
        protected abstract Result ReprotectWithAttributes(ulong address, ulong pagesCount, KMemoryPermission permission);

        /// <summary>
        /// Alerts the memory tracking that a given region has been read from or written to.
        /// This should be called before read/write is performed.
        /// </summary>
        /// <param name="va">Virtual address of the region</param>
        /// <param name="size">Size of the region</param>
        protected abstract void SignalMemoryTracking(ulong va, ulong size, bool write);

        /// <summary>
        /// Writes data to CPU mapped memory, with write tracking.
        /// </summary>
        /// <param name="va">Virtual address to write the data into</param>
        /// <param name="data">Data to be written</param>
        /// <exception cref="Ryujinx.Memory.InvalidMemoryRegionException">Throw for unhandled invalid or unmapped memory accesses</exception>
        protected abstract void Write(ulong va, ReadOnlySpan<byte> data);
    }
}