aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/ytalloc/impl/core-inl.h
blob: 64e95188f407b2934221fb78839f8e40a6e0bd05 (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
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
#pragma once

// This file contains the core parts of YTAlloc but no malloc/free-bridge.
// The latter bridge is placed into alloc.cpp, which includes (sic!) core-inl.h.
// This ensures that AllocateInline/FreeInline calls are properly inlined into malloc/free.
// Also core-inl.h can be directly included in, e.g., benchmarks.

#include <library/cpp/yt/containers/intrusive_linked_list.h>

#include <library/cpp/yt/memory/memory_tag.h>

#include <library/cpp/yt/threading/at_fork.h>
#include <library/cpp/yt/threading/fork_aware_spin_lock.h>

#include <library/cpp/yt/memory/free_list.h>

#include <util/system/tls.h>
#include <util/system/align.h>
#include <util/system/thread.h>

#include <util/string/printf.h>

#include <util/generic/singleton.h>
#include <util/generic/size_literals.h>
#include <util/generic/utility.h>

#include <util/digest/numeric.h>

#include <library/cpp/ytalloc/api/ytalloc.h>

#include <atomic>
#include <array>
#include <vector>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <cstdio>
#include <optional>

#include <sys/mman.h>

#ifdef _linux_
    #include <sys/utsname.h>
#endif

#include <errno.h>
#include <pthread.h>
#include <time.h>

#ifndef MAP_POPULATE
    #define MAP_POPULATE 0x08000
#endif

// MAP_FIXED which doesn't unmap underlying mapping.
// Linux kernels older than 4.17 silently ignore this flag.
#ifndef MAP_FIXED_NOREPLACE
    #ifdef _linux_
        #define MAP_FIXED_NOREPLACE 0x100000
    #else
        #define MAP_FIXED_NOREPLACE 0
    #endif
#endif

#ifndef MADV_POPULATE
    #define MADV_POPULATE 0x59410003
#endif

#ifndef MADV_STOCKPILE
    #define MADV_STOCKPILE 0x59410004
#endif

#ifndef MADV_FREE
    #define MADV_FREE 8
#endif

#ifndef MADV_DONTDUMP
    #define MADV_DONTDUMP 16
#endif

#ifndef NDEBUG
    #define YTALLOC_PARANOID
#endif

#ifdef YTALLOC_PARANOID
    #define YTALLOC_NERVOUS
#endif

#define YTALLOC_VERIFY(condition)                                                             \
    do {                                                                                      \
        if (Y_UNLIKELY(!(condition))) {                                                       \
            ::NYT::NYTAlloc::AssertTrap("Assertion failed: " #condition, __FILE__, __LINE__); \
        }                                                                                     \
    } while (false)

#ifdef NDEBUG
    #define YTALLOC_ASSERT(condition) YTALLOC_VERIFY(condition)
#else
    #define YTALLOC_ASSERT(condition) (void)(0)
#endif

#ifdef YTALLOC_PARANOID
    #define YTALLOC_PARANOID_ASSERT(condition) YTALLOC_VERIFY(condition)
#else
    #define YTALLOC_PARANOID_ASSERT(condition) (true || (condition))
#endif

#define YTALLOC_TRAP(message) ::NYT::NYTAlloc::AssertTrap(message, __FILE__, __LINE__)

namespace NYT::NYTAlloc {

////////////////////////////////////////////////////////////////////////////////
// Allocations are classified into three types:
//
// a) Small chunks (less than LargeAllocationSizeThreshold)
// These are the fastest and are extensively cached (both per-thread and globally).
// Memory claimed for these allocations is never reclaimed back.
// Code dealing with such allocations is heavy optimized with all hot paths
// as streamlined as possible. The implementation is mostly inspired by LFAlloc.
//
// b) Large blobs (from LargeAllocationSizeThreshold to HugeAllocationSizeThreshold)
// These are cached as well. We expect such allocations to be less frequent
// than small ones but still do our best to provide good scalability.
// In particular, thread-sharded concurrent data structures as used to provide access to
// cached blobs. Memory is claimed via madvise(MADV_POPULATE) and reclaimed back
// via madvise(MADV_FREE).
//
// c) Huge blobs (from HugeAllocationSizeThreshold)
// These should be rare; we delegate directly to mmap and munmap for each allocation.
//
// We also provide a separate allocator for all system allocations (that are needed by YTAlloc itself).
// These are rare and also delegate to mmap/unmap.

// Periods between background activities.
constexpr auto BackgroundInterval = TDuration::Seconds(1);

static_assert(LargeRankCount - MinLargeRank <= 16, "Too many large ranks");
static_assert(SmallRankCount <= 32, "Too many small ranks");

constexpr size_t SmallZoneSize = 1_TB;
constexpr size_t LargeZoneSize = 16_TB;
constexpr size_t HugeZoneSize = 1_TB;
constexpr size_t SystemZoneSize = 1_TB;

constexpr size_t MaxCachedChunksPerRank = 256;

constexpr uintptr_t UntaggedSmallZonesStart = 0;
constexpr uintptr_t UntaggedSmallZonesEnd = UntaggedSmallZonesStart + 32 * SmallZoneSize;
constexpr uintptr_t MinUntaggedSmallPtr = UntaggedSmallZonesStart + SmallZoneSize * 1;
constexpr uintptr_t MaxUntaggedSmallPtr = UntaggedSmallZonesStart + SmallZoneSize * SmallRankCount;

constexpr uintptr_t TaggedSmallZonesStart = UntaggedSmallZonesEnd;
constexpr uintptr_t TaggedSmallZonesEnd = TaggedSmallZonesStart + 32 * SmallZoneSize;
constexpr uintptr_t MinTaggedSmallPtr = TaggedSmallZonesStart + SmallZoneSize * 1;
constexpr uintptr_t MaxTaggedSmallPtr = TaggedSmallZonesStart + SmallZoneSize * SmallRankCount;

constexpr uintptr_t DumpableLargeZoneStart = TaggedSmallZonesEnd;
constexpr uintptr_t DumpableLargeZoneEnd = DumpableLargeZoneStart + LargeZoneSize;

constexpr uintptr_t UndumpableLargeZoneStart = DumpableLargeZoneEnd;
constexpr uintptr_t UndumpableLargeZoneEnd = UndumpableLargeZoneStart + LargeZoneSize;

constexpr uintptr_t LargeZoneStart(bool dumpable)
{
    return dumpable ? DumpableLargeZoneStart : UndumpableLargeZoneStart;
}
constexpr uintptr_t LargeZoneEnd(bool dumpable)
{
    return dumpable ? DumpableLargeZoneEnd : UndumpableLargeZoneEnd;
}

constexpr uintptr_t HugeZoneStart = UndumpableLargeZoneEnd;
constexpr uintptr_t HugeZoneEnd = HugeZoneStart + HugeZoneSize;

constexpr uintptr_t SystemZoneStart = HugeZoneEnd;
constexpr uintptr_t SystemZoneEnd = SystemZoneStart + SystemZoneSize;

// We leave 64_KB at the end of 256_MB block and never use it.
// That serves two purposes:
//   1. SmallExtentSize % SmallSegmentSize == 0
//   2. Every small object satisfies RightReadableArea requirement.
constexpr size_t SmallExtentAllocSize = 256_MB;
constexpr size_t SmallExtentSize = SmallExtentAllocSize - 64_KB;
constexpr size_t SmallSegmentSize = 96_KB; // LCM(SmallRankToSize)

constexpr ui16 SmallRankBatchSize[SmallRankCount] = {
    0, 256, 256, 256, 256, 256, 256, 256, 256, 256, 192, 128, 96, 64, 48, 32, 24, 16, 12, 8, 6, 4, 3
};

constexpr bool CheckSmallSizes()
{
    for (size_t rank = 0; rank < SmallRankCount; rank++) {
        auto size = SmallRankToSize[rank];
        if (size == 0) {
            continue;
        }

        if (SmallSegmentSize % size != 0) {
            return false;
        }

        if (SmallRankBatchSize[rank] > MaxCachedChunksPerRank) {
            return false;
        }
    }

    return true;
}

static_assert(CheckSmallSizes());
static_assert(SmallExtentSize % SmallSegmentSize == 0);
static_assert(SmallSegmentSize % PageSize == 0);

constexpr size_t LargeExtentSize = 1_GB;
static_assert(LargeExtentSize >= LargeAllocationSizeThreshold, "LargeExtentSize < LargeAllocationSizeThreshold");

constexpr const char* BackgroundThreadName = "YTAllocBack";
constexpr const char* StockpileThreadName = "YTAllocStock";

DEFINE_ENUM(EAllocationKind,
    (Untagged)
    (Tagged)
);

// Forward declarations.
struct TThreadState;
struct TLargeArena;
struct TLargeBlobExtent;

////////////////////////////////////////////////////////////////////////////////
// Traps and assertions

[[noreturn]]
void OomTrap()
{
    _exit(9);
}

[[noreturn]]
void AssertTrap(const char* message, const char* file, int line)
{
    ::fprintf(stderr, "*** YTAlloc has detected an internal trap at %s:%d\n*** %s\n",
        file,
        line,
        message);
    __builtin_trap();
}

template <class T, class E>
void AssertBlobState(T* header, E expectedState)
{
    auto actualState = header->State;
    if (Y_UNLIKELY(actualState != expectedState)) {
        char message[256];
        sprintf(message, "Invalid blob header state at %p: expected %" PRIx64 ", actual %" PRIx64,
            header,
            static_cast<ui64>(expectedState),
            static_cast<ui64>(actualState));
        YTALLOC_TRAP(message);
    }
}

////////////////////////////////////////////////////////////////////////////////

// Provides a never-dying singleton with explicit construction.
template <class T>
class TExplicitlyConstructableSingleton
{
public:
    TExplicitlyConstructableSingleton()
    { }

    ~TExplicitlyConstructableSingleton()
    { }

    template <class... Ts>
    void Construct(Ts&&... args)
    {
        new (&Storage_) T(std::forward<Ts>(args)...);
#ifndef NDEBUG
        Constructed_ = true;
#endif
    }

    Y_FORCE_INLINE T* Get()
    {
#ifndef NDEBUG
        YTALLOC_PARANOID_ASSERT(Constructed_);
#endif
        return &Storage_;
    }

    Y_FORCE_INLINE const T* Get() const
    {
#ifndef NDEBUG
        YTALLOC_PARANOID_ASSERT(Constructed_);
#endif
        return &Storage_;
    }

    Y_FORCE_INLINE T* operator->()
    {
        return Get();
    }

    Y_FORCE_INLINE const T* operator->() const
    {
        return Get();
    }

    Y_FORCE_INLINE T& operator*()
    {
        return *Get();
    }

    Y_FORCE_INLINE const T& operator*() const
    {
        return *Get();
    }

private:
    union {
        T Storage_;
    };

#ifndef NDEBUG
    bool Constructed_;
#endif
};

////////////////////////////////////////////////////////////////////////////////

// Initializes all singletons.
// Safe to call multiple times.
// Guaranteed to not allocate.
void InitializeGlobals();

// Spawns the background thread, if it's time.
// Safe to call multiple times.
// Must be called on allocation slow path.
void StartBackgroundThread();

////////////////////////////////////////////////////////////////////////////////

class TLogManager
{
public:
    // Sets the handler to be invoked for each log event produced by YTAlloc.
    void EnableLogging(TLogHandler logHandler)
    {
        LogHandler_.store(logHandler);
    }

    // Checks (in a racy way) that logging is enabled.
    bool IsLoggingEnabled()
    {
        return LogHandler_.load() != nullptr;
    }

    // Logs the message via log handler (if any).
    template <class... Ts>
    void LogMessage(ELogEventSeverity severity, const char* format, Ts&&... args)
    {
        auto logHandler = LogHandler_.load();
        if (!logHandler) {
            return;
        }

        std::array<char, 16_KB> buffer;
        auto len = ::snprintf(buffer.data(), buffer.size(), format, std::forward<Ts>(args)...);

        TLogEvent event;
        event.Severity = severity;
        event.Message = TStringBuf(buffer.data(), len);
        logHandler(event);
    }

    // A special case of zero args.
    void LogMessage(ELogEventSeverity severity, const char* message)
    {
        LogMessage(severity, "%s", message);
    }

private:
    std::atomic<TLogHandler> LogHandler_= nullptr;

};

TExplicitlyConstructableSingleton<TLogManager> LogManager;

#define YTALLOC_LOG_EVENT(...)   LogManager->LogMessage(__VA_ARGS__)
#define YTALLOC_LOG_DEBUG(...)   YTALLOC_LOG_EVENT(ELogEventSeverity::Debug, __VA_ARGS__)
#define YTALLOC_LOG_INFO(...)    YTALLOC_LOG_EVENT(ELogEventSeverity::Info, __VA_ARGS__)
#define YTALLOC_LOG_WARNING(...) YTALLOC_LOG_EVENT(ELogEventSeverity::Warning, __VA_ARGS__)
#define YTALLOC_LOG_ERROR(...)   YTALLOC_LOG_EVENT(ELogEventSeverity::Error, __VA_ARGS__)

////////////////////////////////////////////////////////////////////////////////

Y_FORCE_INLINE size_t GetUsed(ssize_t allocated, ssize_t freed)
{
    return allocated >= freed ? static_cast<size_t>(allocated - freed) : 0;
}

template <class T>
Y_FORCE_INLINE void* HeaderToPtr(T* header)
{
    return header + 1;
}

template <class T>
Y_FORCE_INLINE T* PtrToHeader(void* ptr)
{
    return static_cast<T*>(ptr) - 1;
}

template <class T>
Y_FORCE_INLINE const T* PtrToHeader(const void* ptr)
{
    return static_cast<const T*>(ptr) - 1;
}

Y_FORCE_INLINE size_t PtrToSmallRank(const void* ptr)
{
    return (reinterpret_cast<uintptr_t>(ptr) >> 40) & 0x1f;
}

Y_FORCE_INLINE char* AlignDownToSmallSegment(char* extent, char* ptr)
{
    auto offset = static_cast<uintptr_t>(ptr - extent);
    // NB: This modulo operation is always performed using multiplication.
    offset -= (offset % SmallSegmentSize);
    return extent + offset;
}

Y_FORCE_INLINE char* AlignUpToSmallSegment(char* extent, char* ptr)
{
    return AlignDownToSmallSegment(extent, ptr + SmallSegmentSize - 1);
}

template <class T>
static Y_FORCE_INLINE void UnalignPtr(void*& ptr)
{
    if (reinterpret_cast<uintptr_t>(ptr) % PageSize == 0) {
        reinterpret_cast<char*&>(ptr) -= PageSize - sizeof (T);
    }
    YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(ptr) % PageSize == sizeof (T));
}

template <class T>
static Y_FORCE_INLINE void UnalignPtr(const void*& ptr)
{
    if (reinterpret_cast<uintptr_t>(ptr) % PageSize == 0) {
        reinterpret_cast<const char*&>(ptr) -= PageSize - sizeof (T);
    }
    YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(ptr) % PageSize == sizeof (T));
}

template <class T>
Y_FORCE_INLINE size_t GetRawBlobSize(size_t size)
{
    return AlignUp(size + sizeof (T) + RightReadableAreaSize, PageSize);
}

template <class T>
Y_FORCE_INLINE size_t GetBlobAllocationSize(size_t size)
{
    size += sizeof(T);
    size += RightReadableAreaSize;
    size = AlignUp(size, PageSize);
    size -= sizeof(T);
    size -= RightReadableAreaSize;
    return size;
}

Y_FORCE_INLINE size_t GetLargeRank(size_t size)
{
    size_t rank = 64 - __builtin_clzl(size);
    if (size == (1ULL << (rank - 1))) {
        --rank;
    }
    return rank;
}

Y_FORCE_INLINE void PoisonRange(void* ptr, size_t size, ui32 magic)
{
#ifdef YTALLOC_PARANOID
    size = ::AlignUp<size_t>(size, 4);
    std::fill(static_cast<ui32*>(ptr), static_cast<ui32*>(ptr) + size / 4, magic);
#else
    Y_UNUSED(ptr);
    Y_UNUSED(size);
    Y_UNUSED(magic);
#endif
}

Y_FORCE_INLINE void PoisonFreedRange(void* ptr, size_t size)
{
    PoisonRange(ptr, size, 0xdeadbeef);
}

Y_FORCE_INLINE void PoisonUninitializedRange(void* ptr, size_t size)
{
    PoisonRange(ptr, size, 0xcafebabe);
}

// Checks that the header size is divisible by 16 (as needed due to alignment restrictions).
#define CHECK_HEADER_ALIGNMENT(T) static_assert(sizeof(T) % 16 == 0, "sizeof(" #T ") % 16 != 0");

////////////////////////////////////////////////////////////////////////////////

static_assert(sizeof(TFreeList<void>) == CacheLineSize, "sizeof(TFreeList) != CacheLineSize");

////////////////////////////////////////////////////////////////////////////////

constexpr size_t ShardCount = 16;
std::atomic<size_t> GlobalCurrentShardIndex;

// Provides a context for working with sharded data structures.
// Captures the initial shard index upon construction (indicating the shard
// where all insertions go). Maintains the current shard index (round-robin,
// indicating the shard currently used for extraction).
// Can be or be not thread-safe depending on TCounter.
template <class TCounter>
class TShardedState
{
public:
    TShardedState()
        : InitialShardIndex_(GlobalCurrentShardIndex++ % ShardCount)
        , CurrentShardIndex_(InitialShardIndex_)
    { }

    Y_FORCE_INLINE size_t GetInitialShardIndex() const
    {
        return InitialShardIndex_;
    }

    Y_FORCE_INLINE size_t GetNextShardIndex()
    {
        return ++CurrentShardIndex_ % ShardCount;
    }

private:
    const size_t InitialShardIndex_;
    TCounter CurrentShardIndex_;
};

using TLocalShardedState = TShardedState<size_t>;
using TGlobalShardedState = TShardedState<std::atomic<size_t>>;

// Implemented as a collection of free lists (each called a shard).
// One needs TShardedState to access the sharded data structure.
template <class T>
class TShardedFreeList
{
public:
    // First tries to extract an item from the initial shard;
    // if failed then proceeds to all shards in round-robin fashion.
    template <class TState>
    T* Extract(TState* state)
    {
        if (auto* item = Shards_[state->GetInitialShardIndex()].Extract()) {
            return item;
        }
        return ExtractRoundRobin(state);
    }

    // Attempts to extract an item from all shards in round-robin fashion.
    template <class TState>
    T* ExtractRoundRobin(TState* state)
    {
       for (size_t index = 0; index < ShardCount; ++index) {
            if (auto* item = Shards_[state->GetNextShardIndex()].Extract()) {
                return item;
            }
        }
        return nullptr;
    }

    // Extracts items from all shards linking them together.
    T* ExtractAll()
    {
        T* head = nullptr;
        T* tail = nullptr;
        for (auto& shard : Shards_) {
            auto* item = shard.ExtractAll();
            if (!head) {
                head = item;
            }
            if (tail) {
                YTALLOC_PARANOID_ASSERT(!tail->Next);
                tail->Next = item;
            } else {
                tail = item;
            }
            while (tail && tail->Next) {
                tail = tail->Next;
            }
        }
        return head;
    }

    template <class TState>
    void Put(TState* state, T* item)
    {
        Shards_[state->GetInitialShardIndex()].Put(item);
    }

private:
    std::array<TFreeList<T>, ShardCount> Shards_;
};

////////////////////////////////////////////////////////////////////////////////

// Holds YTAlloc control knobs.
// Thread safe.
class TConfigurationManager
{
public:
    void SetLargeUnreclaimableCoeff(double value)
    {
        LargeUnreclaimableCoeff_.store(value);
    }

    double GetLargeUnreclaimableCoeff() const
    {
        return LargeUnreclaimableCoeff_.load(std::memory_order_relaxed);
    }


    void SetMinLargeUnreclaimableBytes(size_t value)
    {
        MinLargeUnreclaimableBytes_.store(value);
    }

    void SetMaxLargeUnreclaimableBytes(size_t value)
    {
        MaxLargeUnreclaimableBytes_.store(value);
    }

    size_t GetMinLargeUnreclaimableBytes() const
    {
        return MinLargeUnreclaimableBytes_.load(std::memory_order_relaxed);
    }

    size_t GetMaxLargeUnreclaimableBytes() const
    {
        return MaxLargeUnreclaimableBytes_.load(std::memory_order_relaxed);
    }


    void SetTimingEventThreshold(TDuration value)
    {
        TimingEventThresholdNs_.store(value.MicroSeconds() * 1000);
    }

    i64 GetTimingEventThresholdNs() const
    {
        return TimingEventThresholdNs_.load(std::memory_order_relaxed);
    }


    void SetAllocationProfilingEnabled(bool value);

    bool IsAllocationProfilingEnabled() const
    {
        return AllocationProfilingEnabled_.load();
    }


    Y_FORCE_INLINE bool GetAllocationProfilingSamplingRate()
    {
        return AllocationProfilingSamplingRate_.load();
    }

    void SetAllocationProfilingSamplingRate(double rate)
    {
        if (rate < 0) {
            rate = 0;
        }
        if (rate > 1) {
            rate = 1;
        }
        i64 rateX64K = static_cast<i64>(rate * (1ULL << 16));
        AllocationProfilingSamplingRateX64K_.store(ClampVal<ui32>(rateX64K, 0, std::numeric_limits<ui16>::max() + 1));
        AllocationProfilingSamplingRate_.store(rate);
    }


    Y_FORCE_INLINE bool IsSmallArenaAllocationProfilingEnabled(size_t rank)
    {
        return SmallArenaAllocationProfilingEnabled_[rank].load(std::memory_order_relaxed);
    }

    Y_FORCE_INLINE bool IsSmallArenaAllocationProfiled(size_t rank)
    {
        return IsSmallArenaAllocationProfilingEnabled(rank) && IsAllocationSampled();
    }

    void SetSmallArenaAllocationProfilingEnabled(size_t rank, bool value)
    {
        if (rank >= SmallRankCount) {
            return;
        }
        SmallArenaAllocationProfilingEnabled_[rank].store(value);
    }


    Y_FORCE_INLINE bool IsLargeArenaAllocationProfilingEnabled(size_t rank)
    {
        return LargeArenaAllocationProfilingEnabled_[rank].load(std::memory_order_relaxed);
    }

    Y_FORCE_INLINE bool IsLargeArenaAllocationProfiled(size_t rank)
    {
        return IsLargeArenaAllocationProfilingEnabled(rank) && IsAllocationSampled();
    }

    void SetLargeArenaAllocationProfilingEnabled(size_t rank, bool value)
    {
        if (rank >= LargeRankCount) {
            return;
        }
        LargeArenaAllocationProfilingEnabled_[rank].store(value);
    }


    Y_FORCE_INLINE int GetProfilingBacktraceDepth()
    {
        return ProfilingBacktraceDepth_.load();
    }

    void SetProfilingBacktraceDepth(int depth)
    {
        if (depth < 1) {
            return;
        }
        if (depth > MaxAllocationProfilingBacktraceDepth) {
            depth = MaxAllocationProfilingBacktraceDepth;
        }
        ProfilingBacktraceDepth_.store(depth);
    }


    Y_FORCE_INLINE size_t GetMinProfilingBytesUsedToReport()
    {
        return MinProfilingBytesUsedToReport_.load();
    }

    void SetMinProfilingBytesUsedToReport(size_t size)
    {
        MinProfilingBytesUsedToReport_.store(size);
    }

    void SetEnableEagerMemoryRelease(bool value)
    {
        EnableEagerMemoryRelease_.store(value);
    }

    bool GetEnableEagerMemoryRelease()
    {
        return EnableEagerMemoryRelease_.load(std::memory_order_relaxed);
    }

    void SetEnableMadvisePopulate(bool value)
    {
        EnableMadvisePopulate_.store(value);
    }

    bool GetEnableMadvisePopulate()
    {
        return EnableMadvisePopulate_.load(std::memory_order_relaxed);
    }

    void EnableStockpile()
    {
        StockpileEnabled_.store(true);
    }

    bool IsStockpileEnabled()
    {
        return StockpileEnabled_.load();
    }

    void SetStockpileInterval(TDuration value)
    {
        StockpileInterval_.store(value);
    }

    TDuration GetStockpileInterval()
    {
        return StockpileInterval_.load();
    }

    void SetStockpileThreadCount(int count)
    {
        StockpileThreadCount_.store(count);
    }

    int GetStockpileThreadCount()
    {
        return ClampVal(StockpileThreadCount_.load(), 0, MaxStockpileThreadCount);
    }

    void SetStockpileSize(size_t value)
    {
        StockpileSize_.store(value);
    }

    size_t GetStockpileSize()
    {
        return StockpileSize_.load();
    }

private:
    std::atomic<double> LargeUnreclaimableCoeff_ = 0.05;
    std::atomic<size_t> MinLargeUnreclaimableBytes_ = 128_MB;
    std::atomic<size_t> MaxLargeUnreclaimableBytes_ = 10_GB;
    std::atomic<i64> TimingEventThresholdNs_ = 10000000; // in ns, 10 ms by default

    std::atomic<bool> AllocationProfilingEnabled_ = false;
    std::atomic<double> AllocationProfilingSamplingRate_ = 1.0;
    std::atomic<ui32> AllocationProfilingSamplingRateX64K_ = std::numeric_limits<ui32>::max();
    std::array<std::atomic<bool>, SmallRankCount> SmallArenaAllocationProfilingEnabled_ = {};
    std::array<std::atomic<bool>, LargeRankCount> LargeArenaAllocationProfilingEnabled_ = {};
    std::atomic<int> ProfilingBacktraceDepth_ = 10;
    std::atomic<size_t> MinProfilingBytesUsedToReport_ = 1_MB;

    std::atomic<bool> EnableEagerMemoryRelease_ = true;
    std::atomic<bool> EnableMadvisePopulate_ = false;

    std::atomic<bool> StockpileEnabled_ = false;
    std::atomic<TDuration> StockpileInterval_ = TDuration::MilliSeconds(10);
    static constexpr int MaxStockpileThreadCount = 8;
    std::atomic<int> StockpileThreadCount_ = 4;
    std::atomic<size_t> StockpileSize_ = 1_GB;

private:
    bool IsAllocationSampled()
    {
        Y_POD_STATIC_THREAD(ui16) Counter;
        return Counter++ < AllocationProfilingSamplingRateX64K_.load();
    }
};

TExplicitlyConstructableSingleton<TConfigurationManager> ConfigurationManager;

////////////////////////////////////////////////////////////////////////////////

template <class TEvent, class TManager>
class TEventLogManagerBase
{
public:
    void DisableForCurrentThread()
    {
        TManager::DisabledForCurrentThread_ = true;
    }

    template <class... TArgs>
    void EnqueueEvent(TArgs&&... args)
    {
        if (TManager::DisabledForCurrentThread_) {
            return;
        }

        auto timestamp = TInstant::Now();
        auto fiberId = NYTAlloc::GetCurrentFiberId();
        auto guard = Guard(EventLock_);

        auto event = TEvent(args...);
        OnEvent(event);

        if (EventCount_ >= EventBufferSize) {
            return;
        }

        auto& enqueuedEvent = Events_[EventCount_++];
        enqueuedEvent = std::move(event);
        enqueuedEvent.Timestamp = timestamp;
        enqueuedEvent.FiberId = fiberId;
    }

    void RunBackgroundTasks()
    {
        if (LogManager->IsLoggingEnabled()) {
            for (const auto& event : PullEvents()) {
                ProcessEvent(event);
            }
        }
    }

protected:
    NThreading::TForkAwareSpinLock EventLock_;

    virtual void OnEvent(const TEvent& event) = 0;

    virtual void ProcessEvent(const TEvent& event) = 0;

private:
    static constexpr size_t EventBufferSize = 1000;
    size_t EventCount_ = 0;
    std::array<TEvent, EventBufferSize> Events_;

    std::vector<TEvent> PullEvents()
    {
        std::vector<TEvent> events;
        events.reserve(EventBufferSize);

        auto guard = Guard(EventLock_);
        for (size_t index = 0; index < EventCount_; ++index) {
            events.push_back(Events_[index]);
        }
        EventCount_ = 0;
        return events;
    }
};

////////////////////////////////////////////////////////////////////////////////

struct TTimingEvent
{
    ETimingEventType Type;
    TDuration Duration;
    size_t Size;
    TInstant Timestamp;
    TFiberId FiberId;

    TTimingEvent()
    { }

    TTimingEvent(
        ETimingEventType type,
        TDuration duration,
        size_t size)
        : Type(type)
        , Duration(duration)
        , Size(size)
    { }
};

class TTimingManager
    : public TEventLogManagerBase<TTimingEvent, TTimingManager>
{
public:
    TEnumIndexedVector<ETimingEventType, TTimingEventCounters> GetTimingEventCounters()
    {
        auto guard = Guard(EventLock_);
        return EventCounters_;
    }

private:
    TEnumIndexedVector<ETimingEventType, TTimingEventCounters> EventCounters_;

    Y_POD_STATIC_THREAD(bool) DisabledForCurrentThread_;

    friend class TEventLogManagerBase<TTimingEvent, TTimingManager>;

    virtual void OnEvent(const TTimingEvent& event) override
    {
        auto& counters = EventCounters_[event.Type];
        counters.Count += 1;
        counters.Size += event.Size;
    }

    virtual void ProcessEvent(const TTimingEvent& event) override
    {
        YTALLOC_LOG_DEBUG("Timing event logged (Type: %s, Duration: %s, Size: %zu, Timestamp: %s, FiberId: %" PRIu64 ")",
            ToString(event.Type).c_str(),
            ToString(event.Duration).c_str(),
            event.Size,
            ToString(event.Timestamp).c_str(),
            event.FiberId);
    }
};

Y_POD_THREAD(bool) TTimingManager::DisabledForCurrentThread_;

TExplicitlyConstructableSingleton<TTimingManager> TimingManager;

////////////////////////////////////////////////////////////////////////////////

i64 GetElapsedNs(const struct timespec& startTime, const struct timespec& endTime)
{
    if (Y_LIKELY(startTime.tv_sec == endTime.tv_sec)) {
        return static_cast<i64>(endTime.tv_nsec) - static_cast<i64>(startTime.tv_nsec);
    }

    return
        static_cast<i64>(endTime.tv_nsec) - static_cast<i64>(startTime.tv_nsec) +
        (static_cast<i64>(endTime.tv_sec) - static_cast<i64>(startTime.tv_sec)) * 1000000000;
}

// Used to log statistics about long-running syscalls and lock acquisitions.
class TTimingGuard
    : public TNonCopyable
{
public:
    explicit TTimingGuard(ETimingEventType eventType, size_t size = 0)
        : EventType_(eventType)
        , Size_(size)
    {
        ::clock_gettime(CLOCK_MONOTONIC, &StartTime_);
    }

    ~TTimingGuard()
    {
        auto elapsedNs = GetElapsedNs();
        if (elapsedNs > ConfigurationManager->GetTimingEventThresholdNs()) {
            TimingManager->EnqueueEvent(EventType_, TDuration::MicroSeconds(elapsedNs / 1000), Size_);
        }
    }

private:
    const ETimingEventType EventType_;
    const size_t Size_;
    struct timespec StartTime_;

    i64 GetElapsedNs() const
    {
        struct timespec endTime;
        ::clock_gettime(CLOCK_MONOTONIC, &endTime);
        return NYTAlloc::GetElapsedNs(StartTime_, endTime);
    }
};

template <class T>
Y_FORCE_INLINE TGuard<T> GuardWithTiming(const T& lock)
{
    TTimingGuard timingGuard(ETimingEventType::Locking);
    TGuard<T> lockingGuard(lock);
    return lockingGuard;
}

////////////////////////////////////////////////////////////////////////////////

// A wrapper for mmap, mumap, and madvise calls.
// The latter are invoked with MADV_POPULATE (if enabled) and MADV_FREE flags
// and may fail if the OS support is missing. These failures are logged (once) and
// handled as follows:
// * if MADV_POPULATE fails then we fallback to manual per-page prefault
// for all subsequent attempts;
// * if MADV_FREE fails then it (and all subsequent attempts) is replaced with MADV_DONTNEED
// (which is non-lazy and is less efficient but will somehow do).
// Also this class mlocks all VMAs on startup to prevent pagefaults in our heavy binaries
// from disturbing latency tails.
class TMappedMemoryManager
{
public:
    void* Map(uintptr_t hint, size_t size, int flags)
    {
        TTimingGuard timingGuard(ETimingEventType::Mmap, size);
        auto* result = ::mmap(
            reinterpret_cast<void*>(hint),
            size,
            PROT_READ | PROT_WRITE,
            MAP_PRIVATE | MAP_ANONYMOUS | flags,
            -1,
            0);
        if (result == MAP_FAILED) {
            auto error = errno;
            if (error == EEXIST && (flags & MAP_FIXED_NOREPLACE)) {
                // Caller must retry with different hint address.
                return result;
            }
            YTALLOC_VERIFY(error == ENOMEM);
            ::fprintf(stderr, "*** YTAlloc has received ENOMEM error while trying to mmap %zu bytes\n",
                size);
            OomTrap();
        }
        return result;
    }

    void Unmap(void* ptr, size_t size)
    {
        TTimingGuard timingGuard(ETimingEventType::Munmap, size);
        auto result = ::munmap(ptr, size);
        YTALLOC_VERIFY(result == 0);
    }

    void DontDump(void* ptr, size_t size)
    {
        auto result = ::madvise(ptr, size, MADV_DONTDUMP);
        // Must not fail.
        YTALLOC_VERIFY(result == 0);
    }

    void PopulateFile(void* ptr, size_t size)
    {
        TTimingGuard timingGuard(ETimingEventType::FilePrefault, size);

        auto* begin = static_cast<volatile char*>(ptr);
        for (auto* current = begin; current < begin + size; current += PageSize) {
            *current;
        }
    }

    void PopulateReadOnly(void* ptr, size_t size)
    {
        if (!MadvisePopulateUnavailable_.load(std::memory_order_relaxed) &&
            ConfigurationManager->GetEnableMadvisePopulate())
        {
            if (!TryMadvisePopulate(ptr, size)) {
                MadvisePopulateUnavailable_.store(true);
            }
        }
    }

    void Populate(void* ptr, size_t size)
    {
        if (MadvisePopulateUnavailable_.load(std::memory_order_relaxed) ||
            !ConfigurationManager->GetEnableMadvisePopulate())
        {
            DoPrefault(ptr, size);
        } else if (!TryMadvisePopulate(ptr, size)) {
            MadvisePopulateUnavailable_.store(true);
            DoPrefault(ptr, size);
        }
    }

    void Release(void* ptr, size_t size)
    {
        if (CanUseMadviseFree() && !ConfigurationManager->GetEnableEagerMemoryRelease()) {
            DoMadviseFree(ptr, size);
        } else {
            DoMadviseDontNeed(ptr, size);
        }
    }

    bool Stockpile(size_t size)
    {
        if (MadviseStockpileUnavailable_.load(std::memory_order_relaxed)) {
            return false;
        }
        if (!TryMadviseStockpile(size)) {
            MadviseStockpileUnavailable_.store(true);
            return false;
        }
        return true;
    }

    void RunBackgroundTasks()
    {
        if (!LogManager->IsLoggingEnabled()) {
            return;
        }
        if (IsBuggyKernel() && !BuggyKernelLogged_) {
            YTALLOC_LOG_WARNING("Kernel is buggy; see KERNEL-118");
            BuggyKernelLogged_ = true;
        }
        if (MadviseFreeSupported_ && !MadviseFreeSupportedLogged_) {
            YTALLOC_LOG_INFO("MADV_FREE is supported");
            MadviseFreeSupportedLogged_ = true;
        }
        if (MadviseFreeNotSupported_ && !MadviseFreeNotSupportedLogged_) {
            YTALLOC_LOG_WARNING("MADV_FREE is not supported");
            MadviseFreeNotSupportedLogged_ = true;
        }
        if (MadvisePopulateUnavailable_.load() && !MadvisePopulateUnavailableLogged_) {
            YTALLOC_LOG_WARNING("MADV_POPULATE is not supported");
            MadvisePopulateUnavailableLogged_ = true;
        }
        if (MadviseStockpileUnavailable_.load() && !MadviseStockpileUnavailableLogged_) {
            YTALLOC_LOG_WARNING("MADV_STOCKPILE is not supported");
            MadviseStockpileUnavailableLogged_ = true;
        }
    }

private:
    bool BuggyKernelLogged_ = false;

    std::atomic<bool> MadviseFreeSupported_ = false;
    bool MadviseFreeSupportedLogged_ = false;

    std::atomic<bool> MadviseFreeNotSupported_ = false;
    bool MadviseFreeNotSupportedLogged_ = false;

    std::atomic<bool> MadvisePopulateUnavailable_ = false;
    bool MadvisePopulateUnavailableLogged_ = false;

    std::atomic<bool> MadviseStockpileUnavailable_ = false;
    bool MadviseStockpileUnavailableLogged_ = false;

private:
    bool TryMadvisePopulate(void* ptr, size_t size)
    {
        TTimingGuard timingGuard(ETimingEventType::MadvisePopulate, size);
        auto result = ::madvise(ptr, size, MADV_POPULATE);
        if (result != 0) {
            auto error = errno;
            YTALLOC_VERIFY(error == EINVAL || error == ENOMEM);
            if (error == ENOMEM) {
                ::fprintf(stderr, "*** YTAlloc has received ENOMEM error while trying to madvise(MADV_POPULATE) %zu bytes\n",
                    size);
                OomTrap();
            }
            return false;
        }
        return true;
    }

    void DoPrefault(void* ptr, size_t size)
    {
        TTimingGuard timingGuard(ETimingEventType::Prefault, size);
        auto* begin = static_cast<char*>(ptr);
        for (auto* current = begin; current < begin + size; current += PageSize) {
            *current = 0;
        }
    }

    bool CanUseMadviseFree()
    {
        if (MadviseFreeSupported_.load()) {
            return true;
        }
        if (MadviseFreeNotSupported_.load()) {
            return false;
        }

        if (IsBuggyKernel()) {
            MadviseFreeNotSupported_.store(true);
        } else {
            auto* ptr = Map(0, PageSize, 0);
            if (::madvise(ptr, PageSize, MADV_FREE) == 0) {
                MadviseFreeSupported_.store(true);
            } else {
                MadviseFreeNotSupported_.store(true);
            }
            Unmap(ptr, PageSize);
        }

        // Will not recurse.
        return CanUseMadviseFree();
    }

    void DoMadviseDontNeed(void* ptr, size_t size)
    {
        TTimingGuard timingGuard(ETimingEventType::MadviseDontNeed, size);
        auto result = ::madvise(ptr, size, MADV_DONTNEED);
        if (result != 0) {
            auto error = errno;
            // Failure is possible for locked pages.
            Y_ABORT_UNLESS(error == EINVAL);
        }
    }

    void DoMadviseFree(void* ptr, size_t size)
    {
        TTimingGuard timingGuard(ETimingEventType::MadviseFree, size);
        auto result = ::madvise(ptr, size, MADV_FREE);
        if (result != 0) {
            auto error = errno;
            // Failure is possible for locked pages.
            YTALLOC_VERIFY(error == EINVAL);
        }
    }

    bool TryMadviseStockpile(size_t size)
    {
        auto result = ::madvise(nullptr, size, MADV_STOCKPILE);
        if (result != 0) {
            auto error = errno;
            if (error == ENOMEM || error == EAGAIN || error == EINTR) {
                // The call is advisory, ignore ENOMEM, EAGAIN, and EINTR.
                return true;
            }
            YTALLOC_VERIFY(error == EINVAL);
            return false;
        }
        return true;
    }

    // Some kernels are known to contain bugs in MADV_FREE; see https://st.yandex-team.ru/KERNEL-118.
    bool IsBuggyKernel()
    {
#ifdef _linux_
        static const bool result = [] () {
            struct utsname buf;
            YTALLOC_VERIFY(uname(&buf) == 0);
            if (strverscmp(buf.release, "4.4.1-1") >= 0 &&
                strverscmp(buf.release, "4.4.96-44") < 0)
            {
                return true;
            }
            if (strverscmp(buf.release, "4.14.1-1") >= 0 &&
                strverscmp(buf.release, "4.14.79-33") < 0)
            {
                return true;
            }
            return false;
        }();
        return result;
#else
        return false;
#endif
    }
};

TExplicitlyConstructableSingleton<TMappedMemoryManager> MappedMemoryManager;

////////////////////////////////////////////////////////////////////////////////
// System allocator

// Each system allocation is prepended with such a header.
struct TSystemBlobHeader
{
    explicit TSystemBlobHeader(size_t size)
        : Size(size)
    { }

    size_t Size;
    char Padding[8];
};

CHECK_HEADER_ALIGNMENT(TSystemBlobHeader)

// Used for some internal allocations.
// Delgates directly to TMappedMemoryManager.
class TSystemAllocator
{
public:
    void* Allocate(size_t size);
    void Free(void* ptr);

private:
    std::atomic<uintptr_t> CurrentPtr_ = SystemZoneStart;
};

TExplicitlyConstructableSingleton<TSystemAllocator> SystemAllocator;

////////////////////////////////////////////////////////////////////////////////

// Deriving from this class makes instances bound to TSystemAllocator.
struct TSystemAllocatable
{
    void* operator new(size_t size) noexcept
    {
        return SystemAllocator->Allocate(size);
    }

    void* operator new[](size_t size) noexcept
    {
        return SystemAllocator->Allocate(size);
    }

    void operator delete(void* ptr) noexcept
    {
        SystemAllocator->Free(ptr);
    }

    void operator delete[](void* ptr) noexcept
    {
        SystemAllocator->Free(ptr);
    }
};

////////////////////////////////////////////////////////////////////////////////

// Maintains a pool of objects.
// Objects are allocated in groups each containing BatchSize instances.
// The actual allocation is carried out by TSystemAllocator.
// Memory is never actually reclaimed; freed instances are put into TFreeList.
template <class T, size_t BatchSize>
class TSystemPool
{
public:
    T* Allocate()
    {
        while (true) {
            auto* obj = FreeList_.Extract();
            if (Y_LIKELY(obj)) {
                new (obj) T();
                return obj;
            }
            AllocateMore();
        }
    }

    void Free(T* obj)
    {
        obj->T::~T();
        PoisonFreedRange(obj, sizeof(T));
        FreeList_.Put(obj);
    }

private:
    TFreeList<T> FreeList_;

private:
    void AllocateMore()
    {
        auto* objs = static_cast<T*>(SystemAllocator->Allocate(sizeof(T) * BatchSize));
        for (size_t index = 0; index < BatchSize; ++index) {
            auto* obj = objs + index;
            FreeList_.Put(obj);
        }
    }
};

// A sharded analogue TSystemPool.
template <class T, size_t BatchSize>
class TShardedSystemPool
{
public:
    template <class TState>
    T* Allocate(TState* state)
    {
        if (auto* obj = FreeLists_[state->GetInitialShardIndex()].Extract()) {
            new (obj) T();
            return obj;
        }

        while (true) {
            for (size_t index = 0; index < ShardCount; ++index) {
                if (auto* obj = FreeLists_[state->GetNextShardIndex()].Extract()) {
                    new (obj) T();
                    return obj;
                }
            }
            AllocateMore();
        }
    }

    template <class TState>
    void Free(TState* state, T* obj)
    {
        obj->T::~T();
        PoisonFreedRange(obj, sizeof(T));
        FreeLists_[state->GetInitialShardIndex()].Put(obj);
    }

private:
    std::array<TFreeList<T>, ShardCount> FreeLists_;

private:
    void AllocateMore()
    {
        auto* objs = static_cast<T*>(SystemAllocator->Allocate(sizeof(T) * BatchSize));
        for (size_t index = 0; index < BatchSize; ++index) {
            auto* obj = objs + index;
            FreeLists_[index % ShardCount].Put(obj);
        }
    }
};

////////////////////////////////////////////////////////////////////////////////

// Handles allocations inside a zone of memory given by its start and end pointers.
// Each allocation is a separate mapped region of memory.
// A special care is taken to guarantee that all allocated regions fall inside the zone.
class TZoneAllocator
{
public:
    TZoneAllocator(uintptr_t zoneStart, uintptr_t zoneEnd)
        : ZoneStart_(zoneStart)
        , ZoneEnd_(zoneEnd)
        , Current_(zoneStart)
    {
        YTALLOC_VERIFY(ZoneStart_ % PageSize == 0);
    }

    void* Allocate(size_t size, int flags)
    {
        YTALLOC_VERIFY(size % PageSize == 0);
        bool restarted = false;
        while (true) {
            auto hint = (Current_ += size) - size;
            if (reinterpret_cast<uintptr_t>(hint) + size > ZoneEnd_) {
                if (restarted) {
                    ::fprintf(stderr, "*** YTAlloc was unable to mmap %zu bytes in zone %" PRIx64 "--%" PRIx64 "\n",
                        size,
                        ZoneStart_,
                        ZoneEnd_);
                    OomTrap();
                }
                restarted = true;
                Current_ = ZoneStart_;
            } else {
                char* ptr = static_cast<char*>(MappedMemoryManager->Map(
                    hint,
                    size,
                    MAP_FIXED_NOREPLACE | flags));
                if (reinterpret_cast<uintptr_t>(ptr) == hint) {
                    return ptr;
                }
                if (ptr != MAP_FAILED) {
                    MappedMemoryManager->Unmap(ptr, size);
                }
            }
        }
    }

    void Free(void* ptr, size_t size)
    {
        MappedMemoryManager->Unmap(ptr, size);
    }

private:
    const uintptr_t ZoneStart_;
    const uintptr_t ZoneEnd_;

    std::atomic<uintptr_t> Current_;
};

////////////////////////////////////////////////////////////////////////////////

// YTAlloc supports tagged allocations.
// Since the total number of tags can be huge, a two-level scheme is employed.
// Possible tags are arranged into sets each containing TaggedCounterSetSize tags.
// There are up to MaxTaggedCounterSets in total.
// Upper 4 sets are reserved for profiled allocations.
constexpr size_t TaggedCounterSetSize = 16384;
constexpr size_t AllocationProfilingTaggedCounterSets = 4;
constexpr size_t MaxTaggedCounterSets = 256 + AllocationProfilingTaggedCounterSets;

constexpr size_t MaxCapturedAllocationBacktraces = 65000;
static_assert(
    MaxCapturedAllocationBacktraces < AllocationProfilingTaggedCounterSets * TaggedCounterSetSize,
    "MaxCapturedAllocationBacktraces is too big");

constexpr TMemoryTag AllocationProfilingMemoryTagBase = TaggedCounterSetSize * (MaxTaggedCounterSets - AllocationProfilingTaggedCounterSets);
constexpr TMemoryTag AllocationProfilingUnknownMemoryTag = AllocationProfilingMemoryTagBase + MaxCapturedAllocationBacktraces;

static_assert(
    MaxMemoryTag == TaggedCounterSetSize * (MaxTaggedCounterSets - AllocationProfilingTaggedCounterSets) - 1,
    "Wrong MaxMemoryTag");

template <class TCounter>
using TUntaggedTotalCounters = TEnumIndexedVector<EBasicCounter, TCounter>;

template <class TCounter>
struct TTaggedTotalCounterSet
    : public TSystemAllocatable
{
    std::array<TEnumIndexedVector<EBasicCounter, TCounter>, TaggedCounterSetSize> Counters;
};

using TLocalTaggedBasicCounterSet = TTaggedTotalCounterSet<ssize_t>;
using TGlobalTaggedBasicCounterSet = TTaggedTotalCounterSet<std::atomic<ssize_t>>;

template <class TCounter>
struct TTotalCounters
{
    // The sum of counters across all tags.
    TUntaggedTotalCounters<TCounter> CumulativeTaggedCounters;

    // Counters for untagged allocations.
    TUntaggedTotalCounters<TCounter> UntaggedCounters;

    // Access to tagged counters may involve creation of a new tag set.
    // For simplicity, we separate the read-side (TaggedCounterSets) and the write-side (TaggedCounterSetHolders).
    // These arrays contain virtually identical data (up to std::unique_ptr and std::atomic semantic differences).
    std::array<std::atomic<TTaggedTotalCounterSet<TCounter>*>, MaxTaggedCounterSets> TaggedCounterSets{};
    std::array<std::unique_ptr<TTaggedTotalCounterSet<TCounter>>, MaxTaggedCounterSets> TaggedCounterSetHolders;

    // Protects TaggedCounterSetHolders from concurrent updates.
    NThreading::TForkAwareSpinLock TaggedCounterSetsLock;

    // Returns null if the set is not yet constructed.
    Y_FORCE_INLINE TTaggedTotalCounterSet<TCounter>* FindTaggedCounterSet(size_t index) const
    {
        return TaggedCounterSets[index].load();
    }

    // Constructs the set on first access.
    TTaggedTotalCounterSet<TCounter>* GetOrCreateTaggedCounterSet(size_t index)
    {
        auto* set = TaggedCounterSets[index].load();
        if (Y_LIKELY(set)) {
            return set;
        }

        auto guard = GuardWithTiming(TaggedCounterSetsLock);
        auto& setHolder = TaggedCounterSetHolders[index];
        if (!setHolder) {
            setHolder = std::make_unique<TTaggedTotalCounterSet<TCounter>>();
            TaggedCounterSets[index] = setHolder.get();
        }
        return setHolder.get();
    }
};

using TLocalSystemCounters = TEnumIndexedVector<ESystemCounter, ssize_t>;
using TGlobalSystemCounters = TEnumIndexedVector<ESystemCounter, std::atomic<ssize_t>>;

using TLocalSmallCounters = TEnumIndexedVector<ESmallArenaCounter, ssize_t>;
using TGlobalSmallCounters = TEnumIndexedVector<ESmallArenaCounter, std::atomic<ssize_t>>;

using TLocalLargeCounters = TEnumIndexedVector<ELargeArenaCounter, ssize_t>;
using TGlobalLargeCounters = TEnumIndexedVector<ELargeArenaCounter, std::atomic<ssize_t>>;

using TLocalHugeCounters = TEnumIndexedVector<EHugeCounter, ssize_t>;
using TGlobalHugeCounters = TEnumIndexedVector<EHugeCounter, std::atomic<ssize_t>>;

using TLocalUndumpableCounters = TEnumIndexedVector<EUndumpableCounter, ssize_t>;
using TGlobalUndumpableCounters = TEnumIndexedVector<EUndumpableCounter, std::atomic<ssize_t>>;

Y_FORCE_INLINE ssize_t LoadCounter(ssize_t counter)
{
    return counter;
}

Y_FORCE_INLINE ssize_t LoadCounter(const std::atomic<ssize_t>& counter)
{
    return counter.load();
}

////////////////////////////////////////////////////////////////////////////////

struct TMmapObservationEvent
{
    size_t Size;
    std::array<void*, MaxAllocationProfilingBacktraceDepth> Frames;
    int FrameCount;
    TInstant Timestamp;
    TFiberId FiberId;

    TMmapObservationEvent() = default;

    TMmapObservationEvent(
        size_t size,
        std::array<void*, MaxAllocationProfilingBacktraceDepth> frames,
        int frameCount)
        : Size(size)
        , Frames(frames)
        , FrameCount(frameCount)
    { }
};

class TMmapObservationManager
    : public TEventLogManagerBase<TMmapObservationEvent, TMmapObservationManager>
{
public:
    void SetBacktraceFormatter(TBacktraceFormatter formatter)
    {
        BacktraceFormatter_.store(formatter);
    }

private:
    std::atomic<TBacktraceFormatter> BacktraceFormatter_ = nullptr;

    Y_POD_STATIC_THREAD(bool) DisabledForCurrentThread_;

    friend class TEventLogManagerBase<TMmapObservationEvent, TMmapObservationManager>;

    virtual void OnEvent(const TMmapObservationEvent& /*event*/) override
    { }

    virtual void ProcessEvent(const TMmapObservationEvent& event) override
    {
        YTALLOC_LOG_DEBUG("Large arena mmap observed (Size: %zu, Timestamp: %s, FiberId: %" PRIx64 ")",
            event.Size,
            ToString(event.Timestamp).c_str(),
            event.FiberId);

        if (auto backtraceFormatter = BacktraceFormatter_.load()) {
            auto backtrace = backtraceFormatter(const_cast<void**>(event.Frames.data()), event.FrameCount);
            YTALLOC_LOG_DEBUG("YTAlloc stack backtrace (Stack: %s)",
                backtrace.c_str());
        }
    }
};

Y_POD_THREAD(bool) TMmapObservationManager::DisabledForCurrentThread_;

TExplicitlyConstructableSingleton<TMmapObservationManager> MmapObservationManager;

////////////////////////////////////////////////////////////////////////////////

// A per-thread structure containing counters, chunk caches etc.
struct TThreadState
    : public TFreeListItemBase<TThreadState>
    , public TLocalShardedState
{
    // TThreadState instances of all alive threads are put into a double-linked intrusive list.
    // This is a pair of next/prev pointers connecting an instance of TThreadState to its neighbors.
    TIntrusiveLinkedListNode<TThreadState> RegistryNode;

    // Pointers to the respective parts of TThreadManager::ThreadControlWord_.
    // If null then the thread is already destroyed (but TThreadState may still live for a while
    // due to ref-counting).
    ui8* AllocationProfilingEnabled;
    ui8* BackgroundThreadStarted;

    // TThreadStates are ref-counted.
    // TThreadManager::EnumerateThreadStates enumerates the registered states and acquires
    // a temporary reference preventing these states from being destructed. This provides
    // for shorter periods of time the global lock needs to be held.
    int RefCounter = 1;

    // Per-thread counters.
    TTotalCounters<ssize_t> TotalCounters;
    std::array<TLocalLargeCounters, LargeRankCount> LargeArenaCounters;
    TLocalUndumpableCounters UndumpableCounters;

    // Each thread maintains caches of small chunks.
    // One cache is for tagged chunks; the other is for untagged ones.
    // Each cache contains up to MaxCachedChunksPerRank chunks per any rank.
    // Special sentinels are placed to distinguish the boundaries of region containing
    // pointers of a specific rank. This enables a tiny-bit faster inplace boundary checks.

    static constexpr uintptr_t LeftSentinel = 1;
    static constexpr uintptr_t RightSentinel = 2;

    struct TSmallBlobCache
    {
        TSmallBlobCache()
        {
            void** chunkPtrs = CachedChunks.data();
            for (size_t rank = 0; rank < SmallRankCount; ++rank) {
                RankToCachedChunkPtrHead[rank] = chunkPtrs;
                chunkPtrs[0] = reinterpret_cast<void*>(LeftSentinel);
                chunkPtrs[MaxCachedChunksPerRank + 1] = reinterpret_cast<void*>(RightSentinel);

#ifdef YTALLOC_PARANOID
                RankToCachedChunkPtrTail[rank] = chunkPtrs;
                CachedChunkFull[rank] = false;

                RankToCachedChunkLeftBorder[rank] = chunkPtrs;
                RankToCachedChunkRightBorder[rank] = chunkPtrs + MaxCachedChunksPerRank + 1;
#endif
                chunkPtrs += MaxCachedChunksPerRank + 2;
            }
        }

        // For each rank we have a segment of pointers in CachedChunks with the following layout:
        //   LCC[C]........R
        // Legend:
        //   .  = garbage
        //   L  = left sentinel
        //   R  = right sentinel
        //   C  = cached pointer
        //  [C] = current cached pointer
        //
        // Under YTALLOC_PARANOID the following layout is used:
        //   L.[T]CCC[H]...R
        // Legend:
        //   [H] = head cached pointer, put chunks here
        //   [T] = tail cached pointer, take chunks from here

        //  +2 is for two sentinels
        std::array<void*, SmallRankCount * (MaxCachedChunksPerRank + 2)> CachedChunks{};

        // Pointer to [P] for each rank.
        std::array<void**, SmallRankCount> RankToCachedChunkPtrHead{};

#ifdef YTALLOC_PARANOID
        // Pointers to [L] and [R] for each rank.
        std::array<void**, SmallRankCount> RankToCachedChunkLeftBorder{};
        std::array<void**, SmallRankCount> RankToCachedChunkRightBorder{};

        std::array<void**, SmallRankCount> RankToCachedChunkPtrTail{};
        std::array<bool, SmallRankCount> CachedChunkFull{};
#endif
    };
    TEnumIndexedVector<EAllocationKind, TSmallBlobCache> SmallBlobCache;
};

struct TThreadStateToRegistryNode
{
    auto operator() (TThreadState* state) const
    {
        return &state->RegistryNode;
    }
};

// Manages all registered threads and controls access to TThreadState.
class TThreadManager
{
public:
    TThreadManager()
    {
        pthread_key_create(&ThreadDtorKey_, DestroyThread);

        NThreading::RegisterAtForkHandlers(
            nullptr,
            nullptr,
            [=] { AfterFork(); });
    }

    // Returns TThreadState for the current thread; the caller guarantees that this
    // state is initialized and is not destroyed yet.
    static TThreadState* GetThreadStateUnchecked();

    // Returns TThreadState for the current thread; may return null.
    static TThreadState* FindThreadState();

    // Returns TThreadState for the current thread; may not return null
    // (but may crash if TThreadState is already destroyed).
    static TThreadState* GetThreadStateChecked()
    {
        auto* state = FindThreadState();
        YTALLOC_VERIFY(state);
        return state;
    }

    // Enumerates all threads and invokes func passing TThreadState instances.
    // func must not throw but can take arbitrary time; no locks are being held while it executes.
    template <class THandler>
    void EnumerateThreadStatesAsync(const THandler& handler) noexcept
    {
        TMemoryTagGuard guard(NullMemoryTag);

        std::vector<TThreadState*> states;
        states.reserve(1024); // must be enough in most cases

        auto unrefStates = [&] {
            // Releasing references also requires global lock to be held to avoid getting zombies above.
            auto guard = GuardWithTiming(ThreadRegistryLock_);
            for (auto* state : states) {
                UnrefThreadState(state);
            }
        };

        auto tryRefStates = [&] {
            // Only hold this guard for a small period of time to reference all the states.
            auto guard = GuardWithTiming(ThreadRegistryLock_);
            auto* current = ThreadRegistry_.GetFront();
            while (current) {
                if (states.size() == states.capacity()) {
                    // Cannot allocate while holding ThreadRegistryLock_ due to a possible deadlock as follows:
                    // EnumerateThreadStatesAsync -> StartBackgroundThread -> EnumerateThreadStatesSync
                    // (many other scenarios are also possible).
                    guard.Release();
                    unrefStates();
                    states.clear();
                    states.reserve(states.capacity() * 2);
                    return false;
                }
                RefThreadState(current);
                states.push_back(current);
                current = current->RegistryNode.Next;
            }
            return true;
        };

        while (!tryRefStates()) ;

        for (auto* state : states) {
            handler(state);
        }

        unrefStates();
    }

    // Similar to EnumerateThreadStatesAsync but holds the global lock while enumerating the threads.
    // Also invokes a given prologue functor while holding the thread registry lock.
    // Handler and prologue calls must be fast and must not allocate.
    template <class TPrologue, class THandler>
    void EnumerateThreadStatesSync(const TPrologue& prologue, const THandler& handler) noexcept
    {
        auto guard = GuardWithTiming(ThreadRegistryLock_);
        prologue();
        auto* current = ThreadRegistry_.GetFront();
        while (current) {
            handler(current);
            current = current->RegistryNode.Next;
        }
    }


    // We store a special 64-bit "thread control word" in TLS encapsulating the following
    // crucial per-thread parameters:
    // * the current memory tag
    // * a flag indicating that a valid TThreadState is known to exists
    // (and can be obtained via GetThreadStateUnchecked)
    // * a flag indicating that allocation profiling is enabled
    // * a flag indicating that background thread is started
    // Thread control word is fetched via GetThreadControlWord and is compared
    // against FastPathControlWord to see if the fast path can be taken.
    // The latter happens when no memory tagging is configured, TThreadState is
    // valid, allocation profiling is disabled, and background thread is started.

    // The mask for extracting memory tag from thread control word.
    static constexpr ui64 MemoryTagControlWordMask = 0xffffffff;
    // ThreadStateValid is on.
    static constexpr ui64 ThreadStateValidControlWordMask = (1ULL << 32);
    // AllocationProfiling is on.
    static constexpr ui64 AllocationProfilingEnabledControlWordMask = (1ULL << 40);
    // All background thread are properly started.
    static constexpr ui64 BackgroundThreadStartedControlWorkMask = (1ULL << 48);
    // Memory tag is NullMemoryTag; thread state is valid.
    static constexpr ui64 FastPathControlWord =
        BackgroundThreadStartedControlWorkMask |
        ThreadStateValidControlWordMask |
        NullMemoryTag;

    Y_FORCE_INLINE static ui64 GetThreadControlWord()
    {
        return (&ThreadControlWord_)->Value;
    }


    static TMemoryTag GetCurrentMemoryTag()
    {
        return (&ThreadControlWord_)->Parts.MemoryTag;
    }

    static void SetCurrentMemoryTag(TMemoryTag tag)
    {
        Y_ABORT_UNLESS(tag <= MaxMemoryTag);
        (&ThreadControlWord_)->Parts.MemoryTag = tag;
    }


    static EMemoryZone GetCurrentMemoryZone()
    {
        return CurrentMemoryZone_;
    }

    static void SetCurrentMemoryZone(EMemoryZone zone)
    {
        CurrentMemoryZone_ = zone;
    }


    static void SetCurrentFiberId(TFiberId id)
    {
        CurrentFiberId_ = id;
    }

    static TFiberId GetCurrentFiberId()
    {
        return CurrentFiberId_;
    }

private:
    static void DestroyThread(void*);

    TThreadState* AllocateThreadState();

    void RefThreadState(TThreadState* state)
    {
        auto result = ++state->RefCounter;
        Y_ABORT_UNLESS(result > 1);
    }

    void UnrefThreadState(TThreadState* state)
    {
        auto result = --state->RefCounter;
        Y_ABORT_UNLESS(result >= 0);
        if (result == 0) {
            DestroyThreadState(state);
        }
    }

    void DestroyThreadState(TThreadState* state);

    void AfterFork();

private:
    // TThreadState instance for the current thread.
    // Initially null, then initialized when first needed.
    // TThreadState is destroyed upon thread termination (which is detected with
    // the help of pthread_key_create machinery), so this pointer can become null again.
    Y_POD_STATIC_THREAD(TThreadState*) ThreadState_;

    // Initially false, then set to true then TThreadState is destroyed.
    // If the thread requests for its state afterwards, null is returned and no new state is (re-)created.
    // The caller must be able to deal with it.
    Y_POD_STATIC_THREAD(bool) ThreadStateDestroyed_;

    union TThreadControlWord
    {
        ui64 __attribute__((__may_alias__)) Value;
        struct TParts
        {
            // The current memory tag used in all allocations by this thread.
            ui32 __attribute__((__may_alias__)) MemoryTag;
            // Indicates if a valid TThreadState exists and can be obtained via GetThreadStateUnchecked.
            ui8 __attribute__((__may_alias__)) ThreadStateValid;
            // Indicates if allocation profiling is on.
            ui8 __attribute__((__may_alias__)) AllocationProfilingEnabled;
            // Indicates if all background threads are properly started.
            ui8 __attribute__((__may_alias__)) BackgroundThreadStarted;
            ui8 Padding[2];
        } Parts;
    };
    Y_POD_STATIC_THREAD(TThreadControlWord) ThreadControlWord_;

    // See memory zone API.
    Y_POD_STATIC_THREAD(EMemoryZone) CurrentMemoryZone_;

    // See fiber id API.
    Y_POD_STATIC_THREAD(TFiberId) CurrentFiberId_;

    pthread_key_t ThreadDtorKey_;

    static constexpr size_t ThreadStatesBatchSize = 1;
    TSystemPool<TThreadState, ThreadStatesBatchSize> ThreadStatePool_;

    NThreading::TForkAwareSpinLock ThreadRegistryLock_;
    TIntrusiveLinkedList<TThreadState, TThreadStateToRegistryNode> ThreadRegistry_;
};

Y_POD_THREAD(TThreadState*) TThreadManager::ThreadState_;
Y_POD_THREAD(bool) TThreadManager::ThreadStateDestroyed_;
Y_POD_THREAD(TThreadManager::TThreadControlWord) TThreadManager::ThreadControlWord_;
Y_POD_THREAD(EMemoryZone) TThreadManager::CurrentMemoryZone_;
Y_POD_THREAD(TFiberId) TThreadManager::CurrentFiberId_;

TExplicitlyConstructableSingleton<TThreadManager> ThreadManager;

////////////////////////////////////////////////////////////////////////////////

void TConfigurationManager::SetAllocationProfilingEnabled(bool value)
{
    // Update threads' TLS.
    ThreadManager->EnumerateThreadStatesSync(
        [&] {
            AllocationProfilingEnabled_.store(value);
        },
        [&] (auto* state) {
            if (state->AllocationProfilingEnabled) {
                *state->AllocationProfilingEnabled = value;
            }
        });
}

////////////////////////////////////////////////////////////////////////////////
// Backtrace Manager
//
// Captures backtraces observed during allocations and assigns memory tags to them.
// Memory tags are chosen sequentially starting from AllocationProfilingMemoryTagBase.
//
// For each backtrace we compute a 64-bit hash and use it as a key in a certain concurrent hashmap.
// This hashmap is organized into BucketCount buckets, each consisting of BucketSize slots.
//
// Backtrace hash is translated into bucket index by taking the appropriate number of
// its lower bits. For each slot, we remember a 32-bit fingerprint, which is
// just the next 32 bits of the backtrace's hash, and the (previously assigned) memory tag.
//
// Upon access to the hashtable, the bucket is first scanned optimistically, without taking
// any locks. In case of a miss, a per-bucket spinlock is acquired and the bucket is rescanned.
//
// The above scheme may involve collisions but we neglect their probability.
//
// If the whole hash table overflows (i.e. a total of MaxCapturedAllocationBacktraces
// backtraces are captured) or the bucket overflows (i.e. all of its slots become occupied),
// the allocation is annotated with AllocationProfilingUnknownMemoryTag. Such allocations
// appear as having no backtrace whatsoever in the profiling reports.

class TBacktraceManager
{
public:
    // Sets the provider used for collecting backtraces when allocation profiling
    // is turned ON.
    void SetBacktraceProvider(TBacktraceProvider provider)
    {
        BacktraceProvider_.store(provider);
    }

    // Captures the backtrace and inserts it into the hashtable.
    TMemoryTag GetMemoryTagFromBacktrace(int framesToSkip)
    {
        std::array<void*, MaxAllocationProfilingBacktraceDepth> frames;
        auto backtraceProvider = BacktraceProvider_.load();
        if (!backtraceProvider) {
            return NullMemoryTag;
        }
        auto frameCount  = backtraceProvider(frames.data(), ConfigurationManager->GetProfilingBacktraceDepth(), framesToSkip);
        auto hash = GetBacktraceHash(frames.data(), frameCount);
        return CaptureBacktrace(hash, frames.data(), frameCount);
    }

    // Returns the backtrace corresponding to the given tag, if any.
    std::optional<TBacktrace> FindBacktrace(TMemoryTag tag)
    {
        if (tag < AllocationProfilingMemoryTagBase ||
            tag >= AllocationProfilingMemoryTagBase + MaxCapturedAllocationBacktraces)
        {
            return std::nullopt;
        }
        const auto& entry = Backtraces_[tag - AllocationProfilingMemoryTagBase];
        if (!entry.Captured.load()) {
            return std::nullopt;
        }
        return entry.Backtrace;
    }

private:
    static constexpr int Log2BucketCount = 16;
    static constexpr int BucketCount = 1 << Log2BucketCount;
    static constexpr int BucketSize = 8;

    std::atomic<TBacktraceProvider> BacktraceProvider_ = nullptr;

    std::array<std::array<std::atomic<ui32>, BucketSize>, BucketCount> Fingerprints_= {};
    std::array<std::array<std::atomic<TMemoryTag>, BucketSize>, BucketCount> MemoryTags_ = {};
    std::array<NThreading::TForkAwareSpinLock, BucketCount> BucketLocks_;
    std::atomic<TMemoryTag> CurrentMemoryTag_ = AllocationProfilingMemoryTagBase;

    struct TBacktraceEntry
    {
        TBacktrace Backtrace;
        std::atomic<bool> Captured = false;
    };

    std::array<TBacktraceEntry, MaxCapturedAllocationBacktraces> Backtraces_;

private:
    static size_t GetBacktraceHash(void** frames, int frameCount)
    {
        size_t hash = 0;
        for (int index = 0; index < frameCount; ++index) {
            hash = CombineHashes(hash, THash<void*>()(frames[index]));
        }
        return hash;
    }

    TMemoryTag CaptureBacktrace(size_t hash, void** frames, int frameCount)
    {
        size_t bucketIndex = hash % BucketCount;
        ui32 fingerprint = (hash >> Log2BucketCount) & 0xffffffff;
        // Zero fingerprint indicates the slot is free; check and adjust to ensure
        // that regular fingerprints are non-zero.
        if (fingerprint == 0) {
            fingerprint = 1;
        }

        for (int slotIndex = 0; slotIndex < BucketSize; ++slotIndex) {
            auto currentFingerprint = Fingerprints_[bucketIndex][slotIndex].load(std::memory_order_relaxed);
            if (currentFingerprint == fingerprint) {
                return MemoryTags_[bucketIndex][slotIndex].load();
            }
        }

        auto guard = Guard(BucketLocks_[bucketIndex]);

        int spareSlotIndex = -1;
        for (int slotIndex = 0; slotIndex < BucketSize; ++slotIndex) {
            auto currentFingerprint = Fingerprints_[bucketIndex][slotIndex].load(std::memory_order_relaxed);
            if (currentFingerprint == fingerprint) {
                return MemoryTags_[bucketIndex][slotIndex];
            }
            if (currentFingerprint == 0) {
                spareSlotIndex = slotIndex;
                break;
            }
        }

        if (spareSlotIndex < 0) {
            return AllocationProfilingUnknownMemoryTag;
        }

        auto memoryTag = CurrentMemoryTag_++;
        if (memoryTag >= AllocationProfilingMemoryTagBase + MaxCapturedAllocationBacktraces) {
            return AllocationProfilingUnknownMemoryTag;
        }

        MemoryTags_[bucketIndex][spareSlotIndex].store(memoryTag);
        Fingerprints_[bucketIndex][spareSlotIndex].store(fingerprint);

        auto& entry = Backtraces_[memoryTag - AllocationProfilingMemoryTagBase];
        entry.Backtrace.FrameCount = frameCount;
        ::memcpy(entry.Backtrace.Frames.data(), frames, sizeof (void*) * frameCount);
        entry.Captured.store(true);

        return memoryTag;
    }
};

TExplicitlyConstructableSingleton<TBacktraceManager> BacktraceManager;

////////////////////////////////////////////////////////////////////////////////

// Mimics the counters of TThreadState but uses std::atomic to survive concurrent access.
struct TGlobalState
    : public TGlobalShardedState
{
    TTotalCounters<std::atomic<ssize_t>> TotalCounters;
    std::array<TGlobalLargeCounters, LargeRankCount> LargeArenaCounters;
    TGlobalUndumpableCounters UndumpableCounters;
};

TExplicitlyConstructableSingleton<TGlobalState> GlobalState;

////////////////////////////////////////////////////////////////////////////////

// Accumulates various allocation statistics.
class TStatisticsManager
{
public:
    template <EAllocationKind Kind = EAllocationKind::Tagged, class TState>
    static Y_FORCE_INLINE void IncrementTotalCounter(TState* state, TMemoryTag tag, EBasicCounter counter, ssize_t delta)
    {
        // This branch is typically resolved at compile time.
        if (Kind == EAllocationKind::Tagged && tag != NullMemoryTag) {
            IncrementTaggedTotalCounter(&state->TotalCounters, tag, counter, delta);
        } else {
            IncrementUntaggedTotalCounter(&state->TotalCounters, counter, delta);
        }
    }

    static Y_FORCE_INLINE void IncrementTotalCounter(TMemoryTag tag, EBasicCounter counter, ssize_t delta)
    {
        IncrementTotalCounter(GlobalState.Get(), tag, counter, delta);
    }

    void IncrementSmallArenaCounter(ESmallArenaCounter counter, size_t rank, ssize_t delta)
    {
        SmallArenaCounters_[rank][counter] += delta;
    }

    template <class TState>
    static Y_FORCE_INLINE void IncrementLargeArenaCounter(TState* state, size_t rank, ELargeArenaCounter counter, ssize_t delta)
    {
        state->LargeArenaCounters[rank][counter] += delta;
    }

    template <class TState>
    static Y_FORCE_INLINE void IncrementUndumpableCounter(TState* state, EUndumpableCounter counter, ssize_t delta)
    {
        state->UndumpableCounters[counter] += delta;
    }

    void IncrementHugeCounter(EHugeCounter counter, ssize_t delta)
    {
        HugeCounters_[counter] += delta;
    }

    void IncrementHugeUndumpableCounter(EUndumpableCounter counter, ssize_t delta)
    {
        HugeUndumpableCounters_[counter] += delta;
    }

    void IncrementSystemCounter(ESystemCounter counter, ssize_t delta)
    {
        SystemCounters_[counter] += delta;
    }

    // Computes memory usage for a list of tags by aggregating counters across threads.
    void GetTaggedMemoryCounters(const TMemoryTag* tags, size_t count, TEnumIndexedVector<EBasicCounter, ssize_t>* counters)
    {
        TMemoryTagGuard guard(NullMemoryTag);

        for (size_t index = 0; index < count; ++index) {
            counters[index][EBasicCounter::BytesAllocated] = 0;
            counters[index][EBasicCounter::BytesFreed] = 0;
        }

        for (size_t index = 0; index < count; ++index) {
            auto tag = tags[index];
            counters[index][EBasicCounter::BytesAllocated] += LoadTaggedTotalCounter(GlobalState->TotalCounters, tag, EBasicCounter::BytesAllocated);
            counters[index][EBasicCounter::BytesFreed] += LoadTaggedTotalCounter(GlobalState->TotalCounters, tag, EBasicCounter::BytesFreed);
        }

        ThreadManager->EnumerateThreadStatesAsync(
            [&] (const auto* state) {
                for (size_t index = 0; index < count; ++index) {
                    auto tag = tags[index];
                    counters[index][EBasicCounter::BytesAllocated] += LoadTaggedTotalCounter(state->TotalCounters, tag, EBasicCounter::BytesAllocated);
                    counters[index][EBasicCounter::BytesFreed] += LoadTaggedTotalCounter(state->TotalCounters, tag, EBasicCounter::BytesFreed);
                }
            });

        for (size_t index = 0; index < count; ++index) {
            counters[index][EBasicCounter::BytesUsed] = GetUsed(counters[index][EBasicCounter::BytesAllocated], counters[index][EBasicCounter::BytesFreed]);
        }
    }

    void GetTaggedMemoryUsage(const TMemoryTag* tags, size_t count, size_t* results)
    {
        TMemoryTagGuard guard(NullMemoryTag);

        std::vector<TEnumIndexedVector<EBasicCounter, ssize_t>> counters;
        counters.resize(count);
        GetTaggedMemoryCounters(tags, count, counters.data());

        for (size_t index = 0; index < count; ++index) {
            results[index] = counters[index][EBasicCounter::BytesUsed];
        }
    }

    TEnumIndexedVector<ETotalCounter, ssize_t> GetTotalAllocationCounters()
    {
        TEnumIndexedVector<ETotalCounter, ssize_t> result;

        auto accumulate = [&] (const auto& counters) {
            result[ETotalCounter::BytesAllocated] += LoadCounter(counters[EBasicCounter::BytesAllocated]);
            result[ETotalCounter::BytesFreed] += LoadCounter(counters[EBasicCounter::BytesFreed]);
        };

        accumulate(GlobalState->TotalCounters.UntaggedCounters);
        accumulate(GlobalState->TotalCounters.CumulativeTaggedCounters);

        ThreadManager->EnumerateThreadStatesAsync(
            [&] (const auto* state) {
                accumulate(state->TotalCounters.UntaggedCounters);
                accumulate(state->TotalCounters.CumulativeTaggedCounters);
            });

        result[ETotalCounter::BytesUsed] = GetUsed(
            result[ETotalCounter::BytesAllocated],
            result[ETotalCounter::BytesFreed]);

        auto systemCounters = GetSystemAllocationCounters();
        result[ETotalCounter::BytesCommitted] += systemCounters[EBasicCounter::BytesUsed];

        auto hugeCounters = GetHugeAllocationCounters();
        result[ETotalCounter::BytesCommitted] += hugeCounters[EHugeCounter::BytesUsed];

        auto smallArenaCounters = GetSmallArenaAllocationCounters();
        for (size_t rank = 0; rank < SmallRankCount; ++rank) {
            result[ETotalCounter::BytesCommitted] += smallArenaCounters[rank][ESmallArenaCounter::BytesCommitted];
        }

        auto largeArenaCounters = GetLargeArenaAllocationCounters();
        for (size_t rank = 0; rank < LargeRankCount; ++rank) {
            result[ETotalCounter::BytesCommitted] += largeArenaCounters[rank][ELargeArenaCounter::BytesCommitted];
        }

        result[ETotalCounter::BytesUnaccounted] = std::max<ssize_t>(GetProcessRss() - result[ETotalCounter::BytesCommitted], 0);

        return result;
    }

    TEnumIndexedVector<ESmallCounter, ssize_t> GetSmallAllocationCounters()
    {
        TEnumIndexedVector<ESmallCounter, ssize_t> result;

        auto totalCounters = GetTotalAllocationCounters();
        result[ESmallCounter::BytesAllocated] = totalCounters[ETotalCounter::BytesAllocated];
        result[ESmallCounter::BytesFreed] = totalCounters[ETotalCounter::BytesFreed];
        result[ESmallCounter::BytesUsed] = totalCounters[ETotalCounter::BytesUsed];

        auto largeArenaCounters = GetLargeArenaAllocationCounters();
        for (size_t rank = 0; rank < LargeRankCount; ++rank) {
            result[ESmallCounter::BytesAllocated] -= largeArenaCounters[rank][ELargeArenaCounter::BytesAllocated];
            result[ESmallCounter::BytesFreed] -= largeArenaCounters[rank][ELargeArenaCounter::BytesFreed];
            result[ESmallCounter::BytesUsed] -= largeArenaCounters[rank][ELargeArenaCounter::BytesUsed];
        }

        auto hugeCounters = GetHugeAllocationCounters();
        result[ESmallCounter::BytesAllocated] -= hugeCounters[EHugeCounter::BytesAllocated];
        result[ESmallCounter::BytesFreed] -= hugeCounters[EHugeCounter::BytesFreed];
        result[ESmallCounter::BytesUsed] -= hugeCounters[EHugeCounter::BytesUsed];

        return result;
    }

    std::array<TLocalSmallCounters, SmallRankCount> GetSmallArenaAllocationCounters()
    {
        std::array<TLocalSmallCounters, SmallRankCount> result;
        for (size_t rank = 0; rank < SmallRankCount; ++rank) {
            for (auto counter : TEnumTraits<ESmallArenaCounter>::GetDomainValues()) {
                result[rank][counter] = SmallArenaCounters_[rank][counter].load();
            }
        }
        return result;
    }

    TEnumIndexedVector<ELargeCounter, ssize_t> GetLargeAllocationCounters()
    {
        TEnumIndexedVector<ELargeCounter, ssize_t> result;
        auto largeArenaCounters = GetLargeArenaAllocationCounters();
        for (size_t rank = 0; rank < LargeRankCount; ++rank) {
            result[ESmallCounter::BytesAllocated] += largeArenaCounters[rank][ELargeArenaCounter::BytesAllocated];
            result[ESmallCounter::BytesFreed] += largeArenaCounters[rank][ELargeArenaCounter::BytesFreed];
            result[ESmallCounter::BytesUsed] += largeArenaCounters[rank][ELargeArenaCounter::BytesUsed];
        }
        return result;
    }

    std::array<TLocalLargeCounters, LargeRankCount> GetLargeArenaAllocationCounters()
    {
        std::array<TLocalLargeCounters, LargeRankCount> result{};

        for (size_t rank = 0; rank < LargeRankCount; ++rank) {
            for (auto counter : TEnumTraits<ELargeArenaCounter>::GetDomainValues()) {
                result[rank][counter] = GlobalState->LargeArenaCounters[rank][counter].load();
            }
        }

        ThreadManager->EnumerateThreadStatesAsync(
            [&] (const auto* state) {
                for (size_t rank = 0; rank < LargeRankCount; ++rank) {
                    for (auto counter : TEnumTraits<ELargeArenaCounter>::GetDomainValues()) {
                        result[rank][counter] += state->LargeArenaCounters[rank][counter];
                    }
                }
            });

        for (size_t rank = 0; rank < LargeRankCount; ++rank) {
            result[rank][ELargeArenaCounter::BytesUsed] = GetUsed(result[rank][ELargeArenaCounter::BytesAllocated], result[rank][ELargeArenaCounter::BytesFreed]);
            result[rank][ELargeArenaCounter::BlobsUsed] = GetUsed(result[rank][ELargeArenaCounter::BlobsAllocated], result[rank][ELargeArenaCounter::BlobsFreed]);
        }

        return result;
    }

    TLocalSystemCounters GetSystemAllocationCounters()
    {
        TLocalSystemCounters result;
        for (auto counter : TEnumTraits<ESystemCounter>::GetDomainValues()) {
            result[counter] = SystemCounters_[counter].load();
        }
        result[ESystemCounter::BytesUsed] = GetUsed(result[ESystemCounter::BytesAllocated], result[ESystemCounter::BytesFreed]);
        return result;
    }

    TLocalHugeCounters GetHugeAllocationCounters()
    {
        TLocalHugeCounters result;
        for (auto counter : TEnumTraits<EHugeCounter>::GetDomainValues()) {
            result[counter] = HugeCounters_[counter].load();
        }
        result[EHugeCounter::BytesUsed] = GetUsed(result[EHugeCounter::BytesAllocated], result[EHugeCounter::BytesFreed]);
        result[EHugeCounter::BlobsUsed] = GetUsed(result[EHugeCounter::BlobsAllocated], result[EHugeCounter::BlobsFreed]);
        return result;
    }

    TLocalUndumpableCounters GetUndumpableAllocationCounters()
    {
        TLocalUndumpableCounters result;
        for (auto counter : TEnumTraits<EUndumpableCounter>::GetDomainValues()) {
            result[counter] = HugeUndumpableCounters_[counter].load();
            result[counter] += GlobalState->UndumpableCounters[counter].load();
        }

        ThreadManager->EnumerateThreadStatesAsync(
            [&] (const auto* state) {
                result[EUndumpableCounter::BytesAllocated] += LoadCounter(state->UndumpableCounters[EUndumpableCounter::BytesAllocated]);
                result[EUndumpableCounter::BytesFreed] += LoadCounter(state->UndumpableCounters[EUndumpableCounter::BytesFreed]);
            });

        result[EUndumpableCounter::BytesUsed] = GetUsed(result[EUndumpableCounter::BytesAllocated], result[EUndumpableCounter::BytesFreed]);
        return result;
    }

    // Called before TThreadState is destroyed.
    // Adds the counter values from TThreadState to the global counters.
    void AccumulateLocalCounters(TThreadState* state)
    {
        for (auto counter : TEnumTraits<EBasicCounter>::GetDomainValues()) {
            GlobalState->TotalCounters.CumulativeTaggedCounters[counter] += state->TotalCounters.CumulativeTaggedCounters[counter];
            GlobalState->TotalCounters.UntaggedCounters[counter] += state->TotalCounters.UntaggedCounters[counter];
        }
        for (size_t index = 0; index < MaxTaggedCounterSets; ++index) {
            const auto* localSet = state->TotalCounters.FindTaggedCounterSet(index);
            if (!localSet) {
                continue;
            }
            auto* globalSet = GlobalState->TotalCounters.GetOrCreateTaggedCounterSet(index);
            for (size_t jndex = 0; jndex < TaggedCounterSetSize; ++jndex) {
                for (auto counter : TEnumTraits<EBasicCounter>::GetDomainValues()) {
                    globalSet->Counters[jndex][counter] += localSet->Counters[jndex][counter];
                }
            }
        }
        for (size_t rank = 0; rank < LargeRankCount; ++rank) {
            for (auto counter : TEnumTraits<ELargeArenaCounter>::GetDomainValues()) {
                GlobalState->LargeArenaCounters[rank][counter] += state->LargeArenaCounters[rank][counter];
            }
        }
        for (auto counter : TEnumTraits<EUndumpableCounter>::GetDomainValues()) {
            GlobalState->UndumpableCounters[counter] += state->UndumpableCounters[counter];
        }
    }

private:
    template <class TCounter>
    static ssize_t LoadTaggedTotalCounter(const TTotalCounters<TCounter>& counters, TMemoryTag tag, EBasicCounter counter)
    {
        const auto* set = counters.FindTaggedCounterSet(tag / TaggedCounterSetSize);
        if (Y_UNLIKELY(!set)) {
            return 0;
        }
        return LoadCounter(set->Counters[tag % TaggedCounterSetSize][counter]);
    }

    template <class TCounter>
    static Y_FORCE_INLINE void IncrementUntaggedTotalCounter(TTotalCounters<TCounter>* counters, EBasicCounter counter, ssize_t delta)
    {
        counters->UntaggedCounters[counter] += delta;
    }

    template <class TCounter>
    static Y_FORCE_INLINE void IncrementTaggedTotalCounter(TTotalCounters<TCounter>* counters, TMemoryTag tag, EBasicCounter counter, ssize_t delta)
    {
        counters->CumulativeTaggedCounters[counter] += delta;
        auto* set = counters->GetOrCreateTaggedCounterSet(tag / TaggedCounterSetSize);
        set->Counters[tag % TaggedCounterSetSize][counter] += delta;
    }


    static ssize_t GetProcessRss()
    {
        auto* file = ::fopen("/proc/self/statm", "r");
        if (!file) {
            return 0;
        }

        ssize_t dummy;
        ssize_t rssPages;
        auto readResult = fscanf(file, "%zd %zd", &dummy, &rssPages);

        ::fclose(file);

        if (readResult != 2) {
            return 0;
        }

        return rssPages * PageSize;
    }

private:
    TGlobalSystemCounters SystemCounters_;
    std::array<TGlobalSmallCounters, SmallRankCount> SmallArenaCounters_;
    TGlobalHugeCounters HugeCounters_;
    TGlobalUndumpableCounters HugeUndumpableCounters_;
};

TExplicitlyConstructableSingleton<TStatisticsManager> StatisticsManager;

////////////////////////////////////////////////////////////////////////////////

void* TSystemAllocator::Allocate(size_t size)
{
    auto rawSize = GetRawBlobSize<TSystemBlobHeader>(size);
    void* mmappedPtr;
    while (true) {
        auto currentPtr = CurrentPtr_.fetch_add(rawSize);
        Y_ABORT_UNLESS(currentPtr + rawSize <= SystemZoneEnd);
        mmappedPtr = MappedMemoryManager->Map(
            currentPtr,
            rawSize,
            MAP_FIXED_NOREPLACE | MAP_POPULATE);
        if (mmappedPtr == reinterpret_cast<void*>(currentPtr)) {
            break;
        }
        if (mmappedPtr != MAP_FAILED) {
            MappedMemoryManager->Unmap(mmappedPtr, rawSize);
        }
    }
    auto* blob = static_cast<TSystemBlobHeader*>(mmappedPtr);
    new (blob) TSystemBlobHeader(size);
    auto* result = HeaderToPtr(blob);
    PoisonUninitializedRange(result, size);
    StatisticsManager->IncrementSystemCounter(ESystemCounter::BytesAllocated, rawSize);
    return result;
}

void TSystemAllocator::Free(void* ptr)
{
    auto* blob = PtrToHeader<TSystemBlobHeader>(ptr);
    auto rawSize = GetRawBlobSize<TSystemBlobHeader>(blob->Size);
    MappedMemoryManager->Unmap(blob, rawSize);
    StatisticsManager->IncrementSystemCounter(ESystemCounter::BytesFreed, rawSize);
}

////////////////////////////////////////////////////////////////////////////////
// Small allocator
//
// Allocations (called small chunks) are grouped by their sizes. Two most-significant binary digits are
// used to determine the rank of a chunk, which guarantees 25% overhead in the worst case.
// A pair of helper arrays (SizeToSmallRank1 and SizeToSmallRank2) are used to compute ranks; we expect
// them to be permanently cached.
//
// Chunks of the same rank are served by a (small) arena allocator.
// In fact, there are two arenas for each rank: one is for tagged allocations and another is for untagged ones.
//
// We encode chunk's rank and whether it is tagged or not in the resulting pointer as follows:
//   0- 3:  must be zero due to alignment
//   4-39:  varies
//  40-44:  rank
//     45:  0 for untagged allocations, 1 for tagged ones
//  45-63:  zeroes
// This enables computing chunk's rank and also determining if it is tagged in constant time
// without any additional lookups. Also, one pays no space overhead for untagged allocations
// and pays 16 bytes for each tagged one.
//
// Each arena allocates extents of memory by calling mmap for each extent of SmallExtentSize bytes.
// (Recall that this memory is never reclaimed.)
// Each extent is then sliced into segments of SmallSegmentSize bytes.
// Whenever a new segment is acquired, its memory is pre-faulted by madvise(MADV_POPULATE).
// New segments are acquired in a lock-free manner.
//
// Each thread maintains a separate cache of chunks of each rank (two caches to be precise: one
// for tagged allocations and the other for untagged). These caches are fully thread-local and
// involve no atomic operations.
//
// There are also global caches (per rank, for tagged and untagged allocations).
// Instead of keeping individual chunks these work with chunk groups (collections of up to ChunksPerGroup
// arbitrary chunks).
//
// When the local cache becomes exhausted, a group of chunks is fetched from the global cache
// (if the latter is empty then the arena allocator is consulted).
// Vice versa, if the local cache overflows, a group of chunks is moved from it to the global cache.
//
// Global caches and arena allocators also take care of (rare) cases when Allocate/Free is called
// without a valid thread state (which happens during thread shutdown when TThreadState is already destroyed).
//
// Each arena allocates memory in a certain "data" zone of SmallZoneSize.
// In addition to that zone, up to two "shadow" zones are maintained.
//
// The first one contains memory tags of chunks residing in the primary zone.
// The second one (which is present if YTALLOC_NERVOUS is defined) contains
// states of chunks. These states enable some simple internal sanity checks
// (e.g. detect attempts to double-free a chunk).
//
// Addresses in the data zone are directly mapped to offsets in shadow zones.
// When a segment of a small arena zone is allocated, the relevant portions of shadow
// zones get initialized (and also accounted for as a system allocation).
//
// Shadow zones are memory-mapped with MAP_NORESERVE flag and are quite sparse.
// These zones are omitted from core dumps due to their huge size and sparsity.

// For each small rank i, gives max K such that 2^k <= SmallRankToSize[i].
// Chunk pointer is mapped to its shadow image via GetShadowOffset helper.
// Note that chunk size is not always a power of 2. To avoid costly integer division,
// chunk pointer is translated by means of bitwise shift only (leaving some bytes
// of shadow zones unused). This array provides the needed shifts.
constexpr int SmallRankToLogSize[SmallRankCount] = {
    0,
    4, 5, 5, 6, 6, 7,
    7, 8, 8, 9, 9, 10, 10, 11,
    11, 12, 12, 13, 13, 14, 14, 15
};

enum class ESmallChunkState : ui8
{
    Spare         = 0,
    Allocated     = 0x61, // a
    Freed         = 0x66  // f
};

class TSmallArenaAllocator
{
public:
    TSmallArenaAllocator(EAllocationKind kind, size_t rank, uintptr_t dataZoneStart)
        : Kind_(kind)
        , Rank_(rank)
        , LogSize_(SmallRankToLogSize[Rank_])
        , ChunkSize_(SmallRankToSize[Rank_])
        , DataZoneStart_(dataZoneStart)
        , DataZoneAllocator_(DataZoneStart_, DataZoneStart_ + SmallZoneSize)
    { }

    size_t PullMany(void** batch, size_t maxCount)
    {
        size_t count;
        while (true) {
            count = TryAllocateFromCurrentExtent(batch, maxCount);
            if (Y_LIKELY(count != 0)) {
                break;
            }
            PopulateAnotherExtent();
        }
        return count;
    }

    void* Allocate(size_t size)
    {
        void* ptr;
        auto count = PullMany(&ptr, 1);
        YTALLOC_PARANOID_ASSERT(count == 1);
        YTALLOC_PARANOID_ASSERT(PtrToSmallRank(ptr) == Rank_);
        PoisonUninitializedRange(ptr, size);
        UpdateChunkState(ptr, ESmallChunkState::Freed, ESmallChunkState::Allocated);
        return ptr;
    }

    TMemoryTag GetAndResetMemoryTag(const void* ptr)
    {
        auto& tag = MemoryTagZoneStart_[GetShadowOffset(ptr)];
        auto currentTag = tag;
        tag = NullMemoryTag;
        return currentTag;
    }

    void SetMemoryTag(void* ptr, TMemoryTag tag)
    {
        MemoryTagZoneStart_[GetShadowOffset(ptr)] = tag;
    }

    void UpdateChunkState(const void* ptr, ESmallChunkState expectedState, ESmallChunkState newState)
    {
#ifdef YTALLOC_NERVOUS
        auto& state = ChunkStateZoneStart_[GetShadowOffset(ptr)];
        auto actualState = state;
        if (Y_UNLIKELY(actualState != expectedState)) {
            char message[256];
            sprintf(message, "Invalid small chunk state at %p: expected %" PRIx8 ", actual %" PRIx8,
                ptr,
                static_cast<ui8>(expectedState),
                static_cast<ui8>(actualState));
            YTALLOC_TRAP(message);
        }
        state = newState;
#else
        Y_UNUSED(ptr);
        Y_UNUSED(expectedState);
        Y_UNUSED(newState);
#endif
    }

private:
    size_t TryAllocateFromCurrentExtent(void** batch, size_t maxCount)
    {
        auto* oldPtr = CurrentPtr_.load();
        if (Y_UNLIKELY(!oldPtr)) {
            return 0;
        }

        auto* currentExtent = CurrentExtent_.load(std::memory_order_relaxed);
        if (Y_UNLIKELY(!currentExtent)) {
            return 0;
        }

        char* newPtr;
        while (true) {
            if (Y_UNLIKELY(oldPtr < currentExtent || oldPtr + ChunkSize_ + RightReadableAreaSize > currentExtent + SmallExtentSize)) {
                return 0;
            }

            newPtr = std::min(
                oldPtr + ChunkSize_ * maxCount,
                currentExtent + SmallExtentSize);

            auto* alignedNewPtr = AlignDownToSmallSegment(currentExtent, newPtr);
            if (alignedNewPtr > oldPtr) {
                newPtr = alignedNewPtr;
            }

            if (Y_LIKELY(CurrentPtr_.compare_exchange_weak(oldPtr, newPtr))) {
                break;
            }
        }

        auto* firstSegment = AlignUpToSmallSegment(currentExtent, oldPtr);
        auto* nextSegment = AlignUpToSmallSegment(currentExtent, newPtr);
        if (firstSegment != nextSegment) {
            auto size = nextSegment - firstSegment;
            MappedMemoryManager->PopulateReadOnly(firstSegment, size);

            StatisticsManager->IncrementSmallArenaCounter(ESmallArenaCounter::BytesCommitted, Rank_, size);
            StatisticsManager->IncrementSmallArenaCounter(ESmallArenaCounter::PagesCommitted, Rank_, size / PageSize);
            if (Kind_ == EAllocationKind::Tagged) {
                StatisticsManager->IncrementSystemCounter(ESystemCounter::BytesAllocated, size / ChunkSize_ * sizeof(TMemoryTag));
            }
#ifdef YTALLOC_NERVOUS
            StatisticsManager->IncrementSystemCounter(ESystemCounter::BytesAllocated, size / ChunkSize_ * sizeof(ESmallChunkState));
#endif
        }

        size_t count = 0;
        while (oldPtr != newPtr) {
            UpdateChunkState(oldPtr, ESmallChunkState::Spare, ESmallChunkState::Freed);

            batch[count] = oldPtr;

            oldPtr += ChunkSize_;
            count++;
        }
        return count;
    }

    void PopulateAnotherExtent()
    {
        auto lockGuard = GuardWithTiming(ExtentLock_);

        auto* currentPtr = CurrentPtr_.load();
        auto* currentExtent = CurrentExtent_.load();

        if (currentPtr && currentPtr + ChunkSize_ + RightReadableAreaSize <= currentExtent + SmallExtentSize) {
            // No need for a new extent.
            return;
        }

        auto* newExtent = static_cast<char*>(DataZoneAllocator_.Allocate(SmallExtentAllocSize, 0));

        AllocateShadowZones();

        YTALLOC_VERIFY(reinterpret_cast<uintptr_t>(newExtent) % SmallExtentAllocSize == 0);
        CurrentPtr_ = CurrentExtent_ = newExtent;

        StatisticsManager->IncrementSmallArenaCounter(ESmallArenaCounter::BytesMapped, Rank_, SmallExtentAllocSize);
        StatisticsManager->IncrementSmallArenaCounter(ESmallArenaCounter::PagesMapped, Rank_, SmallExtentAllocSize / PageSize);
    }

private:
    const EAllocationKind Kind_;
    const size_t Rank_;
    const size_t LogSize_;
    const size_t ChunkSize_;
    const uintptr_t DataZoneStart_;

    TZoneAllocator DataZoneAllocator_;

    bool ShadowZonesAllocated_ = false;
    TMemoryTag* MemoryTagZoneStart_;
#ifdef YTALLOC_NERVOUS
    ESmallChunkState* ChunkStateZoneStart_;
#endif

    NThreading::TForkAwareSpinLock ExtentLock_;
    std::atomic<char*> CurrentPtr_ = nullptr;
    std::atomic<char*> CurrentExtent_ = nullptr;

    size_t GetShadowOffset(const void* ptr)
    {
        return (reinterpret_cast<uintptr_t>(ptr) - DataZoneStart_) >> LogSize_;
    }

    void AllocateShadowZones()
    {
        if (ShadowZonesAllocated_) {
            return;
        }

        if (Kind_ == EAllocationKind::Tagged) {
            MemoryTagZoneStart_ = MapShadowZone<TMemoryTag>();
        }
#ifdef YTALLOC_NERVOUS
        ChunkStateZoneStart_ = MapShadowZone<ESmallChunkState>();
#endif

        ShadowZonesAllocated_ = true;
    }

    template <class T>
    T* MapShadowZone()
    {
        auto size = AlignUp((SmallZoneSize >> LogSize_) * sizeof (T), PageSize);
        auto* ptr = static_cast<T*>(MappedMemoryManager->Map(SystemZoneStart, size, MAP_NORESERVE));
        MappedMemoryManager->DontDump(ptr, size);
        return ptr;
    }
};

TExplicitlyConstructableSingleton<TEnumIndexedVector<EAllocationKind, std::array<TExplicitlyConstructableSingleton<TSmallArenaAllocator>, SmallRankCount>>> SmallArenaAllocators;

////////////////////////////////////////////////////////////////////////////////

constexpr size_t ChunksPerGroup = 128;
constexpr size_t GroupsBatchSize = 1024;

static_assert(ChunksPerGroup <= MaxCachedChunksPerRank, "ChunksPerGroup > MaxCachedChunksPerRank");

class TChunkGroup
    : public TFreeListItemBase<TChunkGroup>
{
public:
    bool IsEmpty() const
    {
        return Size_ == 0;
    }

    size_t ExtractAll(void** ptrs)
    {
        auto count = Size_;
        ::memcpy(ptrs, Ptrs_.data(), count * sizeof(void*));
        Size_ = 0;
        return count;
    }

    void PutOne(void* ptr)
    {
        PutMany(&ptr, 1);
    }

    void PutMany(void** ptrs, size_t count)
    {
        YTALLOC_PARANOID_ASSERT(Size_ == 0);
        YTALLOC_PARANOID_ASSERT(count <= ChunksPerGroup);
        ::memcpy(Ptrs_.data(), ptrs, count * sizeof(void*));
        Size_ = count;
    }

private:
    size_t Size_ = 0; // <= ChunksPerGroup
    std::array<void*, ChunksPerGroup> Ptrs_;
};

class TGlobalSmallChunkCache
{
public:
    explicit TGlobalSmallChunkCache(EAllocationKind kind)
        : Kind_(kind)
    { }

#ifdef YTALLOC_PARANOID
    void CanonizeChunkPtrs(TThreadState* state, size_t rank)
    {
        auto& chunkPtrPtr = state->SmallBlobCache[Kind_].RankToCachedChunkPtrHead[rank];

        auto leftBorder = state->SmallBlobCache[Kind_].RankToCachedChunkLeftBorder[rank];
        auto rightBorder = state->SmallBlobCache[Kind_].RankToCachedChunkRightBorder[rank];

        state->SmallBlobCache[Kind_].CachedChunkFull[rank] = false;
        if (chunkPtrPtr + 1 == rightBorder) {
            chunkPtrPtr = leftBorder;
            state->SmallBlobCache[Kind_].CachedChunkFull[rank] = true;
        }

        state->SmallBlobCache[Kind_].RankToCachedChunkPtrTail[rank] = leftBorder;
    }
#endif

    bool TryMoveGroupToLocal(TThreadState* state, size_t rank)
    {
        auto& groups = RankToChunkGroups_[rank];
        auto* group = groups.Extract(state);
        if (!Y_LIKELY(group)) {
            return false;
        }

        YTALLOC_PARANOID_ASSERT(!group->IsEmpty());

        auto& chunkPtrPtr = state->SmallBlobCache[Kind_].RankToCachedChunkPtrHead[rank];
#ifdef YTALLOC_PARANOID
        chunkPtrPtr = state->SmallBlobCache[Kind_].RankToCachedChunkLeftBorder[rank];
        state->SmallBlobCache[Kind_].RankToCachedChunkPtrTail[rank] = chunkPtrPtr;
#endif
        auto chunkCount = group->ExtractAll(chunkPtrPtr + 1);
        chunkPtrPtr += chunkCount;

#ifdef YTALLOC_PARANOID
        CanonizeChunkPtrs(state, rank);
#endif
        GroupPool_.Free(state, group);
        return true;
    }

    void MoveGroupToGlobal(TThreadState* state, size_t rank)
    {
        auto* group = GroupPool_.Allocate(state);

        auto& chunkPtrPtr = state->SmallBlobCache[Kind_].RankToCachedChunkPtrHead[rank];
        YTALLOC_PARANOID_ASSERT(*(chunkPtrPtr + 1) == reinterpret_cast<void*>(TThreadState::RightSentinel));
        group->PutMany(chunkPtrPtr - ChunksPerGroup + 1, ChunksPerGroup);
        chunkPtrPtr -= ChunksPerGroup;
#ifdef YTALLOC_PARANOID
        ::memset(chunkPtrPtr + 1, 0, sizeof(void*) * ChunksPerGroup);
        CanonizeChunkPtrs(state, rank);
#endif

        auto& groups = RankToChunkGroups_[rank];
        YTALLOC_PARANOID_ASSERT(!group->IsEmpty());
        groups.Put(state, group);
    }

    void MoveOneToGlobal(void* ptr, size_t rank)
    {
        auto* group = GroupPool_.Allocate(&GlobalShardedState_);
        group->PutOne(ptr);

        auto& groups = RankToChunkGroups_[rank];
        YTALLOC_PARANOID_ASSERT(!group->IsEmpty());
        groups.Put(&GlobalShardedState_, group);
    }

#ifdef YTALLOC_PARANOID
    void MoveAllToGlobal(TThreadState* state, size_t rank)
    {
        auto leftSentinelBorder = state->SmallBlobCache[Kind_].RankToCachedChunkLeftBorder[rank];
        auto rightSentinelBorder = state->SmallBlobCache[Kind_].RankToCachedChunkRightBorder[rank];

        auto& headPtr = state->SmallBlobCache[Kind_].RankToCachedChunkPtrHead[rank];
        auto& tailPtr = state->SmallBlobCache[Kind_].RankToCachedChunkPtrTail[rank];

        if (tailPtr == headPtr && !state->SmallBlobCache[Kind_].CachedChunkFull[rank]) {
            headPtr = leftSentinelBorder;
            return;
        }

        // (leftBorder, rightBorder]
        auto moveIntervalToGlobal = [=] (void** leftBorder, void** rightBorder) {
            while (true) {
                size_t count = 0;
                while (count < ChunksPerGroup && rightBorder != leftBorder) {
                    --rightBorder;
                    ++count;
                }

                if (count == 0) {
                    break;
                }

                auto* group = GroupPool_.Allocate(state);
                group->PutMany(rightBorder + 1, count);
                ::memset(rightBorder + 1, 0, sizeof(void*) * count);
                auto& groups = RankToChunkGroups_[rank];
                groups.Put(state, group);
            }
        };

        if (tailPtr >= headPtr) {
            moveIntervalToGlobal(tailPtr, rightSentinelBorder - 1);
            moveIntervalToGlobal(leftSentinelBorder, headPtr);
        } else {
            moveIntervalToGlobal(tailPtr, headPtr);
        }

        headPtr = leftSentinelBorder;
    }
#else
    void MoveAllToGlobal(TThreadState* state, size_t rank)
    {
        auto& chunkPtrPtr = state->SmallBlobCache[Kind_].RankToCachedChunkPtrHead[rank];
        while (true) {
            size_t count = 0;
            while (count < ChunksPerGroup && *chunkPtrPtr != reinterpret_cast<void*>(TThreadState::LeftSentinel)) {
                --chunkPtrPtr;
                ++count;
            }

            if (count == 0) {
                break;
            }

            auto* group = GroupPool_.Allocate(state);
            group->PutMany(chunkPtrPtr + 1, count);
            auto& groups = RankToChunkGroups_[rank];
            groups.Put(state, group);
        }
    }
#endif

private:
    const EAllocationKind Kind_;

    TGlobalShardedState GlobalShardedState_;
    TShardedSystemPool<TChunkGroup, GroupsBatchSize> GroupPool_;
    std::array<TShardedFreeList<TChunkGroup>, SmallRankCount> RankToChunkGroups_;
};

TExplicitlyConstructableSingleton<TEnumIndexedVector<EAllocationKind, TExplicitlyConstructableSingleton<TGlobalSmallChunkCache>>> GlobalSmallChunkCaches;

////////////////////////////////////////////////////////////////////////////////

class TSmallAllocator
{
public:
    template <EAllocationKind Kind>
    static Y_FORCE_INLINE void* Allocate(TMemoryTag tag, size_t rank)
    {
        auto* state = TThreadManager::FindThreadState();
        if (Y_LIKELY(state)) {
            return Allocate<Kind>(tag, rank, state);
        }
        auto size = SmallRankToSize[rank];
        return AllocateGlobal<Kind>(tag, rank, size);
    }

#ifdef YTALLOC_PARANOID
    template <EAllocationKind Kind>
    static Y_FORCE_INLINE void* Allocate(TMemoryTag tag, size_t rank, TThreadState* state)
    {
        auto& localCache = state->SmallBlobCache[Kind];
        auto& allocator = *(*SmallArenaAllocators)[Kind][rank];

        size_t size = SmallRankToSize[rank];
        StatisticsManager->IncrementTotalCounter<Kind>(state, tag, EBasicCounter::BytesAllocated, size);

        auto leftBorder = localCache.RankToCachedChunkLeftBorder[rank];
        auto rightBorder = localCache.RankToCachedChunkRightBorder[rank];

        void* result;
        while (true) {
            auto& chunkHeadPtr = localCache.RankToCachedChunkPtrHead[rank];
            auto& cachedHeadPtr = *(chunkHeadPtr + 1);
            auto* headPtr = cachedHeadPtr;

            auto& chunkTailPtr = localCache.RankToCachedChunkPtrTail[rank];
            auto& cachedTailPtr = *(chunkTailPtr + 1);
            auto* tailPtr = cachedTailPtr;

            auto& chunkFull = localCache.CachedChunkFull[rank];

            if (Y_LIKELY(chunkFull || headPtr != tailPtr)) {
                YTALLOC_PARANOID_ASSERT(tailPtr);
                cachedTailPtr = nullptr;
                ++chunkTailPtr;
                if (Y_LIKELY(chunkTailPtr + 1 == rightBorder)) {
                    chunkTailPtr = leftBorder;
                }

                chunkFull = false;
                result = tailPtr;
                PoisonUninitializedRange(result, size);
                allocator.UpdateChunkState(result, ESmallChunkState::Freed, ESmallChunkState::Allocated);
                break;
            }

            auto& globalCache = *(*GlobalSmallChunkCaches)[Kind];
            if (!globalCache.TryMoveGroupToLocal(state, rank)) {
                result = allocator.Allocate(size);
                break;
            }
        }

        if constexpr(Kind == EAllocationKind::Tagged) {
            allocator.SetMemoryTag(result, tag);
        }

        return result;
    }

    template <EAllocationKind Kind>
    static Y_FORCE_INLINE void Free(void* ptr)
    {
        auto rank = PtrToSmallRank(ptr);
        auto size = SmallRankToSize[rank];

        auto& allocator = *(*SmallArenaAllocators)[Kind][rank];

        auto tag = NullMemoryTag;
        if constexpr(Kind == EAllocationKind::Tagged) {
            tag = allocator.GetAndResetMemoryTag(ptr);
            YTALLOC_PARANOID_ASSERT(tag != NullMemoryTag);
        }

        allocator.UpdateChunkState(ptr, ESmallChunkState::Allocated, ESmallChunkState::Freed);
        PoisonFreedRange(ptr, size);

        auto* state = TThreadManager::FindThreadState();
        if (Y_UNLIKELY(!state)) {
            FreeGlobal<Kind>(tag, ptr, rank, size);
            return;
        }

        StatisticsManager->IncrementTotalCounter<Kind>(state, tag, EBasicCounter::BytesFreed, size);

        auto& localCache = state->SmallBlobCache[Kind];

        auto leftBorder = localCache.RankToCachedChunkLeftBorder[rank];
        auto rightBorder = localCache.RankToCachedChunkRightBorder[rank];

        while (true) {
            auto& chunkHeadPtr = localCache.RankToCachedChunkPtrHead[rank];
            auto& headPtr = *(chunkHeadPtr + 1);

            auto& chunkTailPtr = localCache.RankToCachedChunkPtrTail[rank];
            auto& chunkFull = localCache.CachedChunkFull[rank];

            if (Y_LIKELY(!chunkFull)) {
                headPtr = ptr;
                ++chunkHeadPtr;
                if (Y_LIKELY(chunkHeadPtr + 1 == rightBorder)) {
                    chunkHeadPtr = leftBorder;
                }
                chunkFull = (chunkHeadPtr == chunkTailPtr);
                break;
            }

            chunkHeadPtr = rightBorder - 1;
            chunkTailPtr = leftBorder;

            auto& globalCache = *(*GlobalSmallChunkCaches)[Kind];
            globalCache.MoveGroupToGlobal(state, rank);
        }
    }

#else

    template <EAllocationKind Kind>
    static Y_FORCE_INLINE void* Allocate(TMemoryTag tag, size_t rank, TThreadState* state)
    {
        size_t size = SmallRankToSize[rank];
        StatisticsManager->IncrementTotalCounter<Kind>(state, tag, EBasicCounter::BytesAllocated, size);

        auto& localCache = state->SmallBlobCache[Kind];
        auto& allocator = *(*SmallArenaAllocators)[Kind][rank];

        void* result;
        while (true) {
            auto& chunkPtr = localCache.RankToCachedChunkPtrHead[rank];
            auto& cachedPtr = *chunkPtr;
            auto* ptr = cachedPtr;
            if (Y_LIKELY(ptr != reinterpret_cast<void*>(TThreadState::LeftSentinel))) {
                --chunkPtr;
                result = ptr;
                allocator.UpdateChunkState(result, ESmallChunkState::Freed, ESmallChunkState::Allocated);
                PoisonUninitializedRange(result, size);
                break;
            }

            auto& globalCache = *(*GlobalSmallChunkCaches)[Kind];
            if (globalCache.TryMoveGroupToLocal(state, rank)) {
                continue;
            }

            auto count = allocator.PullMany(
                chunkPtr + 1,
                SmallRankBatchSize[rank]);
            chunkPtr += count;
        }

        if constexpr(Kind == EAllocationKind::Tagged) {
            allocator.SetMemoryTag(result, tag);
        }

        return result;
    }

    template <EAllocationKind Kind>
    static Y_FORCE_INLINE void Free(void* ptr)
    {
        auto rank = PtrToSmallRank(ptr);
        auto size = SmallRankToSize[rank];

        auto& allocator = *(*SmallArenaAllocators)[Kind][rank];

        auto tag = NullMemoryTag;
        if constexpr(Kind == EAllocationKind::Tagged) {
            tag = allocator.GetAndResetMemoryTag(ptr);
            YTALLOC_PARANOID_ASSERT(tag != NullMemoryTag);
        }

        allocator.UpdateChunkState(ptr, ESmallChunkState::Allocated, ESmallChunkState::Freed);
        PoisonFreedRange(ptr, size);

        auto* state = TThreadManager::FindThreadState();
        if (Y_UNLIKELY(!state)) {
            FreeGlobal<Kind>(tag, ptr, rank, size);
            return;
        }

        StatisticsManager->IncrementTotalCounter<Kind>(state, tag, EBasicCounter::BytesFreed, size);

        auto& localCache = state->SmallBlobCache[Kind];

        while (true) {
            auto& chunkPtrPtr = localCache.RankToCachedChunkPtrHead[rank];
            auto& chunkPtr = *(chunkPtrPtr + 1);
            if (Y_LIKELY(chunkPtr != reinterpret_cast<void*>(TThreadState::RightSentinel))) {
                chunkPtr = ptr;
                ++chunkPtrPtr;
                break;
            }

            auto& globalCache = *(*GlobalSmallChunkCaches)[Kind];
            globalCache.MoveGroupToGlobal(state, rank);
        }
    }
#endif

    static size_t GetAllocationSize(const void* ptr)
    {
        return SmallRankToSize[PtrToSmallRank(ptr)];
    }

    static size_t GetAllocationSize(size_t size)
    {
        return SmallRankToSize[SizeToSmallRank(size)];
    }

    static void PurgeCaches()
    {
        DoPurgeCaches<EAllocationKind::Untagged>();
        DoPurgeCaches<EAllocationKind::Tagged>();
    }

private:
    template <EAllocationKind Kind>
    static void DoPurgeCaches()
    {
        auto* state = TThreadManager::GetThreadStateChecked();
        for (size_t rank = 0; rank < SmallRankCount; ++rank) {
            (*GlobalSmallChunkCaches)[Kind]->MoveAllToGlobal(state, rank);
        }
    }

    template <EAllocationKind Kind>
    static void* AllocateGlobal(TMemoryTag tag, size_t rank, size_t size)
    {
        StatisticsManager->IncrementTotalCounter(tag, EBasicCounter::BytesAllocated, size);

        auto& allocator = *(*SmallArenaAllocators)[Kind][rank];
        auto* result = allocator.Allocate(size);

        if constexpr(Kind == EAllocationKind::Tagged) {
            allocator.SetMemoryTag(result, tag);
        }

        return result;
    }

    template <EAllocationKind Kind>
    static void FreeGlobal(TMemoryTag tag, void* ptr, size_t rank, size_t size)
    {
        StatisticsManager->IncrementTotalCounter(tag, EBasicCounter::BytesFreed, size);

        auto& globalCache = *(*GlobalSmallChunkCaches)[Kind];
        globalCache.MoveOneToGlobal(ptr, rank);
    }
};

////////////////////////////////////////////////////////////////////////////////
// Large blob allocator
//
// Like for small chunks, large blobs are grouped into arenas, where arena K handles
// blobs of size (2^{K-1},2^K]. Memory is mapped in extents of LargeExtentSize bytes.
// Each extent is split into segments of size 2^K (here segment is just a memory region, which may fully consist of
// unmapped pages). When a segment is actually allocated, it becomes a blob and a TLargeBlobHeader
// structure is placed at its start.
//
// When an extent is allocated, it is sliced into segments (not blobs, since no headers are placed and
// no memory is touched). These segments are put into disposed segments list.
//
// For each blob two separate sizes are maintained: BytesAcquired indicates the number of bytes
// acquired via madvise(MADV_POPULATE) from the system; BytesAllocated (<= BytesAcquired) corresponds
// to the number of bytes claimed by the user (including the header and page size alignment).
// If BytesAllocated == 0 then this blob is spare, i.e.
// was freed and remains cached for further possible reuse.
//
// When a new blob is being allocated, the allocator first tries to extract a spare blob. On success,
// its acquired size is extended (if needed); the acquired size never shrinks on allocation.
// If no spare blobs exist, a disposed segment is extracted and is turned into a blob (i.e.
// its header is initialized) and the needed number of bytes is acquired. If no disposed segments
// exist, then a new extent is allocated and sliced into segments.
//
// The above algorithm only claims memory from the system (by means of madvise(MADV_POPULATE));
// the reclaim is handled by a separate background mechanism. Two types of reclaimable memory
// regions are possible:
// * spare: these correspond to spare blobs; upon reclaiming this region becomes a disposed segment
// * overhead: these correspond to trailing parts of allocated blobs in [BytesAllocated, BytesAcquired) byte range
//
// Reclaiming spare blobs is easy as these are explicitly tracked by spare blob lists. To reclaim,
// we atomically extract a blob from a spare list, call madvise(MADV_FREE), and put the pointer to
// the disposed segment list.
//
// Reclaiming overheads is more complicated since (a) allocated blobs are never tracked directly and
// (b) reclaiming them may interfere with Allocate and Free.
//
// To overcome (a), for each extent we maintain a bitmap marking segments that are actually blobs
// (i.e. contain a header). (For simplicity and efficiency this bitmap is just a vector of bytes.)
// These flags are updated in Allocate/Free with appropriate memory ordering. Note that
// blobs are only disposed (and are turned into segments) by the background thread; if this
// thread discovers a segment that is marked as a blob, then it is safe to assume that this segment
// remains a blob unless the thread disposes it.
//
// To overcome (b), each large blob header maintains a spin lock. When blob B is extracted
// from a spare list in Allocate, an acquisition is tried. If successful, B is returned to the
// user. Otherwise it is assumed that B is currently being examined by the background
// reclaimer thread. Allocate then skips this blob and retries extraction; the problem is that
// since the spare list is basically a stack one cannot just push B back into the spare list.
// Instead, B is pushed into a special locked spare list. This list is purged by the background
// thread on each tick and its items are pushed back into the usual spare list.
//
// A similar trick is used by Free: when invoked for blob B its spin lock acquisition is first
// tried. Upon success, B is moved to the spare list. On failure, Free has to postpone this deallocation
// by moving B into the freed locked list. This list, similarly, is being purged by the background thread.
//
// It remains to explain how the background thread computes the number of bytes to be reclaimed from
// each arena. To this aim, we first compute the total number of reclaimable bytes.
// This is the sum of spare and overhead bytes in all arenas minus the number of unreclaimable bytes
// The latter grows linearly in the number of used bytes and is capped from below by a MinUnreclaimableLargeBytes;
// and from above by MaxUnreclaimableLargeBytes. SetLargeUnreclaimableCoeff and Set(Min|Max)LargeUnreclaimableBytes
// enable tuning these control knobs. The reclaimable bytes are being taken from arenas starting from those
// with the largest spare and overhead volumes.
//
// The above implies that each large blob contains a fixed-size header preceeding it.
// Hence ptr % PageSize == sizeof (TLargeBlobHeader) for each ptr returned by Allocate
// (since large blob sizes are larger than PageSize and are divisible by PageSize).
// For AllocatePageAligned, however, ptr must be divisible by PageSize. To handle such an allocation, we
// artificially increase its size and align the result of Allocate up to the next page boundary.
// When handling a deallocation, ptr is moved back by UnalignPtr (which is capable of dealing
// with both the results of Allocate and AllocatePageAligned).
// This technique applies to both large and huge blobs.

enum ELargeBlobState : ui64
{
    Allocated   = 0x6c6c61656772616cULL, // largeall
    Spare       = 0x727073656772616cULL, // largespr
    LockedSpare = 0x70736c656772616cULL, // largelsp
    LockedFreed = 0x72666c656772616cULL  // largelfr
};

// Every large blob (either tagged or not) is prepended with this header.
struct TLargeBlobHeader
    : public TFreeListItemBase<TLargeBlobHeader>
{
    TLargeBlobHeader(
        TLargeBlobExtent* extent,
        size_t bytesAcquired,
        size_t bytesAllocated,
        TMemoryTag tag)
        : Extent(extent)
        , BytesAcquired(bytesAcquired)
        , Tag(tag)
        , BytesAllocated(bytesAllocated)
        , State(ELargeBlobState::Allocated)
    { }

    TLargeBlobExtent* Extent;
    // Number of bytes in all acquired pages.
    size_t BytesAcquired;
    std::atomic<bool> Locked = false;
    TMemoryTag Tag = NullMemoryTag;
    // For spare blobs this is zero.
    // For allocated blobs this is the number of bytes requested by user (not including header of any alignment).
    size_t BytesAllocated;
    ELargeBlobState State;
    char Padding[12];
};

CHECK_HEADER_ALIGNMENT(TLargeBlobHeader)

struct TLargeBlobExtent
{
    TLargeBlobExtent(size_t segmentCount, char* ptr)
        : SegmentCount(segmentCount)
        , Ptr(ptr)
    { }

    size_t SegmentCount;
    char* Ptr;
    TLargeBlobExtent* NextExtent = nullptr;

    std::atomic<bool> DisposedFlags[0];
};

// A helper node that enables storing a number of extent's segments
// in a free list. Recall that segments themselves do not posses any headers.
struct TDisposedSegment
    : public TFreeListItemBase<TDisposedSegment>
{
    size_t Index;
    TLargeBlobExtent* Extent;
};

struct TLargeArena
{
    size_t Rank = 0;
    size_t SegmentSize = 0;

    TShardedFreeList<TLargeBlobHeader> SpareBlobs;
    TFreeList<TLargeBlobHeader> LockedSpareBlobs;
    TFreeList<TLargeBlobHeader> LockedFreedBlobs;
    TFreeList<TDisposedSegment> DisposedSegments;
    std::atomic<TLargeBlobExtent*> FirstExtent = nullptr;

    TLargeBlobExtent* CurrentOverheadScanExtent = nullptr;
    size_t CurrentOverheadScanSegment = 0;
};

template <bool Dumpable>
class TLargeBlobAllocator
{
public:
    TLargeBlobAllocator()
        : ZoneAllocator_(LargeZoneStart(Dumpable), LargeZoneEnd(Dumpable))
    {
        for (size_t rank = 0; rank < Arenas_.size(); ++rank) {
            auto& arena = Arenas_[rank];
            arena.Rank = rank;
            arena.SegmentSize = (1ULL << rank);
        }
    }

    void* Allocate(size_t size)
    {
        auto* state = TThreadManager::FindThreadState();
        return Y_LIKELY(state)
            ? DoAllocate(state, size)
            : DoAllocate(GlobalState.Get(), size);
    }

    void Free(void* ptr)
    {
        auto* state = TThreadManager::FindThreadState();
        if (Y_LIKELY(state)) {
            DoFree(state, ptr);
        } else {
            DoFree(GlobalState.Get(), ptr);
        }
    }

    static size_t GetAllocationSize(const void* ptr)
    {
        UnalignPtr<TLargeBlobHeader>(ptr);
        const auto* blob = PtrToHeader<TLargeBlobHeader>(ptr);
        return blob->BytesAllocated;
    }

    static size_t GetAllocationSize(size_t size)
    {
        return GetBlobAllocationSize<TLargeBlobHeader>(size);
    }

    void RunBackgroundTasks()
    {
        ReinstallLockedBlobs();
        ReclaimMemory();
    }

    void SetBacktraceProvider(TBacktraceProvider provider)
    {
        BacktraceProvider_.store(provider);
    }

private:
    template <class TState>
    void PopulateArenaPages(TState* state, TLargeArena* arena, void* ptr, size_t size)
    {
        MappedMemoryManager->Populate(ptr, size);
        StatisticsManager->IncrementLargeArenaCounter(state, arena->Rank, ELargeArenaCounter::BytesPopulated, size);
        StatisticsManager->IncrementLargeArenaCounter(state, arena->Rank, ELargeArenaCounter::PagesPopulated, size / PageSize);
        StatisticsManager->IncrementLargeArenaCounter(state, arena->Rank, ELargeArenaCounter::BytesCommitted, size);
        StatisticsManager->IncrementLargeArenaCounter(state, arena->Rank, ELargeArenaCounter::PagesCommitted, size / PageSize);
    }

    template <class TState>
    void ReleaseArenaPages(TState* state, TLargeArena* arena, void* ptr, size_t size)
    {
        MappedMemoryManager->Release(ptr, size);
        StatisticsManager->IncrementLargeArenaCounter(state, arena->Rank, ELargeArenaCounter::BytesReleased, size);
        StatisticsManager->IncrementLargeArenaCounter(state, arena->Rank, ELargeArenaCounter::PagesReleased, size / PageSize);
        StatisticsManager->IncrementLargeArenaCounter(state, arena->Rank, ELargeArenaCounter::BytesCommitted, -size);
        StatisticsManager->IncrementLargeArenaCounter(state, arena->Rank, ELargeArenaCounter::PagesCommitted, -size / PageSize);
    }

    bool TryLockBlob(TLargeBlobHeader* blob)
    {
        bool expected = false;
        return blob->Locked.compare_exchange_strong(expected, true);
    }

    void UnlockBlob(TLargeBlobHeader* blob)
    {
        blob->Locked.store(false);
    }

    template <class TState>
    void MoveBlobToSpare(TState* state, TLargeArena* arena, TLargeBlobHeader* blob, bool unlock)
    {
        auto rank = arena->Rank;
        auto size = blob->BytesAllocated;
        auto rawSize = GetRawBlobSize<TLargeBlobHeader>(size);
        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::BytesSpare, blob->BytesAcquired);
        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::BytesOverhead, -(blob->BytesAcquired - rawSize));
        blob->BytesAllocated = 0;
        if (unlock) {
            UnlockBlob(blob);
        } else {
            YTALLOC_VERIFY(!blob->Locked.load());
        }
        blob->State = ELargeBlobState::Spare;
        arena->SpareBlobs.Put(state, blob);
    }

    size_t GetBytesToReclaim(const std::array<TLocalLargeCounters, LargeRankCount>& arenaCounters)
    {
        size_t totalBytesAllocated = 0;
        size_t totalBytesFreed = 0;
        size_t totalBytesSpare = 0;
        size_t totalBytesOverhead = 0;
        for (size_t rank = 0; rank < Arenas_.size(); ++rank) {
            const auto& counters = arenaCounters[rank];
            totalBytesAllocated += counters[ELargeArenaCounter::BytesAllocated];
            totalBytesFreed += counters[ELargeArenaCounter::BytesFreed];
            totalBytesSpare += counters[ELargeArenaCounter::BytesSpare];
            totalBytesOverhead += counters[ELargeArenaCounter::BytesOverhead];
        }

        auto totalBytesUsed = totalBytesAllocated - totalBytesFreed;
        auto totalBytesReclaimable = totalBytesSpare + totalBytesOverhead;

        auto threshold = ClampVal(
            static_cast<size_t>(ConfigurationManager->GetLargeUnreclaimableCoeff() * totalBytesUsed),
            ConfigurationManager->GetMinLargeUnreclaimableBytes(),
            ConfigurationManager->GetMaxLargeUnreclaimableBytes());
        if (totalBytesReclaimable < threshold) {
            return 0;
        }

        auto bytesToReclaim = totalBytesReclaimable - threshold;
        return AlignUp(bytesToReclaim, PageSize);
    }

    void ReinstallLockedSpareBlobs(TLargeArena* arena)
    {
        auto* blob = arena->LockedSpareBlobs.ExtractAll();
        auto* state = TThreadManager::GetThreadStateChecked();

        size_t count = 0;
        while (blob) {
            auto* nextBlob = blob->Next.load();
            YTALLOC_VERIFY(!blob->Locked.load());
            AssertBlobState(blob, ELargeBlobState::LockedSpare);
            blob->State = ELargeBlobState::Spare;
            arena->SpareBlobs.Put(state, blob);
            blob = nextBlob;
            ++count;
        }

        if (count > 0) {
            YTALLOC_LOG_DEBUG("Locked spare blobs reinstalled (Rank: %d, Blobs: %zu)",
                arena->Rank,
                count);
        }
    }

    void ReinstallLockedFreedBlobs(TLargeArena* arena)
    {
        auto* state = TThreadManager::GetThreadStateChecked();
        auto* blob = arena->LockedFreedBlobs.ExtractAll();

        size_t count = 0;
        while (blob) {
            auto* nextBlob = blob->Next.load();
            AssertBlobState(blob, ELargeBlobState::LockedFreed);
            MoveBlobToSpare(state, arena, blob, false);
            ++count;
            blob = nextBlob;
        }

        if (count > 0) {
            YTALLOC_LOG_DEBUG("Locked freed blobs reinstalled (Rank: %d, Blobs: %zu)",
                arena->Rank,
                count);
        }
    }

    void ReclaimSpareMemory(TLargeArena* arena, ssize_t bytesToReclaim)
    {
        if (bytesToReclaim <= 0) {
            return;
        }

        auto rank = arena->Rank;
        auto* state = TThreadManager::GetThreadStateChecked();

        YTALLOC_LOG_DEBUG("Started processing spare memory in arena (BytesToReclaim: %zdM, Rank: %d)",
            bytesToReclaim / 1_MB,
            rank);

        size_t bytesReclaimed = 0;
        size_t blobsReclaimed = 0;
        while (bytesToReclaim > 0) {
            auto* blob = arena->SpareBlobs.ExtractRoundRobin(state);
            if (!blob) {
                break;
            }

            AssertBlobState(blob, ELargeBlobState::Spare);
            YTALLOC_VERIFY(blob->BytesAllocated == 0);

            auto bytesAcquired = blob->BytesAcquired;
            StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::BytesSpare, -bytesAcquired);
            bytesToReclaim -= bytesAcquired;
            bytesReclaimed += bytesAcquired;
            blobsReclaimed += 1;

            auto* extent = blob->Extent;
            auto* ptr = reinterpret_cast<char*>(blob);
            ReleaseArenaPages(
                state,
                arena,
                ptr,
                bytesAcquired);

            size_t segmentIndex = (ptr - extent->Ptr) / arena->SegmentSize;
            extent->DisposedFlags[segmentIndex].store(true, std::memory_order_relaxed);

            auto* disposedSegment = DisposedSegmentPool_.Allocate();
            disposedSegment->Index = segmentIndex;
            disposedSegment->Extent = extent;
            arena->DisposedSegments.Put(disposedSegment);
        }

        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::SpareBytesReclaimed, bytesReclaimed);

        YTALLOC_LOG_DEBUG("Finished processing spare memory in arena (Rank: %d, BytesReclaimed: %zdM, BlobsReclaimed: %zu)",
            arena->Rank,
            bytesReclaimed / 1_MB,
            blobsReclaimed);
    }

    void ReclaimOverheadMemory(TLargeArena* arena, ssize_t bytesToReclaim)
    {
        if (bytesToReclaim == 0) {
            return;
        }

        auto* state = TThreadManager::GetThreadStateChecked();
        auto rank = arena->Rank;

        YTALLOC_LOG_DEBUG("Started processing overhead memory in arena (BytesToReclaim: %zdM, Rank: %d)",
            bytesToReclaim / 1_MB,
            rank);

        size_t extentsTraversed = 0;
        size_t segmentsTraversed = 0;
        size_t bytesReclaimed = 0;

        bool restartedFromFirstExtent = false;
        auto& currentExtent = arena->CurrentOverheadScanExtent;
        auto& currentSegment = arena->CurrentOverheadScanSegment;
        while (bytesToReclaim > 0) {
            if (!currentExtent) {
                if (restartedFromFirstExtent) {
                    break;
                }
                currentExtent = arena->FirstExtent.load();
                if (!currentExtent) {
                    break;
                }
                restartedFromFirstExtent = true;
            }

            while (currentSegment  < currentExtent->SegmentCount && bytesToReclaim > 0) {
                ++segmentsTraversed;
                if (!currentExtent->DisposedFlags[currentSegment].load(std::memory_order_acquire)) {
                    auto* ptr = currentExtent->Ptr + currentSegment * arena->SegmentSize;
                    auto* blob = reinterpret_cast<TLargeBlobHeader*>(ptr);
                    YTALLOC_PARANOID_ASSERT(blob->Extent == currentExtent);
                    if (TryLockBlob(blob)) {
                        if (blob->BytesAllocated > 0) {
                            size_t rawSize = GetRawBlobSize<TLargeBlobHeader>(blob->BytesAllocated);
                            size_t bytesToRelease = blob->BytesAcquired - rawSize;
                            if (bytesToRelease > 0) {
                                ReleaseArenaPages(
                                    state,
                                    arena,
                                    ptr + blob->BytesAcquired - bytesToRelease,
                                    bytesToRelease);
                                StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::BytesOverhead, -bytesToRelease);
                                blob->BytesAcquired = rawSize;
                                bytesToReclaim -= bytesToRelease;
                                bytesReclaimed += bytesToRelease;
                            }
                        }
                        UnlockBlob(blob);
                    }
                }
                ++currentSegment;
            }

            ++extentsTraversed;
            currentSegment = 0;
            currentExtent = currentExtent->NextExtent;
        }

        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::OverheadBytesReclaimed, bytesReclaimed);

        YTALLOC_LOG_DEBUG("Finished processing overhead memory in arena (Rank: %d, Extents: %zu, Segments: %zu, BytesReclaimed: %zuM)",
            arena->Rank,
            extentsTraversed,
            segmentsTraversed,
            bytesReclaimed / 1_MB);
    }

    void ReinstallLockedBlobs()
    {
        for (auto& arena : Arenas_) {
            ReinstallLockedSpareBlobs(&arena);
            ReinstallLockedFreedBlobs(&arena);
        }
    }

    void ReclaimMemory()
    {
        auto arenaCounters = StatisticsManager->GetLargeArenaAllocationCounters();
        ssize_t bytesToReclaim = GetBytesToReclaim(arenaCounters);
        if (bytesToReclaim == 0) {
            return;
        }

        YTALLOC_LOG_DEBUG("Memory reclaim started (BytesToReclaim: %zdM)",
            bytesToReclaim / 1_MB);

        std::array<ssize_t, LargeRankCount * 2> bytesReclaimablePerArena;
        for (size_t rank = 0; rank < LargeRankCount; ++rank) {
            bytesReclaimablePerArena[rank * 2] = arenaCounters[rank][ELargeArenaCounter::BytesOverhead];
            bytesReclaimablePerArena[rank * 2 + 1] = arenaCounters[rank][ELargeArenaCounter::BytesSpare];
        }

        std::array<ssize_t, LargeRankCount * 2> bytesToReclaimPerArena{};
        while (bytesToReclaim > 0) {
            ssize_t maxBytes = std::numeric_limits<ssize_t>::min();
            int maxIndex = -1;
            for (int index = 0; index < LargeRankCount * 2; ++index) {
                if (bytesReclaimablePerArena[index] > maxBytes) {
                    maxBytes = bytesReclaimablePerArena[index];
                    maxIndex = index;
                }
            }

            if (maxIndex < 0) {
                break;
            }

            auto bytesToReclaimPerStep = std::min<ssize_t>({bytesToReclaim, maxBytes, 4_MB});
            if (bytesToReclaimPerStep < 0) {
                break;
            }

            bytesToReclaimPerArena[maxIndex] += bytesToReclaimPerStep;
            bytesReclaimablePerArena[maxIndex] -= bytesToReclaimPerStep;
            bytesToReclaim -= bytesToReclaimPerStep;
        }

        for (auto& arena : Arenas_) {
            auto rank = arena.Rank;
            ReclaimOverheadMemory(&arena, bytesToReclaimPerArena[rank * 2]);
            ReclaimSpareMemory(&arena, bytesToReclaimPerArena[rank * 2 + 1]);
        }

        YTALLOC_LOG_DEBUG("Memory reclaim finished");
    }

    template <class TState>
    void AllocateArenaExtent(TState* state, TLargeArena* arena)
    {
        auto rank = arena->Rank;
        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::ExtentsAllocated, 1);

        size_t segmentCount = LargeExtentSize / arena->SegmentSize;
        size_t extentHeaderSize = AlignUp(sizeof (TLargeBlobExtent) + sizeof (TLargeBlobExtent::DisposedFlags[0]) * segmentCount, PageSize);
        size_t allocationSize = extentHeaderSize + LargeExtentSize;

        auto* ptr = ZoneAllocator_.Allocate(allocationSize, MAP_NORESERVE);
        if (!Dumpable) {
            MappedMemoryManager->DontDump(ptr, allocationSize);
        }

        if (auto backtraceProvider = BacktraceProvider_.load()) {
            std::array<void*, MaxAllocationProfilingBacktraceDepth> frames;
            auto frameCount = backtraceProvider(
                frames.data(),
                MaxAllocationProfilingBacktraceDepth,
                3);
            MmapObservationManager->EnqueueEvent(allocationSize, frames, frameCount);
        }

        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::BytesMapped, allocationSize);
        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::PagesMapped, allocationSize / PageSize);

        auto* extent = static_cast<TLargeBlobExtent*>(ptr);
        MappedMemoryManager->Populate(ptr, extentHeaderSize);
        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::BytesPopulated, extentHeaderSize);
        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::PagesPopulated, extentHeaderSize / PageSize);
        StatisticsManager->IncrementSystemCounter(ESystemCounter::BytesAllocated, extentHeaderSize);

        new (extent) TLargeBlobExtent(segmentCount, static_cast<char*>(ptr) + extentHeaderSize);

        for (size_t index = 0; index < segmentCount; ++index) {
            auto* disposedSegment = DisposedSegmentPool_.Allocate();
            disposedSegment->Index = index;
            disposedSegment->Extent = extent;
            arena->DisposedSegments.Put(disposedSegment);
            extent->DisposedFlags[index].store(true);
        }

        auto* expectedFirstExtent = arena->FirstExtent.load();
        do {
            extent->NextExtent = expectedFirstExtent;
        } while (Y_UNLIKELY(!arena->FirstExtent.compare_exchange_weak(expectedFirstExtent, extent)));
    }

    template <class TState>
    void* DoAllocate(TState* state, size_t size)
    {
        auto rawSize = GetRawBlobSize<TLargeBlobHeader>(size);
        auto rank = GetLargeRank(rawSize);
        auto tag = ConfigurationManager->IsLargeArenaAllocationProfiled(rank)
            ? BacktraceManager->GetMemoryTagFromBacktrace(3)
            : TThreadManager::GetCurrentMemoryTag();
        auto& arena = Arenas_[rank];
        YTALLOC_PARANOID_ASSERT(rawSize <= arena.SegmentSize);

        TLargeBlobHeader* blob;
        while (true) {
            blob = arena.SpareBlobs.Extract(state);
            if (blob) {
                AssertBlobState(blob, ELargeBlobState::Spare);
                if (TryLockBlob(blob)) {
                    StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::BytesSpare, -blob->BytesAcquired);
                    if (blob->BytesAcquired < rawSize) {
                        PopulateArenaPages(
                            state,
                            &arena,
                            reinterpret_cast<char*>(blob) + blob->BytesAcquired,
                            rawSize - blob->BytesAcquired);
                        blob->BytesAcquired = rawSize;
                    } else {
                        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::BytesOverhead, blob->BytesAcquired - rawSize);
                    }
                    YTALLOC_PARANOID_ASSERT(blob->BytesAllocated == 0);
                    blob->BytesAllocated = size;
                    blob->Tag = tag;
                    blob->State = ELargeBlobState::Allocated;
                    UnlockBlob(blob);
                    break;
                } else {
                    blob->State = ELargeBlobState::LockedSpare;
                    arena.LockedSpareBlobs.Put(blob);
                }
            }

            auto* disposedSegment = arena.DisposedSegments.Extract();
            if (disposedSegment) {
                auto index = disposedSegment->Index;
                auto* extent = disposedSegment->Extent;
                DisposedSegmentPool_.Free(disposedSegment);

                auto* ptr = extent->Ptr + index * arena.SegmentSize;
                PopulateArenaPages(
                    state,
                    &arena,
                    ptr,
                    rawSize);

                blob = reinterpret_cast<TLargeBlobHeader*>(ptr);
                new (blob) TLargeBlobHeader(extent, rawSize, size, tag);

                extent->DisposedFlags[index].store(false, std::memory_order_release);

                break;
            }

            AllocateArenaExtent(state, &arena);
        }

        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::BlobsAllocated, 1);
        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::BytesAllocated, size);
        StatisticsManager->IncrementTotalCounter(state, tag, EBasicCounter::BytesAllocated, size);
        if (!Dumpable) {
            StatisticsManager->IncrementUndumpableCounter(state, EUndumpableCounter::BytesAllocated, size);
        }

        auto* result = HeaderToPtr(blob);
        YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(result) >= LargeZoneStart(Dumpable) && reinterpret_cast<uintptr_t>(result) < LargeZoneEnd(Dumpable));
        PoisonUninitializedRange(result, size);
        return result;
    }

    template <class TState>
    void DoFree(TState* state, void* ptr)
    {
        YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(ptr) >= LargeZoneStart(Dumpable) && reinterpret_cast<uintptr_t>(ptr) < LargeZoneEnd(Dumpable));

        auto* blob = PtrToHeader<TLargeBlobHeader>(ptr);
        AssertBlobState(blob, ELargeBlobState::Allocated);

        auto size = blob->BytesAllocated;
        PoisonFreedRange(ptr, size);

        auto rawSize = GetRawBlobSize<TLargeBlobHeader>(size);
        auto rank = GetLargeRank(rawSize);
        auto& arena = Arenas_[rank];
        YTALLOC_PARANOID_ASSERT(blob->BytesAcquired <= arena.SegmentSize);

        auto tag = blob->Tag;

        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::BlobsFreed, 1);
        StatisticsManager->IncrementLargeArenaCounter(state, rank, ELargeArenaCounter::BytesFreed, size);
        StatisticsManager->IncrementTotalCounter(state, tag, EBasicCounter::BytesFreed, size);
        if (!Dumpable) {
            StatisticsManager->IncrementUndumpableCounter(state, EUndumpableCounter::BytesFreed, size);
        }

        if (TryLockBlob(blob)) {
            MoveBlobToSpare(state, &arena, blob, true);
        } else {
            blob->State = ELargeBlobState::LockedFreed;
            arena.LockedFreedBlobs.Put(blob);
        }
    }

private:
    TZoneAllocator ZoneAllocator_;
    std::array<TLargeArena, LargeRankCount> Arenas_;

    static constexpr size_t DisposedSegmentsBatchSize = 1024;
    TSystemPool<TDisposedSegment, DisposedSegmentsBatchSize> DisposedSegmentPool_;

    std::atomic<TBacktraceProvider> BacktraceProvider_ = nullptr;
};

TExplicitlyConstructableSingleton<TLargeBlobAllocator<true>> DumpableLargeBlobAllocator;
TExplicitlyConstructableSingleton<TLargeBlobAllocator<false>> UndumpableLargeBlobAllocator;

////////////////////////////////////////////////////////////////////////////////
// Huge blob allocator
//
// Basically a wrapper for TZoneAllocator.

// Acts as a signature to detect broken headers.
enum class EHugeBlobState : ui64
{
    Allocated = 0x72666c656772616cULL // hugeallc
};

// Every huge blob (both tagged or not) is prepended with this header.
struct THugeBlobHeader
{
    THugeBlobHeader(TMemoryTag tag, size_t size, bool dumpable)
        : Tag(tag)
        , Size(size)
        , State(EHugeBlobState::Allocated)
        , Dumpable(dumpable)
    { }

    TMemoryTag Tag;
    size_t Size;
    EHugeBlobState State;
    bool Dumpable;
    char Padding[7];
};

CHECK_HEADER_ALIGNMENT(THugeBlobHeader)

class THugeBlobAllocator
{
public:
    THugeBlobAllocator()
        : ZoneAllocator_(HugeZoneStart, HugeZoneEnd)
    { }

    void* Allocate(size_t size, bool dumpable)
    {
        YTALLOC_VERIFY(size <= MaxAllocationSize);
        auto tag = TThreadManager::GetCurrentMemoryTag();
        auto rawSize = GetRawBlobSize<THugeBlobHeader>(size);
        auto* blob = static_cast<THugeBlobHeader*>(ZoneAllocator_.Allocate(rawSize, MAP_POPULATE));
        if (!dumpable) {
            MappedMemoryManager->DontDump(blob, rawSize);
        }
        new (blob) THugeBlobHeader(tag, size, dumpable);

        StatisticsManager->IncrementTotalCounter(tag, EBasicCounter::BytesAllocated, size);
        StatisticsManager->IncrementHugeCounter(EHugeCounter::BlobsAllocated, 1);
        StatisticsManager->IncrementHugeCounter(EHugeCounter::BytesAllocated, size);
        if (!dumpable) {
            StatisticsManager->IncrementHugeUndumpableCounter(EUndumpableCounter::BytesAllocated, size);
        }

        auto* result = HeaderToPtr(blob);
        PoisonUninitializedRange(result, size);
        return result;
    }

    void Free(void* ptr)
    {
        auto* blob = PtrToHeader<THugeBlobHeader>(ptr);
        AssertBlobState(blob, EHugeBlobState::Allocated);
        auto tag = blob->Tag;
        auto size = blob->Size;
        auto dumpable = blob->Dumpable;
        PoisonFreedRange(ptr, size);

        auto rawSize = GetRawBlobSize<THugeBlobHeader>(size);
        ZoneAllocator_.Free(blob, rawSize);

        StatisticsManager->IncrementTotalCounter(tag, EBasicCounter::BytesFreed, size);
        StatisticsManager->IncrementHugeCounter(EHugeCounter::BlobsFreed, 1);
        StatisticsManager->IncrementHugeCounter(EHugeCounter::BytesFreed, size);
        if (!dumpable) {
            StatisticsManager->IncrementHugeUndumpableCounter(EUndumpableCounter::BytesFreed, size);
        }
    }

    static size_t GetAllocationSize(const void* ptr)
    {
        UnalignPtr<THugeBlobHeader>(ptr);
        const auto* blob = PtrToHeader<THugeBlobHeader>(ptr);
        return blob->Size;
    }

    static size_t GetAllocationSize(size_t size)
    {
        return GetBlobAllocationSize<THugeBlobHeader>(size);
    }

private:
    TZoneAllocator ZoneAllocator_;
};

TExplicitlyConstructableSingleton<THugeBlobAllocator> HugeBlobAllocator;

////////////////////////////////////////////////////////////////////////////////
// A thunk to large and huge blob allocators

class TBlobAllocator
{
public:
    static void* Allocate(size_t size)
    {
        InitializeGlobals();
        bool dumpable = GetCurrentMemoryZone() != EMemoryZone::Undumpable;
        // NB: Account for the header. Also note that we may safely ignore the alignment since
        // HugeAllocationSizeThreshold is already page-aligned.
        if (Y_LIKELY(size < HugeAllocationSizeThreshold - sizeof(TLargeBlobHeader) - RightReadableAreaSize)) {
            void* result = dumpable
                ? DumpableLargeBlobAllocator->Allocate(size)
                : UndumpableLargeBlobAllocator->Allocate(size);
            YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(result) >= LargeZoneStart(dumpable) && reinterpret_cast<uintptr_t>(result) < LargeZoneEnd(dumpable));
            return result;
        } else {
            auto* result = HugeBlobAllocator->Allocate(size, dumpable);
            YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(result) >= HugeZoneStart && reinterpret_cast<uintptr_t>(result) < HugeZoneEnd);
            return result;
        }
    }

    static void Free(void* ptr)
    {
        InitializeGlobals();
        if (reinterpret_cast<uintptr_t>(ptr) < LargeZoneEnd(true)) {
            YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(ptr) >= LargeZoneStart(true) && reinterpret_cast<uintptr_t>(ptr) < LargeZoneEnd(true));
            UnalignPtr<TLargeBlobHeader>(ptr);
            DumpableLargeBlobAllocator->Free(ptr);
        } else if (reinterpret_cast<uintptr_t>(ptr) < LargeZoneEnd(false)) {
            YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(ptr) >= LargeZoneStart(false) && reinterpret_cast<uintptr_t>(ptr) < LargeZoneEnd(false));
            UnalignPtr<TLargeBlobHeader>(ptr);
            UndumpableLargeBlobAllocator->Free(ptr);
        } else if (reinterpret_cast<uintptr_t>(ptr) < HugeZoneEnd) {
            YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(ptr) >= HugeZoneStart && reinterpret_cast<uintptr_t>(ptr) < HugeZoneEnd);
            UnalignPtr<THugeBlobHeader>(ptr);
            HugeBlobAllocator->Free(ptr);
        } else {
            YTALLOC_TRAP("Wrong ptr passed to Free");
        }
    }
};

////////////////////////////////////////////////////////////////////////////////

Y_POD_THREAD(bool) CurrentThreadIsBackground;

// Base class for all background threads.
template <class T>
class TBackgroundThreadBase
{
public:
    TBackgroundThreadBase()
        : State_(new TState())
    {
        NThreading::RegisterAtForkHandlers(
            [=] { BeforeFork(); },
            [=] { AfterForkParent(); },
            [=] { AfterForkChild(); });
    }

    virtual ~TBackgroundThreadBase()
    {
        Stop();
    }

private:
    struct TState
        : public TSystemAllocatable
    {
        std::mutex StartStopMutex;
        std::optional<std::thread> Thread;

        std::mutex StopFlagMutex;
        std::condition_variable StopFlagVariable;
        std::chrono::system_clock::time_point LastInvocationTime;
        bool StopFlag = false;
        bool Paused = false;

        std::atomic<int> ForkDepth = 0;
        bool RestartAfterFork = false;
    };

    TState* State_;

private:
    void BeforeFork()
    {
        bool stopped = Stop();
        if (State_->ForkDepth++ == 0) {
            State_->RestartAfterFork = stopped;
        }
    }

    void AfterForkParent()
    {
        if (--State_->ForkDepth == 0) {
            if (State_->RestartAfterFork) {
                Start(false);
            }
        }
    }

    void AfterForkChild()
    {
        bool restart = State_->RestartAfterFork;
        State_ = new TState();
        if (restart) {
            Start(false);
        }
    }

    virtual void ThreadMain() = 0;

protected:
    void Start(bool fromAlloc)
    {
        std::unique_lock<std::mutex> guard(State_->StartStopMutex, std::defer_lock);
        if (fromAlloc) {
            if (!guard.try_lock()) {
                return;
            }

            if (State_->Paused) {
                return;
            }
        } else {
            guard.lock();
        }

        State_->Paused = false;
        if (State_->Thread) {
            return;
        }

        State_->StopFlag = false;

        State_->Thread.emplace([=] {
            CurrentThreadIsBackground = true;
            ThreadMain();
        });

        OnStart();
    }

    bool Stop()
    {
        std::unique_lock<std::mutex> guard(State_->StartStopMutex);

        State_->Paused = true;
        if (!State_->Thread) {
            return false;
        }

        std::unique_lock<std::mutex> flagGuard(State_->StopFlagMutex);
        State_->StopFlag = true;
        flagGuard.unlock();
        State_->StopFlagVariable.notify_one();

        State_->Thread->join();
        State_->Thread.reset();

        OnStop();

        return true;
    }

    bool IsDone(TDuration interval)
    {
        std::unique_lock<std::mutex> flagGuard(State_->StopFlagMutex);
        auto result = State_->StopFlagVariable.wait_until(
            flagGuard,
            State_->LastInvocationTime + std::chrono::microseconds(interval.MicroSeconds()),
            [&] { return State_->StopFlag; });
        State_->LastInvocationTime = std::chrono::system_clock::now();
        return result;
    }

    virtual void OnStart()
    { }

    virtual void OnStop()
    { }
};

////////////////////////////////////////////////////////////////////////////////

// Invokes madvise(MADV_STOCKPILE) periodically.
class TStockpileThread
    : public TBackgroundThreadBase<TStockpileThread>
{
public:
    explicit TStockpileThread(int index)
        : Index_(index)
    {
        Start(false);
    }

private:
    const int Index_;

    virtual void ThreadMain() override
    {
        TThread::SetCurrentThreadName(Sprintf("%s:%d", StockpileThreadName, Index_).c_str());

        while (!IsDone(ConfigurationManager->GetStockpileInterval())) {
            if (!MappedMemoryManager->Stockpile(ConfigurationManager->GetStockpileSize())) {
                // No use to proceed.
                YTALLOC_LOG_INFO("Stockpile call failed; terminating stockpile thread");
                break;
            }
        }
    }
};

// Manages a bunch of TStockpileThreads.
class TStockpileManager
{
public:
    void SpawnIfNeeded()
    {
        if (!ConfigurationManager->IsStockpileEnabled()) {
            return;
        }

        int threadCount = ConfigurationManager->GetStockpileThreadCount();
        while (static_cast<int>(Threads_.size()) > threadCount) {
            Threads_.pop_back();
        }
        while (static_cast<int>(Threads_.size()) < threadCount) {
            Threads_.push_back(std::make_unique<TStockpileThread>(static_cast<int>(Threads_.size())));
        }
    }

private:
    std::vector<std::unique_ptr<TStockpileThread>> Threads_;
};

TExplicitlyConstructableSingleton<TStockpileManager> StockpileManager;

////////////////////////////////////////////////////////////////////////////////

// Time to wait before re-spawning the thread after a fork.
static constexpr auto BackgroundThreadRespawnDelay = TDuration::Seconds(3);

// Runs basic background activities: reclaim, logging, profiling etc.
class TBackgroundThread
    : public TBackgroundThreadBase<TBackgroundThread>
{
public:
    bool IsStarted()
    {
        return Started_.load();
    }

    void SpawnIfNeeded()
    {
        if (CurrentThreadIsBackground) {
            return;
        }
        Start(true);
    }

private:
    std::atomic<bool> Started_ = false;

private:
    virtual void ThreadMain() override
    {
        TThread::SetCurrentThreadName(BackgroundThreadName);
        TimingManager->DisableForCurrentThread();
        MmapObservationManager->DisableForCurrentThread();

        while (!IsDone(BackgroundInterval)) {
            DumpableLargeBlobAllocator->RunBackgroundTasks();
            UndumpableLargeBlobAllocator->RunBackgroundTasks();
            MappedMemoryManager->RunBackgroundTasks();
            TimingManager->RunBackgroundTasks();
            MmapObservationManager->RunBackgroundTasks();
            StockpileManager->SpawnIfNeeded();
        }
    }

    virtual void OnStart() override
    {
        DoUpdateAllThreadsControlWord(true);
    }

    virtual void OnStop() override
    {
        DoUpdateAllThreadsControlWord(false);
    }

    void DoUpdateAllThreadsControlWord(bool started)
    {
        // Update threads' TLS.
        ThreadManager->EnumerateThreadStatesSync(
            [&] {
                Started_.store(started);
            },
            [&] (auto* state) {
                if (state->BackgroundThreadStarted) {
                    *state->BackgroundThreadStarted = started;
                }
            });
    }
};

TExplicitlyConstructableSingleton<TBackgroundThread> BackgroundThread;

////////////////////////////////////////////////////////////////////////////////

Y_FORCE_INLINE TThreadState* TThreadManager::GetThreadStateUnchecked()
{
    YTALLOC_PARANOID_ASSERT(ThreadState_);
    return ThreadState_;
}

Y_FORCE_INLINE TThreadState* TThreadManager::FindThreadState()
{
    if (Y_LIKELY(ThreadState_)) {
        return ThreadState_;
    }

    if (ThreadStateDestroyed_) {
        return nullptr;
    }

    InitializeGlobals();

    // InitializeGlobals must not allocate.
    Y_ABORT_UNLESS(!ThreadState_);
    ThreadState_ = ThreadManager->AllocateThreadState();
    (&ThreadControlWord_)->Parts.ThreadStateValid = true;

    return ThreadState_;
}

void TThreadManager::DestroyThread(void*)
{
    TSmallAllocator::PurgeCaches();

    TThreadState* state = ThreadState_;
    ThreadState_ = nullptr;
    ThreadStateDestroyed_ = true;
    (&ThreadControlWord_)->Parts.ThreadStateValid = false;

    {
        auto guard = GuardWithTiming(ThreadManager->ThreadRegistryLock_);
        state->AllocationProfilingEnabled = nullptr;
        state->BackgroundThreadStarted = nullptr;
        ThreadManager->UnrefThreadState(state);
    }
}

void TThreadManager::DestroyThreadState(TThreadState* state)
{
    StatisticsManager->AccumulateLocalCounters(state);
    ThreadRegistry_.Remove(state);
    ThreadStatePool_.Free(state);
}

void TThreadManager::AfterFork()
{
    auto guard = GuardWithTiming(ThreadRegistryLock_);
    ThreadRegistry_.Clear();
    TThreadState* state = ThreadState_;
    if (state) {
        ThreadRegistry_.PushBack(state);
    }
}

TThreadState* TThreadManager::AllocateThreadState()
{
    auto* state = ThreadStatePool_.Allocate();
    state->AllocationProfilingEnabled = &(*&ThreadControlWord_).Parts.AllocationProfilingEnabled;
    state->BackgroundThreadStarted = &(*&ThreadControlWord_).Parts.BackgroundThreadStarted;

    {
        auto guard = GuardWithTiming(ThreadRegistryLock_);
        // NB: These flags must be initialized under ThreadRegistryLock_; see EnumerateThreadStatesSync.
        *state->AllocationProfilingEnabled = ConfigurationManager->IsAllocationProfilingEnabled();
        *state->BackgroundThreadStarted = BackgroundThread->IsStarted();
        ThreadRegistry_.PushBack(state);
    }

    // Need to pass some non-null value for DestroyThread to be called.
    pthread_setspecific(ThreadDtorKey_, (void*)-1);

    return state;
}

////////////////////////////////////////////////////////////////////////////////

void InitializeGlobals()
{
    static std::once_flag Initialized;
    std::call_once(Initialized, [] () {
        LogManager.Construct();
        BacktraceManager.Construct();
        StatisticsManager.Construct();
        MappedMemoryManager.Construct();
        ThreadManager.Construct();
        GlobalState.Construct();
        DumpableLargeBlobAllocator.Construct();
        UndumpableLargeBlobAllocator.Construct();
        HugeBlobAllocator.Construct();
        ConfigurationManager.Construct();
        SystemAllocator.Construct();
        TimingManager.Construct();
        MmapObservationManager.Construct();
        StockpileManager.Construct();
        BackgroundThread.Construct();

        SmallArenaAllocators.Construct();
        auto constructSmallArenaAllocators = [&] (EAllocationKind kind, uintptr_t zonesStart) {
            for (size_t rank = 1; rank < SmallRankCount; ++rank) {
                (*SmallArenaAllocators)[kind][rank].Construct(kind, rank, zonesStart + rank * SmallZoneSize);
            }
        };
        constructSmallArenaAllocators(EAllocationKind::Untagged, UntaggedSmallZonesStart);
        constructSmallArenaAllocators(EAllocationKind::Tagged, TaggedSmallZonesStart);

        GlobalSmallChunkCaches.Construct();
        (*GlobalSmallChunkCaches)[EAllocationKind::Tagged].Construct(EAllocationKind::Tagged);
        (*GlobalSmallChunkCaches)[EAllocationKind::Untagged].Construct(EAllocationKind::Untagged);
    });
}

////////////////////////////////////////////////////////////////////////////////

void StartBackgroundThread()
{
    InitializeGlobals();
    BackgroundThread->SpawnIfNeeded();
}

////////////////////////////////////////////////////////////////////////////////

template <class... Ts>
Y_FORCE_INLINE void* AllocateSmallUntagged(size_t rank, Ts... args)
{
    auto* result = TSmallAllocator::Allocate<EAllocationKind::Untagged>(NullMemoryTag, rank, std::forward<Ts>(args)...);
    YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(result) >= MinUntaggedSmallPtr && reinterpret_cast<uintptr_t>(result) < MaxUntaggedSmallPtr);
    return result;
}

template <class... Ts>
Y_FORCE_INLINE void* AllocateSmallTagged(ui64 controlWord, size_t rank, Ts... args)
{
    auto tag = Y_UNLIKELY((controlWord & TThreadManager::AllocationProfilingEnabledControlWordMask) && ConfigurationManager->IsSmallArenaAllocationProfiled(rank))
        ? BacktraceManager->GetMemoryTagFromBacktrace(2)
        : static_cast<TMemoryTag>(controlWord & TThreadManager::MemoryTagControlWordMask);
    auto* result = TSmallAllocator::Allocate<EAllocationKind::Tagged>(tag, rank, std::forward<Ts>(args)...);
    YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(result) >= MinTaggedSmallPtr && reinterpret_cast<uintptr_t>(result) < MaxTaggedSmallPtr);
    return result;
}

Y_FORCE_INLINE void* AllocateInline(size_t size)
{
    size_t rank;
    if (Y_LIKELY(size <= 512)) {
        rank = SizeToSmallRank1[(size + 7) >> 3];
    } else if (Y_LIKELY(size < LargeAllocationSizeThreshold)) {
        rank = SizeToSmallRank2[(size - 1) >> 8];
    } else {
        StartBackgroundThread();
        return TBlobAllocator::Allocate(size);
    }

    auto controlWord = TThreadManager::GetThreadControlWord();
    if (Y_LIKELY(controlWord == TThreadManager::FastPathControlWord)) {
        return AllocateSmallUntagged(rank, TThreadManager::GetThreadStateUnchecked());
    }

    if (Y_UNLIKELY(!(controlWord & TThreadManager::BackgroundThreadStartedControlWorkMask))) {
        StartBackgroundThread();
    }

    if (!(controlWord & (TThreadManager::MemoryTagControlWordMask | TThreadManager::AllocationProfilingEnabledControlWordMask))) {
        return AllocateSmallUntagged(rank);
    } else {
        return AllocateSmallTagged(controlWord, rank);
    }
}

Y_FORCE_INLINE void* AllocateSmallInline(size_t rank)
{
    auto controlWord = TThreadManager::GetThreadControlWord();
    if (Y_LIKELY(controlWord == TThreadManager::FastPathControlWord)) {
        return AllocateSmallUntagged(rank, TThreadManager::GetThreadStateUnchecked());
    }

    if (!(controlWord & (TThreadManager::MemoryTagControlWordMask | TThreadManager::AllocationProfilingEnabledControlWordMask))) {
        return AllocateSmallUntagged(rank);
    } else {
        return AllocateSmallTagged(controlWord, rank);
    }
}

Y_FORCE_INLINE void* AllocatePageAlignedInline(size_t size)
{
    size = std::max(AlignUp(size, PageSize), PageSize);
    void* result = size >= LargeAllocationSizeThreshold
        ? AlignUp(TBlobAllocator::Allocate(size + PageSize), PageSize)
        : Allocate(size);
    YTALLOC_ASSERT(reinterpret_cast<uintptr_t>(result) % PageSize == 0);
    return result;
}

Y_FORCE_INLINE void FreeNonNullInline(void* ptr)
{
    YTALLOC_ASSERT(ptr);
    if (Y_LIKELY(reinterpret_cast<uintptr_t>(ptr) < UntaggedSmallZonesEnd)) {
        YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(ptr) >= MinUntaggedSmallPtr && reinterpret_cast<uintptr_t>(ptr) < MaxUntaggedSmallPtr);
        TSmallAllocator::Free<EAllocationKind::Untagged>(ptr);
    } else if (Y_LIKELY(reinterpret_cast<uintptr_t>(ptr) < TaggedSmallZonesEnd)) {
        YTALLOC_PARANOID_ASSERT(reinterpret_cast<uintptr_t>(ptr) >= MinTaggedSmallPtr && reinterpret_cast<uintptr_t>(ptr) < MaxTaggedSmallPtr);
        TSmallAllocator::Free<EAllocationKind::Tagged>(ptr);
    } else {
        TBlobAllocator::Free(ptr);
    }
}

Y_FORCE_INLINE void FreeInline(void* ptr)
{
    if (Y_LIKELY(ptr)) {
        FreeNonNullInline(ptr);
    }
}

Y_FORCE_INLINE size_t GetAllocationSizeInline(const void* ptr)
{
    if (Y_UNLIKELY(!ptr)) {
        return 0;
    }

    auto uintptr = reinterpret_cast<uintptr_t>(ptr);
    if (uintptr < UntaggedSmallZonesEnd) {
        YTALLOC_PARANOID_ASSERT(uintptr >= MinUntaggedSmallPtr && uintptr < MaxUntaggedSmallPtr);
        return TSmallAllocator::GetAllocationSize(ptr);
    } else if (uintptr < TaggedSmallZonesEnd) {
        YTALLOC_PARANOID_ASSERT(uintptr >= MinTaggedSmallPtr && uintptr < MaxTaggedSmallPtr);
        return TSmallAllocator::GetAllocationSize(ptr);
    } else if (uintptr < LargeZoneEnd(true)) {
        YTALLOC_PARANOID_ASSERT(uintptr >= LargeZoneStart(true) && uintptr < LargeZoneEnd(true));
        return TLargeBlobAllocator<true>::GetAllocationSize(ptr);
    } else if (uintptr < LargeZoneEnd(false)) {
        YTALLOC_PARANOID_ASSERT(uintptr >= LargeZoneStart(false) && uintptr < LargeZoneEnd(false));
        return TLargeBlobAllocator<false>::GetAllocationSize(ptr);
    } else if (uintptr < HugeZoneEnd) {
        YTALLOC_PARANOID_ASSERT(uintptr >= HugeZoneStart && uintptr < HugeZoneEnd);
        return THugeBlobAllocator::GetAllocationSize(ptr);
    } else {
        YTALLOC_TRAP("Wrong ptr passed to GetAllocationSizeInline");
    }
}

Y_FORCE_INLINE size_t GetAllocationSizeInline(size_t size)
{
    if (size <= LargeAllocationSizeThreshold) {
        return TSmallAllocator::GetAllocationSize(size);
    } else if (size <= HugeAllocationSizeThreshold) {
        return TLargeBlobAllocator<true>::GetAllocationSize(size);
    } else {
        return THugeBlobAllocator::GetAllocationSize(size);
    }
}

void EnableLogging(TLogHandler logHandler)
{
    InitializeGlobals();
    LogManager->EnableLogging(logHandler);
}

void SetBacktraceProvider(TBacktraceProvider provider)
{
    InitializeGlobals();
    BacktraceManager->SetBacktraceProvider(provider);
    DumpableLargeBlobAllocator->SetBacktraceProvider(provider);
    UndumpableLargeBlobAllocator->SetBacktraceProvider(provider);
}

void SetBacktraceFormatter(TBacktraceFormatter provider)
{
    InitializeGlobals();
    MmapObservationManager->SetBacktraceFormatter(provider);
}

void EnableStockpile()
{
    InitializeGlobals();
    ConfigurationManager->EnableStockpile();
}

void SetStockpileInterval(TDuration value)
{
    InitializeGlobals();
    ConfigurationManager->SetStockpileInterval(value);
}

void SetStockpileThreadCount(int value)
{
    InitializeGlobals();
    ConfigurationManager->SetStockpileThreadCount(value);
}

void SetStockpileSize(size_t value)
{
    InitializeGlobals();
    ConfigurationManager->SetStockpileSize(value);
}

void SetLargeUnreclaimableCoeff(double value)
{
    InitializeGlobals();
    ConfigurationManager->SetLargeUnreclaimableCoeff(value);
}

void SetTimingEventThreshold(TDuration value)
{
    InitializeGlobals();
    ConfigurationManager->SetTimingEventThreshold(value);
}

void SetMinLargeUnreclaimableBytes(size_t value)
{
    InitializeGlobals();
    ConfigurationManager->SetMinLargeUnreclaimableBytes(value);
}

void SetMaxLargeUnreclaimableBytes(size_t value)
{
    InitializeGlobals();
    ConfigurationManager->SetMaxLargeUnreclaimableBytes(value);
}

void SetAllocationProfilingEnabled(bool value)
{
    ConfigurationManager->SetAllocationProfilingEnabled(value);
}

void SetAllocationProfilingSamplingRate(double rate)
{
    ConfigurationManager->SetAllocationProfilingSamplingRate(rate);
}

void SetSmallArenaAllocationProfilingEnabled(size_t rank, bool value)
{
    ConfigurationManager->SetSmallArenaAllocationProfilingEnabled(rank, value);
}

void SetLargeArenaAllocationProfilingEnabled(size_t rank, bool value)
{
    ConfigurationManager->SetLargeArenaAllocationProfilingEnabled(rank, value);
}

void SetProfilingBacktraceDepth(int depth)
{
    ConfigurationManager->SetProfilingBacktraceDepth(depth);
}

void SetMinProfilingBytesUsedToReport(size_t size)
{
    ConfigurationManager->SetMinProfilingBytesUsedToReport(size);
}

void SetEnableEagerMemoryRelease(bool value)
{
    ConfigurationManager->SetEnableEagerMemoryRelease(value);
}

void SetEnableMadvisePopulate(bool value)
{
    ConfigurationManager->SetEnableMadvisePopulate(value);
}

TEnumIndexedVector<ETotalCounter, ssize_t> GetTotalAllocationCounters()
{
    InitializeGlobals();
    return StatisticsManager->GetTotalAllocationCounters();
}

TEnumIndexedVector<ESystemCounter, ssize_t> GetSystemAllocationCounters()
{
    InitializeGlobals();
    return StatisticsManager->GetSystemAllocationCounters();
}

TEnumIndexedVector<ESystemCounter, ssize_t> GetUndumpableAllocationCounters()
{
    InitializeGlobals();
    return StatisticsManager->GetUndumpableAllocationCounters();
}

TEnumIndexedVector<ESmallCounter, ssize_t> GetSmallAllocationCounters()
{
    InitializeGlobals();
    return StatisticsManager->GetSmallAllocationCounters();
}

TEnumIndexedVector<ESmallCounter, ssize_t> GetLargeAllocationCounters()
{
    InitializeGlobals();
    return StatisticsManager->GetLargeAllocationCounters();
}

std::array<TEnumIndexedVector<ESmallArenaCounter, ssize_t>, SmallRankCount> GetSmallArenaAllocationCounters()
{
    InitializeGlobals();
    return StatisticsManager->GetSmallArenaAllocationCounters();
}

std::array<TEnumIndexedVector<ELargeArenaCounter, ssize_t>, LargeRankCount> GetLargeArenaAllocationCounters()
{
    InitializeGlobals();
    return StatisticsManager->GetLargeArenaAllocationCounters();
}

TEnumIndexedVector<EHugeCounter, ssize_t> GetHugeAllocationCounters()
{
    InitializeGlobals();
    return StatisticsManager->GetHugeAllocationCounters();
}

std::vector<TProfiledAllocation> GetProfiledAllocationStatistics()
{
    InitializeGlobals();

    if (!ConfigurationManager->IsAllocationProfilingEnabled()) {
        return {};
    }

    std::vector<TMemoryTag> tags;
    tags.reserve(MaxCapturedAllocationBacktraces + 1);
    for (TMemoryTag tag = AllocationProfilingMemoryTagBase;
        tag < AllocationProfilingMemoryTagBase + MaxCapturedAllocationBacktraces;
        ++tag)
    {
        tags.push_back(tag);
    }
    tags.push_back(AllocationProfilingUnknownMemoryTag);

    std::vector<TEnumIndexedVector<EBasicCounter, ssize_t>> counters;
    counters.resize(tags.size());
    StatisticsManager->GetTaggedMemoryCounters(tags.data(), tags.size(), counters.data());

    std::vector<TProfiledAllocation> statistics;
    for (size_t index = 0; index < tags.size(); ++index) {
        if (counters[index][EBasicCounter::BytesUsed] < static_cast<ssize_t>(ConfigurationManager->GetMinProfilingBytesUsedToReport())) {
            continue;
        }
        auto tag = tags[index];
        auto optionalBacktrace = BacktraceManager->FindBacktrace(tag);
        if (!optionalBacktrace && tag != AllocationProfilingUnknownMemoryTag) {
            continue;
        }
        statistics.push_back(TProfiledAllocation{
            optionalBacktrace.value_or(TBacktrace()),
            counters[index]
        });
    }
    return statistics;
}

TEnumIndexedVector<ETimingEventType, TTimingEventCounters> GetTimingEventCounters()
{
    InitializeGlobals();
    return TimingManager->GetTimingEventCounters();
}

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT::NYTAlloc