summaryrefslogtreecommitdiffstats
path: root/lib/libc/stdlib/malloc.c
blob: 32497305b7980b1c37fb212a75b0b525e1e1d1f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
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
/*-
 * Copyright (C) 2006 Jason Evans <jasone@FreeBSD.org>.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice(s), this list of conditions and the following disclaimer as
 *    the first lines of this file unmodified other than the possible
 *    addition of one or more copyright notices.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice(s), this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *******************************************************************************
 *
 * Following is a brief list of features that distinguish this malloc
 * implementation:
 *
 *   + Multiple arenas are used if there are multiple CPUs, which reduces lock
 *     contention and cache sloshing.
 *
 *   + Cache line sharing between arenas is avoided for internal data
 *     structures.
 *
 *   + Memory is managed in chunks, rather than as individual pages.
 *
 *   + Allocations are region-based; internal region size is a discrete
 *     multiple of a quantum that is appropriate for alignment constraints.
 *     This applies to allocations that are up to half the chunk size.
 *
 *   + Coalescence of regions is delayed in order to reduce overhead and
 *     fragmentation.
 *
 *   + realloc() always moves data, in order to reduce fragmentation.
 *
 *   + Red-black trees are used to sort large regions.
 *
 *   + Data structures for huge allocations are stored separately from
 *     allocations, which reduces thrashing during low memory conditions.
 *
 *******************************************************************************
 */

/*
 *******************************************************************************
 *
 * Ring macros.
 *
 *******************************************************************************
 */

/* Ring definitions. */
#define	qr(a_type) struct {						\
	a_type *qre_next;						\
	a_type *qre_prev;						\
}

#define	qr_initializer {NULL, NULL}

/* Ring functions. */
#define	qr_new(a_qr, a_field) do {					\
	(a_qr)->a_field.qre_next = (a_qr);				\
	(a_qr)->a_field.qre_prev = (a_qr);				\
} while (0)

#define	qr_next(a_qr, a_field) ((a_qr)->a_field.qre_next)

#define	qr_prev(a_qr, a_field) ((a_qr)->a_field.qre_prev)

#define	qr_before_insert(a_qrelm, a_qr, a_field) do {			\
	(a_qr)->a_field.qre_prev = (a_qrelm)->a_field.qre_prev;		\
	(a_qr)->a_field.qre_next = (a_qrelm);				\
	(a_qr)->a_field.qre_prev->a_field.qre_next = (a_qr);		\
	(a_qrelm)->a_field.qre_prev = (a_qr);				\
} while (0)

#define	qr_after_insert(a_qrelm, a_qr, a_field) do {			\
	(a_qr)->a_field.qre_next = (a_qrelm)->a_field.qre_next;		\
	(a_qr)->a_field.qre_prev = (a_qrelm);				\
	(a_qr)->a_field.qre_next->a_field.qre_prev = (a_qr);		\
	(a_qrelm)->a_field.qre_next = (a_qr);				\
} while (0)

#define	qr_meld(a_qr_a, a_qr_b, a_type, a_field) do {			\
	a_type *t;							\
	(a_qr_a)->a_field.qre_prev->a_field.qre_next = (a_qr_b);	\
	(a_qr_b)->a_field.qre_prev->a_field.qre_next = (a_qr_a);	\
	t = (a_qr_a)->a_field.qre_prev;					\
	(a_qr_a)->a_field.qre_prev = (a_qr_b)->a_field.qre_prev;	\
	(a_qr_b)->a_field.qre_prev = t;					\
} while (0)

/* qr_meld() and qr_split() are functionally equivalent, so there's no need to
 * have two copies of the code. */
#define	qr_split(a_qr_a, a_qr_b, a_type, a_field)			\
	qr_meld((a_qr_a), (a_qr_b), a_type, a_field)

#define	qr_remove(a_qr, a_field) do {					\
	(a_qr)->a_field.qre_prev->a_field.qre_next			\
	    = (a_qr)->a_field.qre_next;					\
	(a_qr)->a_field.qre_next->a_field.qre_prev			\
	    = (a_qr)->a_field.qre_prev;					\
	(a_qr)->a_field.qre_next = (a_qr);				\
	(a_qr)->a_field.qre_prev = (a_qr);				\
} while (0)

#define	qr_foreach(var, a_qr, a_field)					\
	for ((var) = (a_qr);						\
	    (var) != NULL;						\
	    (var) = (((var)->a_field.qre_next != (a_qr))		\
	    ? (var)->a_field.qre_next : NULL))

#define	qr_reverse_foreach(var, a_qr, a_field)				\
	for ((var) = ((a_qr) != NULL) ? qr_prev(a_qr, a_field) : NULL;	\
	    (var) != NULL;						\
	    (var) = (((var) != (a_qr))					\
	    ? (var)->a_field.qre_prev : NULL))

/******************************************************************************/

#define	MALLOC_DEBUG

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "libc_private.h"
#ifdef MALLOC_DEBUG
#  define _LOCK_DEBUG
#endif
#include "spinlock.h"
#include "namespace.h"
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/stddef.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/tree.h>
#include <sys/uio.h>
#include <sys/ktrace.h> /* Must come after several other sys/ includes. */

#include <machine/atomic.h>
#include <machine/cpufunc.h>
#include <machine/vmparam.h>

#include <errno.h>
#include <limits.h>
#include <pthread.h>
#include <sched.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>

#include "un-namespace.h"

/*
 * Calculate statistics that can be used to get an idea of how well caching is
 * working.
 */
#define	MALLOC_STATS
#define	MALLOC_STATS_ARENAS

/*
 * Include redzones before/after every region, and check for buffer overflows.
 */
#define MALLOC_REDZONES
#ifdef MALLOC_REDZONES
#  define MALLOC_RED_2POW	4
#  define MALLOC_RED		((size_t)(1 << MALLOC_RED_2POW))
#endif

#ifndef MALLOC_DEBUG
#  ifndef NDEBUG
#    define NDEBUG
#  endif
#endif
#include <assert.h>

#ifdef MALLOC_DEBUG
   /* Disable inlining to make debugging easier. */
#  define __inline
#endif

/* Size of stack-allocated buffer passed to strerror_r(). */
#define	STRERROR_BUF 64

/* Number of quantum-spaced bins to store free regions in. */
#define	NBINS 128

/* Minimum alignment of allocations is 2^QUANTUM_2POW_MIN bytes. */
#ifdef __i386__
#  define QUANTUM_2POW_MIN	4
#  define SIZEOF_PTR		4
#  define USE_BRK
#endif
#ifdef __ia64__
#  define QUANTUM_2POW_MIN	4
#  define SIZEOF_PTR		8
#  define NO_TLS
#endif
#ifdef __alpha__
#  define QUANTUM_2POW_MIN	4
#  define SIZEOF_PTR		8
#  define NO_TLS
#endif
#ifdef __sparc64__
#  define QUANTUM_2POW_MIN	4
#  define SIZEOF_PTR		8
#  define NO_TLS
#endif
#ifdef __amd64__
#  define QUANTUM_2POW_MIN	4
#  define SIZEOF_PTR		8
#endif
#ifdef __arm__
#  define QUANTUM_2POW_MIN	3
#  define SIZEOF_PTR		4
#  define USE_BRK
#  define NO_TLS
#endif
#ifdef __powerpc__
#  define QUANTUM_2POW_MIN	4
#  define SIZEOF_PTR		4
#  define USE_BRK
#endif

/* We can't use TLS in non-PIC programs, since TLS relies on loader magic. */
#if (!defined(PIC) && !defined(NO_TLS))
#  define NO_TLS
#endif

/*
 * Size and alignment of memory chunks that are allocated by the OS's virtual
 * memory system.
 *
 * chunksize limits:
 *
 *   pagesize <= chunk_size <= 2^29
 */
#define	CHUNK_2POW_DEFAULT	24
#define	CHUNK_2POW_MAX		29

/*
 * Maximum size of L1 cache line.  This is used to avoid cache line aliasing,
 * so over-estimates are okay (up to a point), but under-estimates will
 * negatively affect performance.
 */
#define	CACHELINE_2POW 6
#define	CACHELINE ((size_t) (1 << CACHELINE_2POW))

/* Default number of regions to delay coalescence for. */
#define NDELAY 256

/******************************************************************************/

/*
 * Mutexes based on spinlocks.  We can't use normal pthread mutexes, because
 * they require malloc()ed memory.
 */
typedef struct {
	spinlock_t	lock;
} malloc_mutex_t;

static bool malloc_initialized = false;

/******************************************************************************/
/*
 * Statistics data structures.
 */

#ifdef MALLOC_STATS

typedef struct malloc_bin_stats_s malloc_bin_stats_t;
struct malloc_bin_stats_s {
	/*
	 * Number of allocation requests that corresponded to the size of this
	 * bin.
	 */
	uint64_t	nrequests;

	/*
	 * Number of best-fit allocations that were successfully serviced by
	 * this bin.
	 */
	uint64_t	nfit;

	/*
	 * Number of allocation requests that were successfully serviced by this
	 * bin, but that a smaller bin could have serviced.
	 */
	uint64_t	noverfit;

	/* High-water marks for this bin. */
	unsigned long	highcached;

	/*
	 * Current number of regions in this bin.  This number isn't needed
	 * during normal operation, so is maintained here in order to allow
	 * calculating the high water mark.
	 */
	unsigned	nregions;
};

typedef struct arena_stats_s arena_stats_t;
struct arena_stats_s {
	/* Number of times each function was called. */
	uint64_t	nmalloc;
	uint64_t	npalloc;
	uint64_t	ncalloc;
	uint64_t	ndalloc;
	uint64_t	nralloc;

	/* Number of region splits. */
	uint64_t	nsplit;

	/* Number of region coalescences. */
	uint64_t	ncoalesce;

	/* Bin statistics. */
	malloc_bin_stats_t bins[NBINS];

	/* Split statistics. */
	struct {
		/*
		 * Number of times a region is requested from the "split" field
		 * of the arena.
		 */
		uint64_t	nrequests;

		/*
		 * Number of times the "split" field of the arena successfully
		 * services requests.
		 */
		uint64_t	nserviced;
	}	split;

	/* Frag statistics. */
	struct {
		/*
		 * Number of times a region is cached in the "frag" field of
		 * the arena.
		 */
		uint64_t	ncached;

		/*
		 * Number of times a region is requested from the "frag" field
		 * of the arena.
		 */
		uint64_t	nrequests;

		/*
		 * Number of times the "frag" field of the arena successfully
		 * services requests.
		 */
		uint64_t	nserviced;
	}	frag;

	/* large and large_regions statistics. */
	struct {
		/*
		 * Number of allocation requests that were too large for a bin,
		 * but not large enough for a hugh allocation.
		 */
		uint64_t	nrequests;

		/*
		 * Number of best-fit allocations that were successfully
		 * serviced by large_regions.
		 */
		uint64_t	nfit;

		/*
		 * Number of allocation requests that were successfully serviced
		 * large_regions, but that a bin could have serviced.
		 */
		uint64_t	noverfit;

		/*
		 * High-water mark for large_regions (number of nodes in tree).
		 */
		unsigned long	highcached;

		/*
		 * Used only to store the current number of nodes, since this
		 * number isn't maintained anywhere else.
		 */
		unsigned long	curcached;
	}	large;

	/* Huge allocation statistics. */
	struct {
		/* Number of huge allocation requests. */
		uint64_t	nrequests;
	}	huge;
};

typedef struct chunk_stats_s chunk_stats_t;
struct chunk_stats_s {
	/* Number of chunks that were allocated. */
	uint64_t	nchunks;

	/* High-water mark for number of chunks allocated. */
	unsigned long	highchunks;

	/*
	 * Current number of chunks allocated.  This value isn't maintained for
	 * any other purpose, so keep track of it in order to be able to set
	 * highchunks.
	 */
	unsigned long	curchunks;
};

#endif /* #ifdef MALLOC_STATS */

/******************************************************************************/
/*
 * Chunk data structures.
 */

/* Needed by chunk data structures. */
typedef struct	arena_s arena_t;

/* Tree of chunks. */
typedef struct chunk_node_s chunk_node_t;
struct chunk_node_s {
	/*
	 * For an active chunk that is currently carved into regions by an
	 * arena allocator, this points to the arena that owns the chunk.  We
	 * set this pointer even for huge allocations, so that it is possible
	 * to tell whether a huge allocation was done on behalf of a user
	 * allocation request, or on behalf of an internal allocation request.
	 */
	arena_t *arena;

	/* Linkage for the chunk tree. */
	RB_ENTRY(chunk_node_s) link;

	/*
	 * Pointer to the chunk that this tree node is responsible for.  In some
	 * (but certainly not all) cases, this data structure is placed at the
	 * beginning of the corresponding chunk, so this field may point to this
	 * node.
	 */
	void	*chunk;

	/* Total chunk size. */
	size_t	size;

	/* Number of trailing bytes that are not used. */
	size_t	extra;
};
typedef struct chunk_tree_s chunk_tree_t;
RB_HEAD(chunk_tree_s, chunk_node_s);

/******************************************************************************/
/*
 * Region data structures.
 */

typedef struct region_s region_t;

/*
 * Tree of region headers, used for free regions that don't fit in the arena
 * bins.
 */
typedef struct region_node_s region_node_t;
struct region_node_s {
	RB_ENTRY(region_node_s)	link;
	region_t		*reg;
};
typedef struct region_tree_s region_tree_t;
RB_HEAD(region_tree_s, region_node_s);

typedef struct region_prev_s region_prev_t;
struct region_prev_s {
	uint32_t	size;
};

#define NEXT_SIZE_MASK 0x1fffffffU
typedef struct {
#ifdef MALLOC_REDZONES
	char		prev_red[MALLOC_RED];
#endif
	/*
	 * Typical bit pattern for bits:
	 *
	 *   pncsssss ssssssss ssssssss ssssssss
	 *
	 *   p : Previous free?
	 *   n : Next free?
	 *   c : Part of a range of contiguous allocations?
	 *   s : Next size (number of quanta).
	 *
	 * It's tempting to use structure bitfields here, but the compiler has
	 * to make assumptions that make the code slower than direct bit
	 * manipulations, and these fields are manipulated a lot.
	 */
	uint32_t	bits;

#ifdef MALLOC_REDZONES
	size_t		next_exact_size;
	char		next_red[MALLOC_RED];
#endif
} region_sep_t;

typedef struct region_next_small_sizer_s region_next_small_sizer_t;
struct region_next_small_sizer_s
{
	qr(region_t)	link;
};

typedef struct region_next_small_s region_next_small_t;
struct region_next_small_s
{
	qr(region_t)	link;

	/* Only accessed for delayed regions & footer invalid. */
	uint32_t	slot;
};

typedef struct region_next_large_s region_next_large_t;
struct region_next_large_s
{
	region_node_t	node;

	/* Use for LRU vs MRU tree ordering. */
	bool		lru;
};

typedef struct region_next_s region_next_t;
struct region_next_s {
	union {
		region_next_small_t	s;
		region_next_large_t	l;
	}	u;
};

/*
 * Region separator, including prev/next fields that are only accessible when
 * the neighboring regions are free.
 */
struct region_s {
	/* This field must only be accessed if sep.prev_free is true. */
	region_prev_t   prev;

	/* Actual region separator that is always present between regions. */
	region_sep_t    sep;

	/*
	 * These fields must only be accessed if sep.next_free or
	 * sep.next_contig is true. 
	 */
	region_next_t   next;
};

/* Small variant of region separator, only used for size calculations. */
typedef struct region_small_sizer_s region_small_sizer_t;
struct region_small_sizer_s {
	region_prev_t   prev;
	region_sep_t    sep;
	region_next_small_sizer_t   next;
};

/******************************************************************************/
/*
 * Arena data structures.
 */

typedef struct arena_bin_s arena_bin_t;
struct arena_bin_s {
	/*
	 * Link into ring before the oldest free region and just after the
	 * newest free region.
	 */
	region_t	regions;
};

struct arena_s {
#ifdef MALLOC_DEBUG
	uint32_t	magic;
#  define ARENA_MAGIC 0x947d3d24
#endif

	/* All operations on this arena require that mtx be locked. */
	malloc_mutex_t	mtx;

	/*
	 * bins is used to store rings of free regions of the following sizes,
	 * assuming a 16-byte quantum (sizes include region separators):
	 *
	 *   bins[i] | size |
	 *   --------+------+
	 *        0  |   32 |
	 *        1  |   48 |
	 *        2  |   64 |
	 *           :      :
	 *           :      :
	 *   --------+------+
	 */
	arena_bin_t	bins[NBINS];

	/*
	 * A bitmask that corresponds to which bins have elements in them.
	 * This is used when searching for the first bin that contains a free
	 * region that is large enough to service an allocation request.
	 */
#define	BINMASK_NELMS (NBINS / (sizeof(int) << 3))
	int		bins_mask[BINMASK_NELMS];

	/*
	 * Tree of free regions of the size range [bin_maxsize..~chunk).  These
	 * are sorted primarily by size, and secondarily by LRU.
	 */
	region_tree_t	large_regions;

	/*
	 * If not NULL, a region that is not stored in bins or large_regions.
	 * If large enough, this region is used instead of any region stored in
	 * bins or large_regions, in order to reduce the number of insert/remove
	 * operations, and in order to increase locality of allocation in
	 * common cases.
	 */
	region_t	*split;

	/*
	 * If not NULL, a region that is not stored in bins or large_regions.
	 * If large enough, this region is preferentially used for small
	 * allocations over any region in large_regions, split, or over-fit
	 * small bins.
	 */
	region_t	*frag;

	/* Tree of chunks that this arena currenly owns. */
	chunk_tree_t	chunks;
	unsigned	nchunks;

	/*
	 * FIFO ring of free regions for which coalescence is delayed.  A slot
	 * that contains NULL is considered empty.  opt_ndelay stores how many
	 * elements there are in the FIFO.
	 */
	region_t	**delayed;
	uint32_t	next_delayed; /* Next slot in delayed to use. */

#ifdef MALLOC_STATS
	/* Total byte count of allocated memory, not including overhead. */
	size_t		allocated;

	arena_stats_t stats;
#endif
};

/******************************************************************************/
/*
 * Data.
 */

/* Used as a special "nil" return value for malloc(0). */
static int		nil;

/* Number of CPUs. */
static unsigned		ncpus;

/* VM page size. */
static unsigned		pagesize;

/* Various quantum-related settings. */
static size_t		quantum;
static size_t		quantum_mask; /* (quantum - 1). */
static size_t		bin_shift;
static size_t		bin_maxsize;

/* Various chunk-related settings. */
static size_t		chunk_size;
static size_t		chunk_size_mask; /* (chunk_size - 1). */

/********/
/*
 * Chunks.
 */

/* Protects chunk-related data structures. */
static malloc_mutex_t	chunks_mtx;

/* Tree of chunks that are stand-alone huge allocations. */
static chunk_tree_t	huge;

#ifdef USE_BRK
/*
 * Try to use brk for chunk-size allocations, due to address space constraints.
 */
/* Result of first sbrk(0) call. */
static void		*brk_base;
/* Current end of brk, or ((void *)-1) if brk is exhausted. */
static void		*brk_prev;
/* Upper limit on brk addresses (may be an over-estimate). */
static void		*brk_max;
#endif

#ifdef MALLOC_STATS
/*
 * Byte counters for allocated/total space used by the chunks in the huge
 * allocations tree.
 */
static size_t		huge_allocated;
static size_t		huge_total;
#endif

/*
 * Tree of chunks that were previously allocated.  This is used when allocating
 * chunks, in an attempt to re-use address space.
 */
static chunk_tree_t	old_chunks;

/****************************/
/*
 * base (internal allocation).
 */

/*
 * Current chunk that is being used for internal memory allocations.  This
 * chunk is carved up in cacheline-size quanta, so that there is no chance of
 * false cach sharing. 
 * */
static void		*base_chunk;
static void		*base_next_addr;
static void		*base_past_addr; /* Addr immediately past base_chunk. */
static chunk_node_t	*base_chunk_nodes; /* LIFO cache of chunk nodes. */
static malloc_mutex_t	base_mtx;
#ifdef MALLOC_STATS
static uint64_t		base_total;
#endif

/********/
/*
 * Arenas.
 */

/* 
 * Arenas that are used to service external requests.  Not all elements of the
 * arenas array are necessarily used; arenas are created lazily as needed.
 */
static arena_t		**arenas;
static unsigned		narenas;
#ifndef NO_TLS
static unsigned		next_arena;
#endif
static malloc_mutex_t	arenas_mtx; /* Protects arenas initialization. */

#ifndef NO_TLS
/*
 * Map of pthread_self() --> arenas[???], used for selecting an arena to use
 * for allocations.
 */
static __thread arena_t *arenas_map;
#endif

#ifdef MALLOC_STATS
/* Chunk statistics. */
static chunk_stats_t	stats_chunks;
#endif

/*******************************/
/*
 * Runtime configuration options.
 */
const char	*_malloc_options;

static bool	opt_abort = true;
static bool	opt_junk = true;
static bool	opt_print_stats = false;
static size_t	opt_quantum_2pow = QUANTUM_2POW_MIN;
static size_t	opt_chunk_2pow = CHUNK_2POW_DEFAULT;
static bool	opt_utrace = false;
static bool	opt_sysv = false;
static bool	opt_xmalloc = false;
static bool	opt_zero = false;
static uint32_t	opt_ndelay = NDELAY;
static int32_t	opt_narenas_lshift = 0;

typedef struct {
	void	*p;
	size_t	s;
	void	*r;
} malloc_utrace_t;

#define	UTRACE(a, b, c)							\
	if (opt_utrace) {						\
		malloc_utrace_t ut = {a, b, c};				\
		utrace(&ut, sizeof(ut));				\
	}

/******************************************************************************/
/*
 * Begin function prototypes for non-inline static functions.
 */

static void	malloc_mutex_init(malloc_mutex_t *a_mutex);
static void	wrtmessage(const char *p1, const char *p2, const char *p3,
		const char *p4);
static void	malloc_printf(const char *format, ...);
static void	*base_alloc(size_t size);
static chunk_node_t *base_chunk_node_alloc(void);
static void	base_chunk_node_dealloc(chunk_node_t *node);
#ifdef MALLOC_STATS
static void	stats_merge(arena_t *arena, arena_stats_t *stats_arenas);
static void	stats_print(arena_stats_t *stats_arenas);
#endif
static void	*pages_map(void *addr, size_t size);
static void	pages_unmap(void *addr, size_t size);
static void	*chunk_alloc(size_t size);
static void	chunk_dealloc(void *chunk, size_t size);
static unsigned	arena_bins_search(arena_t *arena, size_t size);
static bool	arena_coalesce(arena_t *arena, region_t **reg, size_t size);
static void	arena_coalesce_hard(arena_t *arena, region_t *reg,
		region_t *next, size_t size, bool split_adjacent);
static void	arena_large_insert(arena_t *arena, region_t *reg, bool lru);
static void	arena_large_cache(arena_t *arena, region_t *reg, bool lru);
static void	arena_lru_cache(arena_t *arena, region_t *reg);
static void	arena_delay_cache(arena_t *arena, region_t *reg);
static region_t	*arena_split_reg_alloc(arena_t *arena, size_t size, bool fit);
static void	arena_reg_fit(arena_t *arena, size_t size, region_t *reg,
		bool restore_split);
static region_t	*arena_large_reg_alloc(arena_t *arena, size_t size, bool fit);
static region_t	*arena_chunk_reg_alloc(arena_t *arena, size_t size, bool fit);
static void	*arena_malloc(arena_t *arena, size_t size);
static void	*arena_palloc(arena_t *arena, size_t alignment, size_t size);
static void	*arena_calloc(arena_t *arena, size_t num, size_t size);
static size_t	arena_salloc(arena_t *arena, void *ptr);
#ifdef MALLOC_REDZONES
static void	redzone_check(void *ptr);
#endif
static void	arena_dalloc(arena_t *arena, void *ptr);
#ifdef NOT_YET
static void	*arena_ralloc(arena_t *arena, void *ptr, size_t size);
#endif
#ifdef MALLOC_STATS
static bool	arena_stats(arena_t *arena, size_t *allocated, size_t *total);
#endif
static bool	arena_new(arena_t *arena);
static arena_t	*arenas_extend(unsigned ind);
#ifndef NO_TLS
static arena_t	*choose_arena_hard(void);
#endif
static void	*huge_malloc(arena_t *arena, size_t size);
static void	huge_dalloc(void *ptr);
static void	*imalloc(arena_t *arena, size_t size);
static void	*ipalloc(arena_t *arena, size_t alignment, size_t size);
static void	*icalloc(arena_t *arena, size_t num, size_t size);
static size_t	isalloc(void *ptr);
static void	idalloc(void *ptr);
static void	*iralloc(arena_t *arena, void *ptr, size_t size);
#ifdef MALLOC_STATS
static void	istats(size_t *allocated, size_t *total);
#endif
static void	malloc_print_stats(void);
static bool	malloc_init_hard(void);

/*
 * End function prototypes.
 */
/******************************************************************************/
/*
 * Begin mutex.
 */

static void
malloc_mutex_init(malloc_mutex_t *a_mutex)
{
	static const spinlock_t lock = _SPINLOCK_INITIALIZER;

	a_mutex->lock = lock;
}

static __inline void
malloc_mutex_lock(malloc_mutex_t *a_mutex)
{

	if (__isthreaded)
		_SPINLOCK(&a_mutex->lock);
}

static __inline void
malloc_mutex_unlock(malloc_mutex_t *a_mutex)
{

	if (__isthreaded)
		_SPINUNLOCK(&a_mutex->lock);
}

/*
 * End mutex.
 */
/******************************************************************************/
/*
 * Begin Utility functions/macros.
 */

/* Return the chunk address for allocation address a. */
#define	CHUNK_ADDR2BASE(a)						\
	((void *) ((size_t) (a) & ~chunk_size_mask))

/* Return the chunk offset of address a. */
#define	CHUNK_ADDR2OFFSET(a)						\
	((size_t) (a) & chunk_size_mask)

/* Return the smallest chunk multiple that is >= s. */
#define	CHUNK_CEILING(s)						\
	(((s) + chunk_size_mask) & ~chunk_size_mask)

/* Return the smallest cacheline multiple that is >= s. */
#define	CACHELINE_CEILING(s)						\
	(((s) + (CACHELINE - 1)) & ~(CACHELINE - 1))

/* Return the smallest quantum multiple that is >= a. */
#define	QUANTUM_CEILING(a)						\
	(((a) + quantum_mask) & ~quantum_mask)

/* Return the offset within a chunk to the first region separator. */
#define	CHUNK_REG_OFFSET						\
	(QUANTUM_CEILING(sizeof(chunk_node_t) +				\
	    sizeof(region_sep_t)) - offsetof(region_t, next))

/*
 * Return how many bytes of usable space are needed for an allocation of size
 * bytes.  This value is not a multiple of quantum, since it doesn't include
 * the region separator.
 */
static __inline size_t
region_ceiling(size_t size)
{
	size_t quantum_size, min_reg_quantum;

	quantum_size = QUANTUM_CEILING(size + sizeof(region_sep_t));
	min_reg_quantum = QUANTUM_CEILING(sizeof(region_small_sizer_t));
	if (quantum_size >= min_reg_quantum)
		return (quantum_size);
	else
		return (min_reg_quantum);
}

static void
wrtmessage(const char *p1, const char *p2, const char *p3, const char *p4)
{

	_write(STDERR_FILENO, p1, strlen(p1));
	_write(STDERR_FILENO, p2, strlen(p2));
	_write(STDERR_FILENO, p3, strlen(p3));
	_write(STDERR_FILENO, p4, strlen(p4));
}

void	(*_malloc_message)(const char *p1, const char *p2, const char *p3,
	    const char *p4) = wrtmessage;

/*
 * Print to stderr in such a way as to (hopefully) avoid memory allocation.
 */
static void
malloc_printf(const char *format, ...)
{
	char buf[4096];
	va_list ap;

	va_start(ap, format);
	vsnprintf(buf, sizeof(buf), format, ap);
	va_end(ap);
	_malloc_message(buf, "", "", "");
}

/******************************************************************************/

static void *
base_alloc(size_t size)
{
	void *ret;
	size_t csize;

	/* Round size up to nearest multiple of the cacheline size. */
	csize = CACHELINE_CEILING(size);

	malloc_mutex_lock(&base_mtx);

	/* Make sure there's enough space for the allocation. */
	if ((size_t)base_next_addr + csize > (size_t)base_past_addr) {
		void *tchunk;
		size_t alloc_size;

		/*
		 * If chunk_size and opt_ndelay are sufficiently small and
		 * large, respectively, it's possible for an allocation request
		 * to exceed a single chunk here.  Deal with this, but don't
		 * worry about internal fragmentation.
		 */

		if (csize <= chunk_size)
			alloc_size = chunk_size;
		else
			alloc_size = CHUNK_CEILING(csize);

		tchunk = chunk_alloc(alloc_size);
		if (tchunk == NULL) {
			ret = NULL;
			goto RETURN;
		}
		base_chunk = tchunk;
		base_next_addr = (void *)base_chunk;
		base_past_addr = (void *)((size_t)base_chunk + alloc_size);
#ifdef MALLOC_STATS
		base_total += alloc_size;
#endif
	}

	/* Allocate. */
	ret = base_next_addr;
	base_next_addr = (void *)((size_t)base_next_addr + csize);

RETURN:
	malloc_mutex_unlock(&base_mtx);
	return (ret);
}

static chunk_node_t *
base_chunk_node_alloc(void)
{
	chunk_node_t *ret;

	malloc_mutex_lock(&base_mtx);
	if (base_chunk_nodes != NULL) {
		ret = base_chunk_nodes;
		base_chunk_nodes = *(chunk_node_t **)ret;
		malloc_mutex_unlock(&base_mtx);
	} else {
		malloc_mutex_unlock(&base_mtx);
		ret = (chunk_node_t *)base_alloc(sizeof(chunk_node_t));
	}

	return (ret);
}

static void
base_chunk_node_dealloc(chunk_node_t *node)
{

	malloc_mutex_lock(&base_mtx);
	*(chunk_node_t **)node = base_chunk_nodes;
	base_chunk_nodes = node;
	malloc_mutex_unlock(&base_mtx);
}

/******************************************************************************/

/*
 * Note that no bitshifting is done for booleans in any of the bitmask-based
 * flag manipulation functions that follow; test for non-zero versus zero.
 */

/**********************/
static __inline uint32_t
region_prev_free_get(region_sep_t *sep)
{

	return ((sep->bits) & 0x80000000U);
}

static __inline void
region_prev_free_set(region_sep_t *sep)
{

	sep->bits = ((sep->bits) | 0x80000000U);
}

static __inline void
region_prev_free_unset(region_sep_t *sep)
{

	sep->bits = ((sep->bits) & 0x7fffffffU);
}

/**********************/
static __inline uint32_t
region_next_free_get(region_sep_t *sep)
{

	return ((sep->bits) & 0x40000000U);
}

static __inline void
region_next_free_set(region_sep_t *sep)
{

	sep->bits = ((sep->bits) | 0x40000000U);
}

static __inline void
region_next_free_unset(region_sep_t *sep)
{

	sep->bits = ((sep->bits) & 0xbfffffffU);
}

/**********************/
static __inline uint32_t
region_next_contig_get(region_sep_t *sep)
{

	return ((sep->bits) & 0x20000000U);
}

static __inline void
region_next_contig_set(region_sep_t *sep)
{

	sep->bits = ((sep->bits) | 0x20000000U);
}

static __inline void
region_next_contig_unset(region_sep_t *sep)
{

	sep->bits = ((sep->bits) & 0xdfffffffU);
}

/********************/
static __inline size_t
region_next_size_get(region_sep_t *sep)
{

	return ((size_t) (((sep->bits) & NEXT_SIZE_MASK) << opt_quantum_2pow));
}

static __inline void
region_next_size_set(region_sep_t *sep, size_t size)
{
	uint32_t bits;

	assert(size % quantum == 0);

	bits = sep->bits;
	bits &= ~NEXT_SIZE_MASK;
	bits |= (((uint32_t) size) >> opt_quantum_2pow);

	sep->bits = bits;
}

#ifdef MALLOC_STATS
static void
stats_merge(arena_t *arena, arena_stats_t *stats_arenas)
{
	unsigned i;

	stats_arenas->nmalloc += arena->stats.nmalloc;
	stats_arenas->npalloc += arena->stats.npalloc;
	stats_arenas->ncalloc += arena->stats.ncalloc;
	stats_arenas->ndalloc += arena->stats.ndalloc;
	stats_arenas->nralloc += arena->stats.nralloc;

	stats_arenas->nsplit += arena->stats.nsplit;
	stats_arenas->ncoalesce += arena->stats.ncoalesce;

	/* Split. */
	stats_arenas->split.nrequests += arena->stats.split.nrequests;
	stats_arenas->split.nserviced += arena->stats.split.nserviced;

	/* Frag. */
	stats_arenas->frag.ncached += arena->stats.frag.ncached;
	stats_arenas->frag.nrequests += arena->stats.frag.nrequests;
	stats_arenas->frag.nserviced += arena->stats.frag.nserviced;

	/* Bins. */
	for (i = 0; i < NBINS; i++) {
		stats_arenas->bins[i].nrequests +=
		    arena->stats.bins[i].nrequests;
		stats_arenas->bins[i].nfit += arena->stats.bins[i].nfit;
		stats_arenas->bins[i].noverfit += arena->stats.bins[i].noverfit;
		if (arena->stats.bins[i].highcached
		    > stats_arenas->bins[i].highcached) {
		    stats_arenas->bins[i].highcached
			= arena->stats.bins[i].highcached;
		}
	}

	/* large and large_regions. */
	stats_arenas->large.nrequests += arena->stats.large.nrequests;
	stats_arenas->large.nfit += arena->stats.large.nfit;
	stats_arenas->large.noverfit += arena->stats.large.noverfit;
	if (arena->stats.large.highcached > stats_arenas->large.highcached)
		stats_arenas->large.highcached = arena->stats.large.highcached;
	stats_arenas->large.curcached += arena->stats.large.curcached;

	/* Huge allocations. */
	stats_arenas->huge.nrequests += arena->stats.huge.nrequests;
}

static void
stats_print(arena_stats_t *stats_arenas)
{
	unsigned i;

	malloc_printf("calls:\n");
	malloc_printf(" %13s%13s%13s%13s%13s\n", "nmalloc", "npalloc",
	    "ncalloc", "ndalloc", "nralloc");
	malloc_printf(" %13llu%13llu%13llu%13llu%13llu\n",
	    stats_arenas->nmalloc, stats_arenas->npalloc, stats_arenas->ncalloc,
	    stats_arenas->ndalloc, stats_arenas->nralloc);

	malloc_printf("region events:\n");
	malloc_printf(" %13s%13s\n", "nsplit", "ncoalesce");
	malloc_printf(" %13llu%13llu\n", stats_arenas->nsplit,
	    stats_arenas->ncoalesce);

	malloc_printf("cached split usage:\n");
	malloc_printf(" %13s%13s\n", "nrequests", "nserviced");
	malloc_printf(" %13llu%13llu\n", stats_arenas->split.nrequests,
	    stats_arenas->split.nserviced);

	malloc_printf("cached frag usage:\n");
	malloc_printf(" %13s%13s%13s\n", "ncached", "nrequests", "nserviced");
	malloc_printf(" %13llu%13llu%13llu\n", stats_arenas->frag.ncached,
	    stats_arenas->frag.nrequests, stats_arenas->frag.nserviced);

	malloc_printf("bins:\n");
	malloc_printf(" %4s%7s%13s%13s%13s%11s\n", "bin", 
	    "size", "nrequests", "nfit", "noverfit", "highcached");
	for (i = 0; i < NBINS; i++) {
		malloc_printf(
		    " %4u%7u%13llu%13llu%13llu%11lu\n",
		    i, ((i + bin_shift) << opt_quantum_2pow),
		    stats_arenas->bins[i].nrequests, stats_arenas->bins[i].nfit,
		    stats_arenas->bins[i].noverfit,
		    stats_arenas->bins[i].highcached);
	}

	malloc_printf("large:\n");
	malloc_printf(" %13s%13s%13s%13s%13s\n", "nrequests", "nfit",
	    "noverfit", "highcached", "curcached");
	malloc_printf(" %13llu%13llu%13llu%13lu%13lu\n",
	    stats_arenas->large.nrequests, stats_arenas->large.nfit,
	    stats_arenas->large.noverfit, stats_arenas->large.highcached,
	    stats_arenas->large.curcached);

	malloc_printf("huge\n");
	malloc_printf(" %13s\n", "nrequests");
	malloc_printf(" %13llu\n", stats_arenas->huge.nrequests);
}
#endif

/*
 * End Utility functions/macros.
 */
/******************************************************************************/
/*
 * Begin Mem.
 */

static __inline int
chunk_comp(chunk_node_t *a, chunk_node_t *b)
{
	int ret;

	assert(a != NULL);
	assert(b != NULL);

	if ((size_t) a->chunk < (size_t) b->chunk)
		ret = -1;
	else if (a->chunk == b->chunk)
		ret = 0;
	else
		ret = 1;

	return (ret);
}

/* Generate red-black tree code for chunks. */
RB_GENERATE_STATIC(chunk_tree_s, chunk_node_s, link, chunk_comp);

static __inline int
region_comp(region_node_t *a, region_node_t *b)
{
	int ret;
	size_t size_a, size_b;

	assert(a != NULL);
	assert(b != NULL);

	size_a = region_next_size_get(&a->reg->sep);
	size_b = region_next_size_get(&b->reg->sep);
	if (size_a < size_b)
		ret = -1;
	else if (size_a == size_b) {
		if (a == b) {
			/* Regions are equal with themselves. */
			ret = 0;
		} else {
			if (a->reg->next.u.l.lru) {
				/*
				 * Oldest region comes first (secondary LRU
				 * ordering).  a is guaranteed to be the search
				 * key, which is how we can enforce this
				 * secondary ordering.
				 */
				ret = 1;
			} else {
				/*
				 * Oldest region comes last (secondary MRU
				 * ordering).  a is guaranteed to be the search
				 * key, which is how we can enforce this
				 * secondary ordering.
				 */
				ret = -1;
			}
		}
	} else
		ret = 1;

	return (ret);
}

/* Generate red-black tree code for regions. */
RB_GENERATE_STATIC(region_tree_s, region_node_s, link, region_comp);

static void *
pages_map(void *addr, size_t size)
{
	void *ret;

#ifdef USE_BRK
AGAIN:
#endif
	/*
	 * We don't use MAP_FIXED here, because it can cause the *replacement*
	 * of existing mappings, and we only want to create new mappings.
	 */
	ret = mmap(addr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON,
	    -1, 0);
	assert(ret != NULL);

	if (ret == MAP_FAILED)
		ret = NULL;
	else if (addr != NULL && ret != addr) {
		/*
		 * We succeeded in mapping memory, but not in the right place.
		 */
		if (munmap(ret, size) == -1) {
			char buf[STRERROR_BUF];

			strerror_r(errno, buf, sizeof(buf));
			malloc_printf("%s: (malloc) Error in munmap(): %s\n",
			    _getprogname(), buf);
			if (opt_abort)
				abort();
		}
		ret = NULL;
	}
#ifdef USE_BRK
	else if ((size_t)ret >= (size_t)brk_base
	    && (size_t)ret < (size_t)brk_max) {
		/*
		 * We succeeded in mapping memory, but at a location that could
		 * be confused with brk.  Leave the mapping intact so that this
		 * won't ever happen again, then try again.
		 */
		assert(addr == NULL);
		goto AGAIN;
	}
#endif

	assert(ret == NULL || (addr == NULL && ret != addr)
	    || (addr != NULL && ret == addr));
	return (ret);
}

static void
pages_unmap(void *addr, size_t size)
{

	if (munmap(addr, size) == -1) {
		char buf[STRERROR_BUF];

		strerror_r(errno, buf, sizeof(buf));
		malloc_printf("%s: (malloc) Error in munmap(): %s\n",
		    _getprogname(), buf);
		if (opt_abort)
			abort();
	}
}

static void *
chunk_alloc(size_t size)
{
	void *ret, *chunk;
	chunk_node_t *tchunk, *delchunk;
	chunk_tree_t delchunks;

	assert(size != 0);
	assert(size % chunk_size == 0);

	RB_INIT(&delchunks);

	malloc_mutex_lock(&chunks_mtx);

	if (size == chunk_size) {
		/*
		 * Check for address ranges that were previously chunks and try
		 * to use them.
		 */

		tchunk = RB_MIN(chunk_tree_s, &old_chunks);
		while (tchunk != NULL) {
			/* Found an address range.  Try to recycle it. */

			chunk = tchunk->chunk;
			delchunk = tchunk;
			tchunk = RB_NEXT(chunk_tree_s, &old_chunks, delchunk);

			/*
			 * Remove delchunk from the tree, but keep track of the
			 * address.
			 */
			RB_REMOVE(chunk_tree_s, &old_chunks, delchunk);

			/*
			 * Keep track of the node so that it can be deallocated
			 * after chunks_mtx is released.
			 */
			RB_INSERT(chunk_tree_s, &delchunks, delchunk);

#ifdef USE_BRK
			if ((size_t)chunk >= (size_t)brk_base
			    && (size_t)chunk < (size_t)brk_max) {
				/* Re-use a previously freed brk chunk. */
				ret = chunk;
				goto RETURN;
			}
#endif
			if ((ret = pages_map(chunk, size)) != NULL) {
				/* Success. */
				goto RETURN;
			}
		}

#ifdef USE_BRK
		/*
		 * Try to create chunk-size allocations in brk, in order to
		 * make full use of limited address space.
		 */
		if (brk_prev != (void *)-1) {
			void *brk_cur;
			intptr_t incr;

			/*
			 * The loop is necessary to recover from races with
			 * other threads that are using brk for something other
			 * than malloc.
			 */
			do {
				/* Get the current end of brk. */
				brk_cur = sbrk(0);

				/*
				 * Calculate how much padding is necessary to
				 * chunk-align the end of brk.
				 */
				incr = (char *)chunk_size
				    - (char *)CHUNK_ADDR2OFFSET(brk_cur);
				if (incr == chunk_size) {
					ret = brk_cur;
				} else {
					ret = (char *)brk_cur + incr;
					incr += chunk_size;
				}

				brk_prev = sbrk(incr);
				if (brk_prev == brk_cur) {
					/* Success. */
					goto RETURN;
				}
			} while (brk_prev != (void *)-1);
		}
#endif
	}

	/*
	 * Try to over-allocate, but allow the OS to place the allocation
	 * anywhere.  Beware of size_t wrap-around.
	 */
	if (size + chunk_size > size) {
		if ((ret = pages_map(NULL, size + chunk_size)) != NULL) {
			size_t offset = CHUNK_ADDR2OFFSET(ret);

			/*
			 * Success.  Clean up unneeded leading/trailing space.
			 */
			if (offset != 0) {
				/* Leading space. */
				pages_unmap(ret, chunk_size - offset);

				ret = (void *) ((size_t) ret + (chunk_size -
				    offset));

				/* Trailing space. */
				pages_unmap((void *) ((size_t) ret + size),
				    offset);
			} else {
				/* Trailing space only. */
				pages_unmap((void *) ((size_t) ret + size),
				    chunk_size);
			}
			goto RETURN;
		}
	}

	/* All strategies for allocation failed. */
	ret = NULL;
RETURN:
#ifdef MALLOC_STATS
	if (ret != NULL) {
		stats_chunks.nchunks += (size / chunk_size);
		stats_chunks.curchunks += (size / chunk_size);
	}
	if (stats_chunks.curchunks > stats_chunks.highchunks)
		stats_chunks.highchunks = stats_chunks.curchunks;
#endif
	malloc_mutex_unlock(&chunks_mtx);

	/*
	 * Deallocation of the chunk nodes must be done after releasing
	 * chunks_mtx, in case deallocation causes a chunk to be unmapped.
	 */
	tchunk = RB_MIN(chunk_tree_s, &delchunks);
	while (tchunk != NULL) {
		delchunk = tchunk;
		tchunk = RB_NEXT(chunk_tree_s, &delchunks, delchunk);
		RB_REMOVE(chunk_tree_s, &delchunks, delchunk);
		base_chunk_node_dealloc(delchunk);
	}

	assert(CHUNK_ADDR2BASE(ret) == ret);
	return (ret);
}

static void
chunk_dealloc(void *chunk, size_t size)
{

	assert(chunk != NULL);
	assert(CHUNK_ADDR2BASE(chunk) == chunk);
	assert(size != 0);
	assert(size % chunk_size == 0);

	if (size == chunk_size) {
		chunk_node_t *node;

		node = base_chunk_node_alloc();

		malloc_mutex_lock(&chunks_mtx);
		if (node != NULL) {
			/*
			 * Create a record of this chunk before deallocating
			 * it, so that the address range can be recycled if
			 * memory usage increases later on.
			 */
			node->arena = NULL;
			node->chunk = chunk;
			node->size = size;
			node->extra = 0;

			RB_INSERT(chunk_tree_s, &old_chunks, node);
		}
		malloc_mutex_unlock(&chunks_mtx);
	}

#ifdef USE_BRK
	if ((size_t)chunk >= (size_t)brk_base
	    && (size_t)chunk < (size_t)brk_max)
		madvise(chunk, size, MADV_FREE);
	else
#endif
		pages_unmap(chunk, size);

#ifdef MALLOC_STATS
	malloc_mutex_lock(&chunks_mtx);
	stats_chunks.curchunks -= (size / chunk_size);
	malloc_mutex_unlock(&chunks_mtx);
#endif
}

/******************************************************************************/
/*
 * arena.
 */

static __inline void
arena_mask_set(arena_t *arena, unsigned bin)
{
	unsigned elm, bit;

	assert(bin < NBINS);

	elm = bin / (sizeof(int) << 3);
	bit = bin - (elm * (sizeof(int) << 3));
	assert((arena->bins_mask[elm] & (1 << bit)) == 0);
	arena->bins_mask[elm] |= (1 << bit);
}

static __inline void
arena_mask_unset(arena_t *arena, unsigned bin)
{
	unsigned elm, bit;

	assert(bin < NBINS);

	elm = bin / (sizeof(int) << 3);
	bit = bin - (elm * (sizeof(int) << 3));
	assert((arena->bins_mask[elm] & (1 << bit)) != 0);
	arena->bins_mask[elm] ^= (1 << bit);
}

static unsigned
arena_bins_search(arena_t *arena, size_t size)
{
	unsigned ret, minbin, i;
	int bit;

	assert(QUANTUM_CEILING(size) == size);
	assert((size >> opt_quantum_2pow) >= bin_shift);

	if (size > bin_maxsize) {
		ret = UINT_MAX;
		goto RETURN;
	}

	minbin = (size >> opt_quantum_2pow) - bin_shift;
	assert(minbin < NBINS);
	for (i = minbin / (sizeof(int) << 3); i < BINMASK_NELMS; i++) {
		bit = ffs(arena->bins_mask[i]
		    & (UINT_MAX << (minbin % (sizeof(int) << 3))));
		if (bit != 0) {
			/* Usable allocation found. */
			ret = (i * (sizeof(int) << 3)) + bit - 1;
#ifdef MALLOC_STATS
			if (ret == minbin)
				arena->stats.bins[minbin].nfit++;
			else
				arena->stats.bins[ret].noverfit++;
#endif
			goto RETURN;
		}
	}

	ret = UINT_MAX;
RETURN:
	return (ret);
}

static __inline void
arena_delayed_extract(arena_t *arena, region_t *reg)
{

	if (region_next_contig_get(&reg->sep)) {
		uint32_t slot;

		/* Extract this region from the delayed FIFO. */
		assert(region_next_free_get(&reg->sep) == false);

		slot = reg->next.u.s.slot;
		assert(arena->delayed[slot] == reg);
		arena->delayed[slot] = NULL;
	}
#ifdef MALLOC_DEBUG
	else {
		region_t *next;

		assert(region_next_free_get(&reg->sep));

		next = (region_t *) &((char *) reg)
		    [region_next_size_get(&reg->sep)];
		assert(region_prev_free_get(&next->sep));
	}
#endif
}

static __inline void
arena_bin_extract(arena_t *arena, unsigned bin, region_t *reg)
{
	arena_bin_t *tbin;

	assert(bin < NBINS);

	tbin = &arena->bins[bin];

	assert(qr_next(&tbin->regions, next.u.s.link) != &tbin->regions);
#ifdef MALLOC_DEBUG
	{
		region_t *next;

		next = (region_t *) &((char *) reg)
		    [region_next_size_get(&reg->sep)];
		if (region_next_free_get(&reg->sep)) {
			assert(region_prev_free_get(&next->sep));
			assert(region_next_size_get(&reg->sep)
			    == next->prev.size);
		} else {
			assert(region_prev_free_get(&next->sep) == false);
		}
	}
#endif
	assert(region_next_size_get(&reg->sep)
	    == ((bin + bin_shift) << opt_quantum_2pow));

	qr_remove(reg, next.u.s.link);
#ifdef MALLOC_STATS
	arena->stats.bins[bin].nregions--;
#endif
	if (qr_next(&tbin->regions, next.u.s.link) == &tbin->regions)
		arena_mask_unset(arena, bin);

	arena_delayed_extract(arena, reg);
}

static __inline void
arena_extract(arena_t *arena, region_t *reg)
{
	size_t size;

	assert(region_next_free_get(&reg->sep));
#ifdef MALLOC_DEBUG
	{
		region_t *next;

		next = (region_t *)&((char *)reg)
		    [region_next_size_get(&reg->sep)];
	}
#endif

	assert(reg != arena->split);
	assert(reg != arena->frag);
	if ((size = region_next_size_get(&reg->sep)) <= bin_maxsize) {
		arena_bin_extract(arena, (size >> opt_quantum_2pow) - bin_shift,
		    reg);
	} else {
		RB_REMOVE(region_tree_s, &arena->large_regions,
		    &reg->next.u.l.node);
#ifdef MALLOC_STATS
		arena->stats.large.curcached--;
#endif
	}
}

/* Try to coalesce reg with its neighbors.  Return NULL if coalescing fails. */
static bool
arena_coalesce(arena_t *arena, region_t **reg, size_t size)
{
	bool ret;
	region_t *prev, *treg, *next, *nextnext;
	size_t tsize, prev_size, next_size;

	ret = false;

	treg = *reg;

	/*
	 * Keep track of the size while coalescing, then just set the size in
	 * the header/footer once at the end of coalescing.
	 */
	assert(size == region_next_size_get(&(*reg)->sep));
	tsize = size;

	next = (region_t *)&((char *)treg)[tsize];
	assert(region_next_free_get(&treg->sep));
	assert(region_prev_free_get(&next->sep));
	assert(region_next_size_get(&treg->sep) == next->prev.size);

	if (region_prev_free_get(&treg->sep)) {
		prev_size = treg->prev.size;
		prev = (region_t *)&((char *)treg)[-prev_size];
		assert(region_next_free_get(&prev->sep));

		arena_extract(arena, prev);

		tsize += prev_size;

		treg = prev;

#ifdef MALLOC_STATS
		arena->stats.ncoalesce++;
#endif
		ret = true;
	}
	assert(region_prev_free_get(&treg->sep) == false);

	if (region_next_free_get(&next->sep)) {
		next_size = region_next_size_get(&next->sep);
		nextnext = (region_t *)&((char *)next)[next_size];
		assert(region_prev_free_get(&nextnext->sep));

		assert(region_next_size_get(&next->sep) == nextnext->prev.size);

		arena_extract(arena, next);

		assert(region_next_size_get(&next->sep) == nextnext->prev.size);

		tsize += next_size;

#ifdef MALLOC_STATS
		if (ret == false)
			arena->stats.ncoalesce++;
#endif
		ret = true;

		next = (region_t *)&((char *)treg)[tsize];
	}
	assert(region_next_free_get(&next->sep) == false);

	/* Update header/footer. */
	if (ret) {
		region_next_size_set(&treg->sep, tsize);
		next->prev.size = tsize;
	}

	/*
	 * Now that coalescing with adjacent free regions is done, we need to
	 * try to coalesce with "split" and "frag".  Those two regions are
	 * marked as allocated, which is why this takes special effort.  There
	 * are seven possible cases, but we want to make the (hopefully) common
	 * case of no coalescence fast, so the checks are optimized for that
	 * case.  The seven cases are:
	 *
	 *   /------\
	 * 0 | treg | No coalescence needed.  Make this case fast.
	 *   \------/
	 *
	 *   /------+------\
	 * 1 | frag | treg |
	 *   \------+------/
	 *
	 *   /------+------\
	 * 2 | treg | frag |
	 *   \------+------/
	 *
	 *   /-------+------\
	 * 3 | split | treg |
	 *   \-------+------/
	 *
	 *   /------+-------\
	 * 4 | treg | split |
	 *   \------+-------/
	 *
	 *   /------+------+-------\
	 * 5 | frag | treg | split |
	 *   \------+------+-------/
	 *
	 *   /-------+------+------\
	 * 6 | split | treg | frag |
	 *   \-------+------+------/
	 */

	if (arena->split == NULL) {
		/* Cases 3-6 ruled out. */
	} else if ((size_t)next < (size_t)arena->split) {
		/* Cases 3-6 ruled out. */
	} else {
		region_t *split_next;
		size_t split_size;

		split_size = region_next_size_get(&arena->split->sep);
		split_next = (region_t *)&((char *)arena->split)[split_size];

		if ((size_t)split_next < (size_t)treg) {
			/* Cases 3-6 ruled out. */
		} else {
			/*
			 * Split is adjacent to treg.  Take the slow path and
			 * coalesce.
			 */

			arena_coalesce_hard(arena, treg, next, tsize, true);

			treg = NULL;
#ifdef MALLOC_STATS
			if (ret == false)
				arena->stats.ncoalesce++;
#endif
			ret = true;
			goto RETURN;
		}
	}

	/* If we get here, then cases 3-6 have been ruled out. */
	if (arena->frag == NULL) {
		/* Cases 1-6 ruled out. */
	} else if ((size_t)next < (size_t)arena->frag) {
		/* Cases 1-6 ruled out. */
	} else {
		region_t *frag_next;
		size_t frag_size;

		frag_size = region_next_size_get(&arena->frag->sep);
		frag_next = (region_t *)&((char *)arena->frag)[frag_size];

		if ((size_t)frag_next < (size_t)treg) {
			/* Cases 1-6 ruled out. */
		} else {
			/*
			 * Frag is adjacent to treg.  Take the slow path and
			 * coalesce.
			 */

			arena_coalesce_hard(arena, treg, next, tsize, false);

			treg = NULL;
#ifdef MALLOC_STATS
			if (ret == false)
				arena->stats.ncoalesce++;
#endif
			ret = true;
			goto RETURN;
		}
	}

	/* If we get here, no coalescence with "split" or "frag" was needed. */

	/* Finish updating header. */
	region_next_contig_unset(&treg->sep);

	assert(region_next_free_get(&treg->sep));
	assert(region_prev_free_get(&next->sep));
	assert(region_prev_free_get(&treg->sep) == false);
	assert(region_next_free_get(&next->sep) == false);

RETURN:
	if (ret)
		*reg = treg;
	return (ret);
}

/*
 * arena_coalesce() calls this function if it determines that a region needs to
 * be coalesced with "split" and/or "frag".
 */
static void
arena_coalesce_hard(arena_t *arena, region_t *reg, region_t *next, size_t size,
    bool split_adjacent)
{
	bool frag_adjacent;

	assert(next == (region_t *)&((char *)reg)[size]);
	assert(region_next_free_get(&reg->sep));
	assert(region_next_size_get(&reg->sep) == size);
	assert(region_prev_free_get(&next->sep));
	assert(next->prev.size == size);

	if (split_adjacent == false)
		frag_adjacent = true;
	else if (arena->frag != NULL) {
		/* Determine whether frag will be coalesced with. */

		if ((size_t)next < (size_t)arena->frag)
			frag_adjacent = false;
		else {
			region_t *frag_next;
			size_t frag_size;

			frag_size = region_next_size_get(&arena->frag->sep);
			frag_next = (region_t *)&((char *)arena->frag)
			    [frag_size];

			if ((size_t)frag_next < (size_t)reg)
				frag_adjacent = false;
			else
				frag_adjacent = true;
		}
	} else
		frag_adjacent = false;

	if (split_adjacent && frag_adjacent) {
		region_t *a;
		size_t a_size, b_size;

		/* Coalesce all three regions. */

		if (arena->frag == next)
			a = arena->split;
		else {
			a = arena->frag;
			arena->split = a;
		}
		arena->frag = NULL;

		a_size = region_next_size_get(&a->sep);
		assert(a_size == (size_t)reg - (size_t)a);

		b_size = region_next_size_get(&next->sep);

		region_next_size_set(&a->sep, a_size + size + b_size);
		assert(region_next_free_get(&a->sep) == false);
	} else {
		/* Coalesce two regions. */

		if (split_adjacent) {
			size += region_next_size_get(&arena->split->sep);
			if (arena->split == next) {
				/* reg comes before split. */
				region_next_size_set(&reg->sep, size);
				
				assert(region_next_free_get(&reg->sep));
				region_next_free_unset(&reg->sep);

				arena->split = reg;
			} else {
				/* reg comes after split. */
				region_next_size_set(&arena->split->sep, size);

				assert(region_next_free_get(&arena->split->sep)
				    == false);

				assert(region_prev_free_get(&next->sep));
				region_prev_free_unset(&next->sep);
			}
		} else {
			assert(frag_adjacent);
			size += region_next_size_get(&arena->frag->sep);
			if (arena->frag == next) {
				/* reg comes before frag. */
				region_next_size_set(&reg->sep, size);

				assert(region_next_free_get(&reg->sep));
				region_next_free_unset(&reg->sep);

				arena->frag = reg;
			} else {
				/* reg comes after frag. */
				region_next_size_set(&arena->frag->sep, size);

				assert(region_next_free_get(&arena->frag->sep)
				    == false);

				assert(region_prev_free_get(&next->sep));
				region_prev_free_unset(&next->sep);
			}
		}
	}
}

static __inline void
arena_bin_append(arena_t *arena, unsigned bin, region_t *reg)
{
	arena_bin_t *tbin;

	assert(bin < NBINS);
	assert((region_next_size_get(&reg->sep) >> opt_quantum_2pow)
	    >= bin_shift);
	assert(region_next_size_get(&reg->sep)
	    == ((bin + bin_shift) << opt_quantum_2pow));

	tbin = &arena->bins[bin];

	if (qr_next(&tbin->regions, next.u.s.link) == &tbin->regions)
		arena_mask_set(arena, bin);

	qr_new(reg, next.u.s.link);
	qr_before_insert(&tbin->regions, reg, next.u.s.link);
#ifdef MALLOC_STATS
	arena->stats.bins[bin].nregions++;

	if (arena->stats.bins[bin].nregions
	    > arena->stats.bins[bin].highcached) {
		arena->stats.bins[bin].highcached
		    = arena->stats.bins[bin].nregions;
	}
#endif
}

static __inline void
arena_bin_push(arena_t *arena, unsigned bin, region_t *reg)
{
	arena_bin_t *tbin;

	assert(bin < NBINS);
	assert((region_next_size_get(&reg->sep) >> opt_quantum_2pow)
	    >= bin_shift);
	assert(region_next_size_get(&reg->sep)
	    == ((bin + bin_shift) << opt_quantum_2pow));

	tbin = &arena->bins[bin];

	if (qr_next(&tbin->regions, next.u.s.link) == &tbin->regions)
		arena_mask_set(arena, bin);

	region_next_contig_unset(&reg->sep);
	qr_new(reg, next.u.s.link);
	qr_after_insert(&tbin->regions, reg, next.u.s.link);
#ifdef MALLOC_STATS
	arena->stats.bins[bin].nregions++;

	if (arena->stats.bins[bin].nregions
	    > arena->stats.bins[bin].highcached) {
		arena->stats.bins[bin].highcached
		    = arena->stats.bins[bin].nregions;
	}
#endif
}

static __inline region_t *
arena_bin_pop(arena_t *arena, unsigned bin)
{
	region_t *ret;
	arena_bin_t *tbin;

	assert(bin < NBINS);

	tbin = &arena->bins[bin];

	assert(qr_next(&tbin->regions, next.u.s.link) != &tbin->regions);

	ret = qr_next(&tbin->regions, next.u.s.link);
	assert(region_next_size_get(&ret->sep)
	    == ((bin + bin_shift) << opt_quantum_2pow));
	qr_remove(ret, next.u.s.link);
#ifdef MALLOC_STATS
	arena->stats.bins[bin].nregions--;
#endif
	if (qr_next(&tbin->regions, next.u.s.link) == &tbin->regions)
		arena_mask_unset(arena, bin);

	arena_delayed_extract(arena, ret);

	if (region_next_free_get(&ret->sep)) {
		region_t *next;

		/* Non-delayed region. */
		region_next_free_unset(&ret->sep);

		next = (region_t *)&((char *)ret)
		    [(bin + bin_shift) << opt_quantum_2pow];
		assert(next->prev.size == region_next_size_get(&ret->sep));
		assert(region_prev_free_get(&next->sep));
		region_prev_free_unset(&next->sep);
	}

	return (ret);
}

static void
arena_large_insert(arena_t *arena, region_t *reg, bool lru)
{

	assert(region_next_free_get(&reg->sep));
#ifdef MALLOC_DEBUG
	{
		region_t *next;

		next = (region_t *)&((char *)reg)
		    [region_next_size_get(&reg->sep)];
		assert(region_prev_free_get(&next->sep));
		assert(next->prev.size == region_next_size_get(&reg->sep));
	}
#endif

	/* Coalescing should have already been done. */
	assert(arena_coalesce(arena, &reg, region_next_size_get(&reg->sep))
	    == false);

	if (region_next_size_get(&reg->sep) < chunk_size
	    - (CHUNK_REG_OFFSET + offsetof(region_t, next))) {
		/*
		 * Make sure not to cache a large region with the nextContig
		 * flag set, in order to simplify the logic that determines
		 * whether a region needs to be extracted from "delayed".
		 */
		region_next_contig_unset(&reg->sep);

		/* Store the region in the large_regions tree. */
		reg->next.u.l.node.reg = reg;
		reg->next.u.l.lru = lru;

		RB_INSERT(region_tree_s, &arena->large_regions,
		    &reg->next.u.l.node);
#ifdef MALLOC_STATS
		arena->stats.large.curcached++;
		if (arena->stats.large.curcached
		    > arena->stats.large.highcached) {
			arena->stats.large.highcached
			    = arena->stats.large.curcached;
		}
#endif
	} else {
		chunk_node_t *node;

		/*
		 * This region now spans an entire chunk. Deallocate the chunk.
		 *
		 * Note that it is possible for allocation of a large region
		 * from a pristine chunk, followed by deallocation of the
		 * region, can cause the chunk to immediately be unmapped.
		 * This isn't ideal, but 1) such scenarios seem unlikely, and
		 * 2) delaying coalescence for large regions could cause
		 * excessive fragmentation for common scenarios.
		 */

		node = (chunk_node_t *)CHUNK_ADDR2BASE(reg);
		RB_REMOVE(chunk_tree_s, &arena->chunks, node);
		arena->nchunks--;
		assert(node->chunk == (chunk_node_t *)node);
		chunk_dealloc(node->chunk, chunk_size);
	}
}

static void
arena_large_cache(arena_t *arena, region_t *reg, bool lru)
{
	size_t size;

	/* Try to coalesce before storing this region anywhere. */
	size = region_next_size_get(&reg->sep);
	if (arena_coalesce(arena, &reg, size)) {
		if (reg == NULL) {
			/* Region no longer needs cached. */
			return;
		}
		size = region_next_size_get(&reg->sep);
	}

	arena_large_insert(arena, reg, lru);
}

static void
arena_lru_cache(arena_t *arena, region_t *reg)
{
	size_t size;

	assert(region_next_free_get(&reg->sep));
#ifdef MALLOC_DEBUG
	{
		region_t *next;

		next = (region_t *)&((char *)reg)
		    [region_next_size_get(&reg->sep)];
		assert(region_prev_free_get(&next->sep));
		assert(next->prev.size == region_next_size_get(&reg->sep));
	}
#endif
	assert(region_next_size_get(&reg->sep) % quantum == 0);
	assert(region_next_size_get(&reg->sep)
	    >= QUANTUM_CEILING(sizeof(region_small_sizer_t)));

	size = region_next_size_get(&reg->sep);
	if (size <= bin_maxsize) {
		arena_bin_append(arena, (size >> opt_quantum_2pow) - bin_shift,
		    reg);
	} else
		arena_large_cache(arena, reg, true);
}

static __inline void
arena_mru_cache(arena_t *arena, region_t *reg, size_t size)
{

	assert(region_next_free_get(&reg->sep));
#ifdef MALLOC_DEBUG
	{
		region_t *next;

		next = (region_t *)&((char *)reg)
		    [region_next_size_get(&reg->sep)];
		assert(region_prev_free_get(&next->sep));
		assert(next->prev.size == region_next_size_get(&reg->sep));
	}
#endif
	assert(region_next_size_get(&reg->sep) % quantum == 0);
	assert(region_next_size_get(&reg->sep)
	    >= QUANTUM_CEILING(sizeof(region_small_sizer_t)));
	assert(size == region_next_size_get(&reg->sep));

	if (size <= bin_maxsize) {
		arena_bin_push(arena, (size >> opt_quantum_2pow) - bin_shift,
		    reg);
	} else
		arena_large_cache(arena, reg, false);
}

static __inline void
arena_undelay(arena_t *arena, uint32_t slot)
{
	region_t *reg, *next;
	size_t size;

	assert(slot == arena->next_delayed);
	assert(arena->delayed[slot] != NULL);

	/* Try to coalesce reg. */
	reg = arena->delayed[slot];

	size = region_next_size_get(&reg->sep);

	assert(region_next_contig_get(&reg->sep));
	assert(reg->next.u.s.slot == slot);

	arena_bin_extract(arena, (size >> opt_quantum_2pow) - bin_shift, reg);

	arena->delayed[slot] = NULL;

	next = (region_t *) &((char *) reg)[size];

	region_next_free_set(&reg->sep);
	region_prev_free_set(&next->sep);
	next->prev.size = size;

	if (arena_coalesce(arena, &reg, size) == false) {
		/* Coalescing failed.  Cache this region. */
		arena_mru_cache(arena, reg, size);
	} else {
		/* Coalescing succeeded. */

		if (reg == NULL) {
			/* Region no longer needs undelayed. */
			return;
		}

		if (region_next_size_get(&reg->sep) < chunk_size
		    - (CHUNK_REG_OFFSET + offsetof(region_t, next))) {
			/*
			 * Insert coalesced region into appropriate bin (or
			 * largeRegions).
			 */
			arena_lru_cache(arena, reg);
		} else {
			chunk_node_t *node;

			/*
			 * This region now spans an entire chunk.  Deallocate
			 * the chunk.
			 */

			node = (chunk_node_t *) CHUNK_ADDR2BASE(reg);
			RB_REMOVE(chunk_tree_s, &arena->chunks, node);
			arena->nchunks--;
			assert(node->chunk == (chunk_node_t *) node);
			chunk_dealloc(node->chunk, chunk_size);
		}
	}
}

static void
arena_delay_cache(arena_t *arena, region_t *reg)
{
	region_t *next;
	size_t size;

	assert(region_next_free_get(&reg->sep) == false);
	assert(region_next_size_get(&reg->sep) % quantum == 0);
	assert(region_next_size_get(&reg->sep)
	    >= QUANTUM_CEILING(sizeof(region_small_sizer_t)));

	size = region_next_size_get(&reg->sep);
	next = (region_t *)&((char *)reg)[size];
	assert(region_prev_free_get(&next->sep) == false);

	if (size <= bin_maxsize) {
		if (region_next_contig_get(&reg->sep)) {
			uint32_t slot;

			/* Insert into delayed. */

			/* Clear a slot, then put reg in it. */
			slot = arena->next_delayed;
			if (arena->delayed[slot] != NULL)
				arena_undelay(arena, slot);
			assert(slot == arena->next_delayed);
			assert(arena->delayed[slot] == NULL);

			reg->next.u.s.slot = slot;

			arena->delayed[slot] = reg;

			/* Update next_delayed. */
			slot++;
			slot &= (opt_ndelay - 1); /* Handle wrap-around. */
			arena->next_delayed = slot;

			arena_bin_append(arena, (size >> opt_quantum_2pow)
			    - bin_shift, reg);
		} else {
			/*
			 * This region was a fragment when it was allocated, so
			 * don't delay coalescence for it.
			 */

			region_next_free_set(&reg->sep);
			region_prev_free_set(&next->sep);
			next->prev.size = size;

			if (arena_coalesce(arena, &reg, size)) {
				/* Coalescing succeeded. */

				if (reg == NULL) {
					/* Region no longer needs cached. */
					return;
				}

				size = region_next_size_get(&reg->sep);
			}

			arena_mru_cache(arena, reg, size);
		}
	} else {
		region_next_free_set(&reg->sep);
		region_prev_free_set(&next->sep);
		region_next_contig_unset(&reg->sep);
		next->prev.size = size;

		arena_large_cache(arena, reg, true);
	}
}

static __inline region_t *
arena_frag_reg_alloc(arena_t *arena, size_t size, bool fit)
{
	region_t *ret;

	/*
	 * Try to fill frag if it's empty.  Frag needs to be marked as
	 * allocated.
	 */
	if (arena->frag == NULL) {
		region_node_t *node;

		node = RB_MIN(region_tree_s, &arena->large_regions);
		if (node != NULL) {
			region_t *frag, *next;

			RB_REMOVE(region_tree_s, &arena->large_regions, node);

			frag = node->reg;
#ifdef MALLOC_STATS
			arena->stats.frag.ncached++;
#endif
			assert(region_next_free_get(&frag->sep));
			region_next_free_unset(&frag->sep);

			next = (region_t *)&((char *)frag)[region_next_size_get(
			    &frag->sep)];
			assert(region_prev_free_get(&next->sep));
			region_prev_free_unset(&next->sep);

			arena->frag = frag;
		}
	}

	if (arena->frag != NULL) {
#ifdef MALLOC_STATS
		arena->stats.frag.nrequests++;
#endif

		if (region_next_size_get(&arena->frag->sep) >= size) {
			if (fit) {
				size_t total_size;

				/*
				 * Use frag, but try to use the beginning for
				 * smaller regions, and the end for larger
				 * regions.  This reduces fragmentation in some
				 * pathological use cases.  It tends to group
				 * short-lived (smaller) regions, which
				 * increases the effectiveness of coalescing.
				 */

				total_size =
				    region_next_size_get(&arena->frag->sep);
				assert(size % quantum == 0);

				if (total_size - size >= QUANTUM_CEILING(
				    sizeof(region_small_sizer_t))) {
					if (size <= bin_maxsize) {
						region_t *next;

						/*
						 * Carve space from the
						 * beginning of frag.
						 */

						/* ret. */
						ret = arena->frag;
						region_next_size_set(&ret->sep,
						    size);
						assert(region_next_free_get(
						    &ret->sep) == false);

						/* next. */
						next = (region_t *)&((char *)
						    ret)[size];
						region_next_size_set(&next->sep,
						    total_size - size);
						assert(size >=
						    QUANTUM_CEILING(sizeof(
						    region_small_sizer_t)));
						region_prev_free_unset(
						    &next->sep);
						region_next_free_unset(
						    &next->sep);

						/* Update frag. */
						arena->frag = next;
					} else {
						region_t *prev;
						size_t prev_size;

						/*
						 * Carve space from the end of
						 * frag.
						 */

						/* prev. */
						prev_size = total_size - size;
						prev = arena->frag;
						region_next_size_set(&prev->sep,
						    prev_size);
						assert(prev_size >=
						    QUANTUM_CEILING(sizeof(
						    region_small_sizer_t)));
						assert(region_next_free_get(
						    &prev->sep) == false);

						/* ret. */
						ret = (region_t *)&((char *)
						    prev)[prev_size];
						region_next_size_set(&ret->sep,
						    size);
						region_prev_free_unset(
						    &ret->sep);
						region_next_free_unset(
						    &ret->sep);

#ifdef MALLOC_DEBUG
						{
					region_t *next;

					/* next. */
					next = (region_t *)&((char *) ret)
					    [region_next_size_get(&ret->sep)];
					assert(region_prev_free_get(&next->sep)
					    == false);
						}
#endif
					}
#ifdef MALLOC_STATS
					arena->stats.nsplit++;
#endif
				} else {
					/*
					 * frag is close enough to the right
					 * size that there isn't enough room to
					 * create a neighboring region.
					 */

					/* ret. */
					ret = arena->frag;
					arena->frag = NULL;
					assert(region_next_free_get(&ret->sep)
					    == false);

#ifdef MALLOC_DEBUG
					{
						region_t *next;

						/* next. */
						next = (region_t *)&((char *)
						    ret)[region_next_size_get(
						    &ret->sep)];
						assert(region_prev_free_get(
						    &next->sep) == false);
					}
#endif
				}
#ifdef MALLOC_STATS
				arena->stats.frag.nserviced++;
#endif
			} else {
				/* Don't fit to the allocation size. */

				/* ret. */
				ret = arena->frag;
				arena->frag = NULL;
				assert(region_next_free_get(&ret->sep)
				    == false);

#ifdef MALLOC_DEBUG
				{
					region_t *next;

					/* next. */
					next = (region_t *) &((char *) ret)
					   [region_next_size_get(&ret->sep)];
					assert(region_prev_free_get(&next->sep)
					    == false);
				}
#endif
			}
			region_next_contig_set(&ret->sep);
			goto RETURN;
		} else if (size <= bin_maxsize) {
			region_t *reg;

			/*
			 * The frag region is too small to service a small
			 * request.  Clear frag.
			 */

			reg = arena->frag;
			region_next_contig_set(&reg->sep);

			arena->frag = NULL;

			arena_delay_cache(arena, reg);
		}
	}

	ret = NULL;
RETURN:
	return (ret);
}

static region_t *
arena_split_reg_alloc(arena_t *arena, size_t size, bool fit)
{
	region_t *ret;

	if (arena->split != NULL) {
#ifdef MALLOC_STATS
		arena->stats.split.nrequests++;
#endif

		if (region_next_size_get(&arena->split->sep) >= size) {
			if (fit) {
				size_t total_size;

				/*
				 * Use split, but try to use the beginning for
				 * smaller regions, and the end for larger
				 * regions.  This reduces fragmentation in some
				 * pathological use cases.  It tends to group
				 * short-lived (smaller) regions, which
				 * increases the effectiveness of coalescing.
				 */

				total_size =
				    region_next_size_get(&arena->split->sep);
				assert(size % quantum == 0);

				if (total_size - size >= QUANTUM_CEILING(
				    sizeof(region_small_sizer_t))) {
					if (size <= bin_maxsize) {
						region_t *next;

						/*
						 * Carve space from the
						 * beginning of split.
						 */

						/* ret. */
						ret = arena->split;
						region_next_size_set(&ret->sep,
						    size);
						assert(region_next_free_get(
						    &ret->sep) == false);

						/* next. */
						next = (region_t *)&((char *)
						    ret)[size];
						region_next_size_set(&next->sep,
						    total_size - size);
						assert(size >=
						    QUANTUM_CEILING(sizeof(
						    region_small_sizer_t)));
						region_prev_free_unset(
						    &next->sep);
						region_next_free_unset(
						    &next->sep);

						/* Update split. */
						arena->split = next;
					} else {
						region_t *prev;
						size_t prev_size;

						/*
						 * Carve space from the end of
						 * split.
						 */

						/* prev. */
						prev_size = total_size - size;
						prev = arena->split;
						region_next_size_set(&prev->sep,
						    prev_size);
						assert(prev_size >=
						    QUANTUM_CEILING(sizeof(
						    region_small_sizer_t)));
						assert(region_next_free_get(
						    &prev->sep) == false);

						/* ret. */
						ret = (region_t *)&((char *)
						    prev)[prev_size];
						region_next_size_set(&ret->sep,
						    size);
						region_prev_free_unset(
						    &ret->sep);
						region_next_free_unset(
						    &ret->sep);

#ifdef MALLOC_DEBUG
						{
					region_t *next;

					/* next. */
					next = (region_t *)&((char *) ret)
					    [region_next_size_get(&ret->sep)];
					assert(region_prev_free_get(&next->sep)
					    == false);
						}
#endif
					}
#ifdef MALLOC_STATS
					arena->stats.nsplit++;
#endif
				} else {
					/*
					 * split is close enough to the right
					 * size that there isn't enough room to
					 * create a neighboring region.
					 */

					/* ret. */
					ret = arena->split;
					arena->split = NULL;
					assert(region_next_free_get(&ret->sep)
					    == false);

#ifdef MALLOC_DEBUG
					{
						region_t *next;

						/* next. */
						next = (region_t *)&((char *)
						    ret)[region_next_size_get(
						    &ret->sep)];
						assert(region_prev_free_get(
						    &next->sep) == false);
					}
#endif
				}

#ifdef MALLOC_STATS
				arena->stats.split.nserviced++;
#endif
			} else {
				/* Don't fit to the allocation size. */

				/* ret. */
				ret = arena->split;
				arena->split = NULL;
				assert(region_next_free_get(&ret->sep)
				    == false);

#ifdef MALLOC_DEBUG
				{
					region_t *next;

					/* next. */
					next = (region_t *) &((char *) ret)
					   [region_next_size_get(&ret->sep)];
					assert(region_prev_free_get(&next->sep)
					    == false);
				}
#endif
			}
			region_next_contig_set(&ret->sep);
			goto RETURN;
		} else if (size <= bin_maxsize) {
			region_t *reg;

			/*
			 * The split region is too small to service a small
			 * request.  Clear split.
			 */

			reg = arena->split;
			region_next_contig_set(&reg->sep);

			arena->split = NULL;

			arena_delay_cache(arena, reg);
		}
	}

	ret = NULL;
RETURN:
	return (ret);
}

/*
 * Split reg if necessary.  The region must be overly large enough to be able
 * to contain a trailing region.
 */
static void
arena_reg_fit(arena_t *arena, size_t size, region_t *reg, bool restore_split)
{
	assert(QUANTUM_CEILING(size) == size);
	assert(region_next_free_get(&reg->sep) == 0);

	if (region_next_size_get(&reg->sep)
	    >= size + QUANTUM_CEILING(sizeof(region_small_sizer_t))) {
		size_t total_size;
		region_t *next;

		total_size = region_next_size_get(&reg->sep);

		region_next_size_set(&reg->sep, size);

		next = (region_t *) &((char *) reg)[size];
		region_next_size_set(&next->sep, total_size - size);
		assert(region_next_size_get(&next->sep)
		    >= QUANTUM_CEILING(sizeof(region_small_sizer_t)));
		region_prev_free_unset(&next->sep);

		if (restore_split) {
			/* Restore what's left to "split". */
			region_next_free_unset(&next->sep);
			arena->split = next;
		} else if (arena->frag == NULL && total_size - size
		    > bin_maxsize) {
			/* This region is large enough to use for "frag". */
			region_next_free_unset(&next->sep);
			arena->frag = next;
		} else {
			region_t *nextnext;
			size_t next_size;

			region_next_free_set(&next->sep);

			assert(region_next_size_get(&next->sep) == total_size
			    - size);
			next_size = total_size - size;
			nextnext = (region_t *) &((char *) next)[next_size];
			nextnext->prev.size = next_size;
			assert(region_prev_free_get(&nextnext->sep) == false);
			region_prev_free_set(&nextnext->sep);

			arena_mru_cache(arena, next, next_size);
		}

#ifdef MALLOC_STATS
		arena->stats.nsplit++;
#endif
	}
}

static __inline region_t *
arena_bin_reg_alloc(arena_t *arena, size_t size, bool fit)
{
	region_t *ret, *header;
	unsigned bin;

	/*
	 * Look for an exact fit in bins (region cached in smallest possible
	 * bin).
	 */
	bin = (size >> opt_quantum_2pow) - bin_shift;
#ifdef MALLOC_STATS
	arena->stats.bins[bin].nrequests++;
#endif
	header = &arena->bins[bin].regions;
	if (qr_next(header, next.u.s.link) != header) {
		/* Exact fit. */
		ret = arena_bin_pop(arena, bin);
		assert(region_next_size_get(&ret->sep) >= size);
#ifdef MALLOC_STATS
		arena->stats.bins[bin].nfit++;
#endif
		goto RETURN;
	}

	/* Look at frag to see whether it's large enough. */
	ret = arena_frag_reg_alloc(arena, size, fit);
	if (ret != NULL)
		goto RETURN;

	/* Look in all bins for a large enough region. */
	if ((bin = arena_bins_search(arena, size)) == (size >> opt_quantum_2pow)
	    - bin_shift) {
		/* Over-fit. */
		ret = arena_bin_pop(arena, bin);
		assert(region_next_size_get(&ret->sep) >= size);

		if (fit)
			arena_reg_fit(arena, size, ret, false);

#ifdef MALLOC_STATS
		arena->stats.bins[bin].noverfit++;
#endif
		goto RETURN;
	}

	ret = NULL;
RETURN:
	return (ret);
}

/* Look in large_regions for a large enough region. */
static region_t *
arena_large_reg_alloc(arena_t *arena, size_t size, bool fit)
{
	region_t *ret, *next;
	region_node_t *node;
	region_t key;

#ifdef MALLOC_STATS
	arena->stats.large.nrequests++;
#endif

	key.next.u.l.node.reg = &key;
	key.next.u.l.lru = true;
	region_next_size_set(&key.sep, size);
	node = RB_NFIND(region_tree_s, &arena->large_regions,
	    &key.next.u.l.node);
	if (node == NULL) {
		ret = NULL;
		goto RETURN;
	}

	/* Cached large region found. */
	ret = node->reg;
	assert(region_next_free_get(&ret->sep));

	RB_REMOVE(region_tree_s, &arena->large_regions, node);
#ifdef MALLOC_STATS
	arena->stats.large.curcached--;
#endif

	region_next_free_unset(&ret->sep);

	next = (region_t *)&((char *)ret)[region_next_size_get(&ret->sep)];
	assert(region_prev_free_get(&next->sep));
	region_prev_free_unset(&next->sep);

	if (fit)
		arena_reg_fit(arena, size, ret, false);

#ifdef MALLOC_STATS
	if (size > bin_maxsize)
		arena->stats.large.nfit++;
	else
		arena->stats.large.noverfit++;
#endif

RETURN:
	return (ret);
}

/* Allocate a new chunk and create a single region from it. */
static region_t *
arena_chunk_reg_alloc(arena_t *arena, size_t size, bool fit)
{
	region_t *ret, *next;
	chunk_node_t *chunk;

	chunk = chunk_alloc(chunk_size);
	if (chunk == NULL) {
		ret = NULL;
		goto RETURN;
	}

#ifdef MALLOC_DEBUG
	{
		chunk_node_t *tchunk;
		chunk_node_t key;

		key.chunk = chunk;
		tchunk = RB_FIND(chunk_tree_s, &arena->chunks, &key);
		assert(tchunk == NULL);
	}
#endif
	chunk->arena = arena;
	chunk->chunk = chunk;
	chunk->size = chunk_size;
	chunk->extra = 0;

	RB_INSERT(chunk_tree_s, &arena->chunks, chunk);
	arena->nchunks++;

	/* Carve a region from the new chunk. */
	ret = (region_t *) &((char *) chunk)[CHUNK_REG_OFFSET];
	region_next_size_set(&ret->sep, chunk_size - (CHUNK_REG_OFFSET
	    + offsetof(region_t, next)));
	region_prev_free_unset(&ret->sep);
	region_next_free_unset(&ret->sep);

	/* Create a separator at the end of this new region. */
	next = (region_t *)&((char *)ret)[region_next_size_get(&ret->sep)];
	region_next_size_set(&next->sep, 0);
	region_prev_free_unset(&next->sep);
	region_next_free_unset(&next->sep);
	region_next_contig_unset(&next->sep);

	if (fit)
		arena_reg_fit(arena, size, ret, (arena->split == NULL));

RETURN:
	return (ret);
}

/*
 * Find a region that is at least as large as aSize, and return a pointer to
 * the separator that precedes the region.  The return value is ready for use,
 * though it may be larger than is necessary if fit is false.
 */
static __inline region_t *
arena_reg_alloc(arena_t *arena, size_t size, bool fit)
{
	region_t *ret;

	assert(QUANTUM_CEILING(size) == size);
	assert(size >= QUANTUM_CEILING(sizeof(region_small_sizer_t)));
	assert(size <= (chunk_size >> 1));

	if (size <= bin_maxsize) {
		ret = arena_bin_reg_alloc(arena, size, fit);
		if (ret != NULL)
			goto RETURN;
	}

	ret = arena_large_reg_alloc(arena, size, fit);
	if (ret != NULL)
		goto RETURN;

	ret = arena_split_reg_alloc(arena, size, fit);
	if (ret != NULL)
		goto RETURN;

	/*
	 * Only try allocating from frag here if size is large, since
	 * arena_bin_reg_alloc() already falls back to allocating from frag for
	 * small regions.
	 */
	if (size > bin_maxsize) {
		ret = arena_frag_reg_alloc(arena, size, fit);
		if (ret != NULL)
			goto RETURN;
	}

	ret = arena_chunk_reg_alloc(arena, size, fit);
	if (ret != NULL)
		goto RETURN;

	ret = NULL;
RETURN:
	return (ret);
}

static void *
arena_malloc(arena_t *arena, size_t size)
{
	void *ret;
	region_t *reg;
	size_t quantum_size;

	assert(arena != NULL);
	assert(arena->magic == ARENA_MAGIC);
	assert(size != 0);
	assert(region_ceiling(size) <= (chunk_size >> 1));

	quantum_size = region_ceiling(size);
	if (quantum_size < size) {
		/* size is large enough to cause size_t wrap-around. */
		ret = NULL;
		goto RETURN;
	}
	assert(quantum_size >= QUANTUM_CEILING(sizeof(region_small_sizer_t)));

	malloc_mutex_lock(&arena->mtx);
	reg = arena_reg_alloc(arena, quantum_size, true);
	if (reg == NULL) {
		malloc_mutex_unlock(&arena->mtx);
		ret = NULL;
		goto RETURN;
	}

#ifdef MALLOC_STATS
	arena->allocated += quantum_size;
#endif

	malloc_mutex_unlock(&arena->mtx);

	ret = (void *)&reg->next;
#ifdef MALLOC_REDZONES
	{
		region_t *next;
		size_t total_size;

		memset(reg->sep.next_red, 0xa5, MALLOC_RED);

		/*
		 * Unused trailing space in the region is considered part of the
		 * trailing redzone.
		 */
		total_size = region_next_size_get(&reg->sep);
		assert(total_size >= size);
		memset(&((char *)ret)[size], 0xa5,
		    total_size - size - sizeof(region_sep_t));

		reg->sep.next_exact_size = size;

		next = (region_t *)&((char *)reg)[total_size];
		memset(next->sep.prev_red, 0xa5, MALLOC_RED);
	}
#endif
RETURN:
	return (ret);
}

static void *
arena_palloc(arena_t *arena, size_t alignment, size_t size)
{
	void *ret;

	assert(arena != NULL);
	assert(arena->magic == ARENA_MAGIC);

	if (alignment <= quantum) {
		/*
		 * The requested alignment is always guaranteed, so use the
		 * normal allocation function.
		 */
		ret = arena_malloc(arena, size);
	} else {
		region_t *reg, *old_split;
		size_t quantum_size, alloc_size, offset, total_size;

		/*
		 * Allocate more space than necessary, then carve an aligned
		 * region out of it.  The smallest allowable region is
		 * potentially a multiple of the quantum size, so care must be
		 * taken to carve things up such that all resulting regions are
		 * large enough.
		 */

		quantum_size = region_ceiling(size);
		if (quantum_size < size) {
			/* size is large enough to cause size_t wrap-around. */
			ret = NULL;
			goto RETURN;
		}

		/*
		 * Calculate how large of a region to allocate.  There must be
		 * enough space to advance far enough to have at least
		 * sizeof(region_small_sizer_t) leading bytes, yet also land at
		 * an alignment boundary.
		 */
		if (alignment >= sizeof(region_small_sizer_t)) {
			alloc_size =
			    QUANTUM_CEILING(sizeof(region_small_sizer_t))
			    + alignment + quantum_size;
		} else {
			alloc_size =
			    (QUANTUM_CEILING(sizeof(region_small_sizer_t)) << 1)
			    + quantum_size;
		}

		if (alloc_size < quantum_size) {
			/* size_t wrap-around occurred. */
			ret = NULL;
			goto RETURN;
		}

		malloc_mutex_lock(&arena->mtx);
		old_split = arena->split;
		reg = arena_reg_alloc(arena, alloc_size, false);
		if (reg == NULL) {
			malloc_mutex_unlock(&arena->mtx);
			ret = NULL;
			goto RETURN;
		}
		if (reg == old_split) {
			/*
			 * We requested a non-fit allocation that was serviced
			 * by split, which means that we need to take care to
			 * restore split in the arena_reg_fit() call later on.
			 *
			 * Do nothing; a non-NULL old_split will be used as the
			 * signal to restore split.
			 */
		} else
			old_split = NULL;

		total_size = region_next_size_get(&reg->sep);

		if (alignment > bin_maxsize || size > bin_maxsize) {
			size_t split_size, p;

			/*
			 * Put this allocation toward the end of reg, since
			 * it is large, and we try to put all large regions at
			 * the end of split regions.
			 */
			split_size = region_next_size_get(&reg->sep);
			p = (size_t)&((char *)&reg->next)[split_size];
			p -= offsetof(region_t, next);
			p -= size;
			p &= ~(alignment - 1);
			p -= offsetof(region_t, next);

			offset = p - (size_t)reg;
		} else {
			if ((((size_t)&reg->next) & (alignment - 1)) != 0) {
				size_t p;

				/*
				 * reg is unaligned.  Calculate the offset into
				 * reg to actually base the allocation at.
				 */
				p = ((size_t)&reg->next + alignment)
				    & ~(alignment - 1);
				while (p - (size_t)&reg->next
				    < QUANTUM_CEILING(sizeof(
				    region_small_sizer_t)))
					p += alignment;
				p -= offsetof(region_t, next);

				offset = p - (size_t)reg;
			} else
				offset = 0;
		}
		assert(offset % quantum == 0);
		assert(offset < total_size);

		if (offset != 0) {
			region_t *prev;

			/*
			 * Move ret to an alignment boundary that is far enough
			 * past the beginning of the allocation to leave a
			 * leading free region, then trim the leading space.
			 */

			assert(offset >= QUANTUM_CEILING(
			    sizeof(region_small_sizer_t)));
			assert(offset + size <= total_size);

			prev = reg;
			reg = (region_t *)&((char *)prev)[offset];
			assert(((size_t)&reg->next & (alignment - 1)) == 0);

			/* prev. */
			region_next_size_set(&prev->sep, offset);
			reg->prev.size = offset;

			/* reg. */
			region_next_size_set(&reg->sep, total_size - offset);
			region_next_free_unset(&reg->sep);
			if (region_next_contig_get(&prev->sep))
				region_next_contig_set(&reg->sep);
			else
				region_next_contig_unset(&reg->sep);

			if (old_split != NULL && (alignment > bin_maxsize
			    || size > bin_maxsize)) {
				/* Restore to split. */
				region_prev_free_unset(&reg->sep);

				arena->split = prev;
				old_split = NULL;
			} else {
				region_next_free_set(&prev->sep);
				region_prev_free_set(&reg->sep);

				arena_mru_cache(arena, prev, offset);
			}
#ifdef MALLOC_STATS
			arena->stats.nsplit++;
#endif
		}

		arena_reg_fit(arena, quantum_size, reg, (old_split != NULL));

#ifdef MALLOC_STATS
		arena->allocated += quantum_size;
#endif

		malloc_mutex_unlock(&arena->mtx);

		ret = (void *)&reg->next;
#ifdef MALLOC_REDZONES
		{
			region_t *next;
			size_t total_size;

			memset(reg->sep.next_red, 0xa5, MALLOC_RED);

			/*
			 * Unused trailing space in the region is considered
			 * part of the trailing redzone.
			 */
			total_size = region_next_size_get(&reg->sep);
			assert(total_size >= size);
			memset(&((char *)ret)[size], 0xa5,
			    total_size - size - sizeof(region_sep_t));

			reg->sep.next_exact_size = size;

			next = (region_t *)&((char *)reg)[total_size];
			memset(next->sep.prev_red, 0xa5, MALLOC_RED);
		}
#endif
	}

RETURN:
	assert(((size_t)ret & (alignment - 1)) == 0);
	return (ret);
}

static void *
arena_calloc(arena_t *arena, size_t num, size_t size)
{
	void *ret;

	assert(arena != NULL);
	assert(arena->magic == ARENA_MAGIC);
	assert(num * size != 0);

	ret = arena_malloc(arena, num * size);
	if (ret == NULL)
		goto RETURN;

	memset(ret, 0, num * size);

RETURN:
	return (ret);
}

static size_t
arena_salloc(arena_t *arena, void *ptr)
{
	size_t ret;
	region_t *reg;

	assert(arena != NULL);
	assert(arena->magic == ARENA_MAGIC);
	assert(ptr != NULL);
	assert(ptr != &nil);
	assert(CHUNK_ADDR2BASE(ptr) != ptr);

	reg = (region_t *)&((char *)ptr)[-offsetof(region_t, next)];

	ret = region_next_size_get(&reg->sep);

	return (ret);
}

#ifdef MALLOC_REDZONES
static void
redzone_check(void *ptr)
{
	region_t *reg, *next;
	size_t size;
	unsigned i, ncorruptions;

	ncorruptions = 0;

	reg = (region_t *)&((char *)ptr)[-offsetof(region_t, next)];
	size = region_next_size_get(&reg->sep);
	next = (region_t *)&((char *)reg)[size];

	/* Leading redzone. */
	for (i = 0; i < MALLOC_RED; i++) {
		if ((unsigned char)reg->sep.next_red[i] != 0xa5) {
			size_t offset = (size_t)MALLOC_RED - i;

			ncorruptions++;
			malloc_printf("%s: (malloc) Corrupted redzone %zu "
			    "byte%s before %p (0x%x)\n", _getprogname(), 
			    offset, offset > 1 ? "s" : "", ptr,
			    (unsigned char)reg->sep.next_red[i]);
		}
	}
	memset(&reg->sep.next_red, 0x5a, MALLOC_RED);

	/* Bytes immediately trailing allocation. */
	for (i = 0; i < size - reg->sep.next_exact_size - sizeof(region_sep_t);
	    i++) {
		if ((unsigned char)((char *)ptr)[reg->sep.next_exact_size + i]
		    != 0xa5) {
			size_t offset = (size_t)(i + 1);

			ncorruptions++;
			malloc_printf("%s: (malloc) Corrupted redzone %zu "
			    "byte%s after %p (size %zu) (0x%x)\n",
			    _getprogname(), offset, offset > 1 ? "s" : "", ptr,
			    reg->sep.next_exact_size, (unsigned char)((char *)
			    ptr)[reg->sep.next_exact_size + i]);
		}
	}
	memset(&((char *)ptr)[reg->sep.next_exact_size], 0x5a,
	    size - reg->sep.next_exact_size - sizeof(region_sep_t));

	/* Trailing redzone. */
	for (i = 0; i < MALLOC_RED; i++) {
		if ((unsigned char)next->sep.prev_red[i] != 0xa5) {
			size_t offset = (size_t)(size - reg->sep.next_exact_size
			    - sizeof(region_sep_t) + i + 1);

			ncorruptions++;
			malloc_printf("%s: (malloc) Corrupted redzone %zu "
			    "byte%s after %p (size %zu) (0x%x)\n",
			    _getprogname(), offset, offset > 1 ? "s" : "", ptr,
			    reg->sep.next_exact_size,
			    (unsigned char)next->sep.prev_red[i]);
		}
	}
	memset(&next->sep.prev_red, 0x5a, MALLOC_RED);

	if (opt_abort && ncorruptions != 0)
		abort();

	reg->sep.next_exact_size = 0;
}
#endif

static void
arena_dalloc(arena_t *arena, void *ptr)
{
	region_t *reg;

	assert(arena != NULL);
	assert(ptr != NULL);
	assert(ptr != &nil);

	assert(arena != NULL);
	assert(arena->magic == ARENA_MAGIC);
	assert(CHUNK_ADDR2BASE(ptr) != ptr);

	reg = (region_t *)&((char *)ptr)[-offsetof(region_t, next)];

	malloc_mutex_lock(&arena->mtx);

#ifdef MALLOC_DEBUG
	{
		chunk_node_t *chunk, *node;
		chunk_node_t key;

		chunk = CHUNK_ADDR2BASE(ptr);
		assert(chunk->arena == arena);

		key.chunk = chunk;
		node = RB_FIND(chunk_tree_s, &arena->chunks, &key);
		assert(node == chunk);
	}
#endif
#ifdef MALLOC_REDZONES
	redzone_check(ptr);
#endif

#ifdef MALLOC_STATS
	arena->allocated -= region_next_size_get(&reg->sep);
#endif

	if (opt_junk) {
		memset(&reg->next, 0x5a,
		    region_next_size_get(&reg->sep) - sizeof(region_sep_t));
	}

	arena_delay_cache(arena, reg);

	malloc_mutex_unlock(&arena->mtx);
}

#ifdef NOT_YET
static void *
arena_ralloc(arena_t *arena, void *ptr, size_t size)
{

	/*
	 * Arenas don't need to support ralloc, since all reallocation is done
	 * by allocating new space and copying.  This function should never be
	 * called.
	 */
	/* NOTREACHED */
	assert(false);

	return (NULL);
}
#endif

#ifdef MALLOC_STATS
static bool
arena_stats(arena_t *arena, size_t *allocated, size_t *total)
{

	assert(arena != NULL);
	assert(arena->magic == ARENA_MAGIC);
	assert(allocated != NULL);
	assert(total != NULL);

	malloc_mutex_lock(&arena->mtx);
	*allocated = arena->allocated;
	*total = arena->nchunks * chunk_size;
	malloc_mutex_unlock(&arena->mtx);

	return (false);
}
#endif

static bool
arena_new(arena_t *arena)
{
	bool ret;
	unsigned i;

	malloc_mutex_init(&arena->mtx);

	for (i = 0; i < NBINS; i++)
		qr_new(&arena->bins[i].regions, next.u.s.link);

	for (i = 0; i < BINMASK_NELMS; i++)
		arena->bins_mask[i] = 0;

	arena->split = NULL;
	arena->frag = NULL;
	RB_INIT(&arena->large_regions);

	RB_INIT(&arena->chunks);
	arena->nchunks = 0;

	assert(opt_ndelay > 0);
	arena->delayed = (region_t **)base_alloc(opt_ndelay
	    * sizeof(region_t *));
	if (arena->delayed == NULL) {
		ret = true;
		goto RETURN;
	}
	memset(arena->delayed, 0, opt_ndelay * sizeof(region_t *));
	arena->next_delayed = 0;

#ifdef MALLOC_STATS
	arena->allocated = 0;

	memset(&arena->stats, 0, sizeof(arena_stats_t));
#endif

#ifdef MALLOC_DEBUG
	arena->magic = ARENA_MAGIC;
#endif

	ret = false;
RETURN:
	return (ret);
}

/* Create a new arena and insert it into the arenas array at index ind. */
static arena_t *
arenas_extend(unsigned ind)
{
	arena_t *ret;

	ret = (arena_t *)base_alloc(sizeof(arena_t));
	if (ret != NULL && arena_new(ret) == false) {
		arenas[ind] = ret;
		return (ret);
	}
	/* Only reached if there is an OOM error. */

	/*
	 * OOM here is quite inconvenient to propagate, since dealing with it
	 * would require a check for failure in the fast path.  Instead, punt
	 * by using arenas[0].  In practice, this is an extremely unlikely
	 * failure.
	 */
	malloc_printf("%s: (malloc) Error initializing arena\n",
	    _getprogname());
	if (opt_abort)
		abort();

	return (arenas[0]);
}

/*
 * End arena.
 */
/******************************************************************************/
/*
 * Begin  general internal functions.
 */

/*
 * Choose an arena based on a per-thread value (fast-path code, calls slow-path
 * code if necessary.
 */
static __inline arena_t *
choose_arena(void)
{
	arena_t *ret;

	/*
	 * We can only use TLS if this is a PIC library, since for the static
	 * library version, libc's malloc is used by TLS allocation, which
	 * introduces a bootstrapping issue.
	 */
#ifndef NO_TLS
	ret = arenas_map;
	if (ret == NULL)
		ret = choose_arena_hard();
#else
	if (__isthreaded) {
		unsigned long ind;
		
		/*
		 * Hash _pthread_self() to one of the arenas.  There is a prime
		 * number of arenas, so this has a reasonable chance of
		 * working.  Even so, the hashing can be easily thwarted by
		 * inconvenient _pthread_self() values.  Without specific
		 * knowledge of how _pthread_self() calculates values, we can't
		 * do much better than this.
		 */
		ind = (unsigned long) _pthread_self() % narenas;

		/*
		 * Optimistially assume that arenas[ind] has been initialized.
		 * At worst, we find out that some other thread has already
		 * done so, after acquiring the lock in preparation.  Note that
		 * this lazy locking also has the effect of lazily forcing
		 * cache coherency; without the lock acquisition, there's no
		 * guarantee that modification of arenas[ind] by another thread
		 * would be seen on this CPU for an arbitrary amount of time.
		 *
		 * In general, this approach to modifying a synchronized value
		 * isn't a good idea, but in this case we only ever modify the
		 * value once, so things work out well.
		 */
		ret = arenas[ind];
		if (ret == NULL) {
			/*
			 * Avoid races with another thread that may have already
			 * initialized arenas[ind].
			 */
			malloc_mutex_lock(&arenas_mtx);
			if (arenas[ind] == NULL)
				ret = arenas_extend((unsigned)ind);
			else
				ret = arenas[ind];
			malloc_mutex_unlock(&arenas_mtx);
		}
	} else
		ret = arenas[0];
#endif

	return (ret);
}

#ifndef NO_TLS
/*
 * Choose an arena based on a per-thread value (slow-path code only, called
 * only by choose_arena()).
 */
static arena_t *
choose_arena_hard(void)
{
	arena_t *ret;

	/* Assign one of the arenas to this thread, in a round-robin fashion. */
	if (__isthreaded) {
		malloc_mutex_lock(&arenas_mtx);
		ret = arenas[next_arena];
		if (ret == NULL)
			ret = arenas_extend(next_arena);
		next_arena = (next_arena + 1) % narenas;
		malloc_mutex_unlock(&arenas_mtx);
	} else
		ret = arenas[0];
	arenas_map = ret;

	return (ret);
}
#endif

static void *
huge_malloc(arena_t *arena, size_t size)
{
	void *ret;
	size_t chunk_size;
	chunk_node_t *node;

	/* Allocate a chunk for this request. */

#ifdef MALLOC_STATS
	arena->stats.huge.nrequests++;
#endif

	chunk_size = CHUNK_CEILING(size);
	if (chunk_size == 0) {
		/* size is large enough to cause size_t wrap-around. */
		ret = NULL;
		goto RETURN;
	}

	/* Allocate a chunk node with which to track the chunk. */
	node = base_chunk_node_alloc();
	if (node == NULL) {
		ret = NULL;
		goto RETURN;
	}

	ret = chunk_alloc(chunk_size);
	if (ret == NULL) {
		base_chunk_node_dealloc(node);
		ret = NULL;
		goto RETURN;
	}

	/* Insert node into chunks. */
	node->arena = arena;
	node->chunk = ret;
	node->size = chunk_size;
	node->extra = chunk_size - size;

	malloc_mutex_lock(&chunks_mtx);
	RB_INSERT(chunk_tree_s, &huge, node);
#ifdef MALLOC_STATS
	huge_allocated += size;
	huge_total += chunk_size;
#endif
	malloc_mutex_unlock(&chunks_mtx);

RETURN:
	return (ret);
}

static void
huge_dalloc(void *ptr)
{
	chunk_node_t key;
	chunk_node_t *node;

	malloc_mutex_lock(&chunks_mtx);

	/* Extract from tree of huge allocations. */
	key.chunk = ptr;
	node = RB_FIND(chunk_tree_s, &huge, &key);
	assert(node != NULL);
	assert(node->chunk == ptr);
	RB_REMOVE(chunk_tree_s, &huge, node);

#ifdef MALLOC_STATS
	malloc_mutex_lock(&node->arena->mtx);
	node->arena->stats.ndalloc++;
	malloc_mutex_unlock(&node->arena->mtx);

	/* Update counters. */
	huge_allocated -= (node->size - node->extra);
	huge_total -= node->size;
#endif

	malloc_mutex_unlock(&chunks_mtx);

	/* Unmap chunk. */
	chunk_dealloc(node->chunk, node->size);

	base_chunk_node_dealloc(node);
}

static void *
imalloc(arena_t *arena, size_t size)
{
	void *ret;

	assert(arena != NULL);
	assert(arena->magic == ARENA_MAGIC);
	assert(size != 0);

	if (region_ceiling(size) <= (chunk_size >> 1))
		ret = arena_malloc(arena, size);
	else
		ret = huge_malloc(arena, size);

#ifdef MALLOC_STATS
	malloc_mutex_lock(&arena->mtx);
	arena->stats.nmalloc++;
	malloc_mutex_unlock(&arena->mtx);
#endif

	if (opt_junk) {
		if (ret != NULL)
			memset(ret, 0xa5, size);
	}
	return (ret);
}

static void *
ipalloc(arena_t *arena, size_t alignment, size_t size)
{
	void *ret;

	assert(arena != NULL);
	assert(arena->magic == ARENA_MAGIC);

	/*
	 * The conditions that disallow calling arena_palloc() are quite
	 * tricky.
	 *
	 * The first main clause of the conditional mirrors that in imalloc(),
	 * and is necesary because arena_palloc() may in turn call
	 * arena_malloc().
	 *
	 * The second and third clauses are necessary because we want to be
	 * sure that it will not be necessary to allocate more than a
	 * half-chunk region at any point during the creation of the aligned
	 * allocation.  These checks closely mirror the calculation of
	 * alloc_size in arena_palloc().
	 *
	 * Finally, the fourth clause makes explicit the constraint on what
	 * alignments will be attempted via regions.  At first glance, this
	 * appears unnecessary, but in actuality, it protects against otherwise
	 * difficult-to-detect size_t wrap-around cases.
	 */
	if (region_ceiling(size) <= (chunk_size >> 1)

	    && (alignment < sizeof(region_small_sizer_t)
	    || (QUANTUM_CEILING(sizeof(region_small_sizer_t)) + alignment
	    + (region_ceiling(size))) <= (chunk_size >> 1))

	    && (alignment >= sizeof(region_small_sizer_t)
	    || ((QUANTUM_CEILING(sizeof(region_small_sizer_t)) << 1)
	    + (region_ceiling(size))) <= (chunk_size >> 1))

	    && alignment <= (chunk_size >> 2))
		ret = arena_palloc(arena, alignment, size);
	else {
		if (alignment <= chunk_size)
			ret = huge_malloc(arena, size);
		else {
			size_t chunksize, alloc_size, offset;
			chunk_node_t *node;

			/*
			 * This allocation requires alignment that is even
			 * larger than chunk alignment.  This means that
			 * huge_malloc() isn't good enough.
			 *
			 * Allocate almost twice as many chunks as are demanded
			 * by the size or alignment, in order to assure the
			 * alignment can be achieved, then unmap leading and
			 * trailing chunks.
			 */

			chunksize = CHUNK_CEILING(size);

			if (size >= alignment)
				alloc_size = chunksize + alignment - chunk_size;
			else
				alloc_size = (alignment << 1) - chunk_size;

			/*
			 * Allocate a chunk node with which to track the chunk.
			 */
			node = base_chunk_node_alloc();
			if (node == NULL) {
				ret = NULL;
				goto RETURN;
			}

			ret = chunk_alloc(alloc_size);
			if (ret == NULL) {
				base_chunk_node_dealloc(node);
				ret = NULL;
				goto RETURN;
			}

			offset = (size_t)ret & (alignment - 1);
			assert(offset % chunk_size == 0);
			assert(offset < alloc_size);
			if (offset == 0) {
				/* Trim trailing space. */
				chunk_dealloc((void *) ((size_t) ret
				    + chunksize), alloc_size - chunksize);
			} else {
				size_t trailsize;

				/* Trim leading space. */
				chunk_dealloc(ret, alignment - offset);

				ret = (void *) ((size_t) ret + (alignment
				    - offset));

				trailsize = alloc_size - (alignment - offset)
				    - chunksize;
				if (trailsize != 0) {
				    /* Trim trailing space. */
				    assert(trailsize < alloc_size);
				    chunk_dealloc((void *) ((size_t) ret
				        + chunksize), trailsize);
				}
			}

			/* Insert node into chunks. */
			node->arena = arena;
			node->chunk = ret;
			node->size = chunksize;
			node->extra = node->size - size;

			malloc_mutex_lock(&chunks_mtx);
			RB_INSERT(chunk_tree_s, &huge, node);
#ifdef MALLOC_STATS
			huge_allocated += size;
			huge_total += chunksize;
#endif
			malloc_mutex_unlock(&chunks_mtx);
		}
	}

RETURN:
#ifdef MALLOC_STATS
	malloc_mutex_lock(&arena->mtx);
	arena->stats.npalloc++;
	malloc_mutex_unlock(&arena->mtx);
#endif

	if (opt_junk) {
		if (ret != NULL)
			memset(ret, 0xa5, size);
	}
	assert(((size_t)ret & (alignment - 1)) == 0);
	return (ret);
}

static void *
icalloc(arena_t *arena, size_t num, size_t size)
{
	void *ret;

	assert(arena != NULL);
	assert(arena->magic == ARENA_MAGIC);
	assert(num * size != 0);

	if (region_ceiling(num * size) <= (chunk_size >> 1))
		ret = arena_calloc(arena, num, size);
	else {
		/*
		 * The virtual memory system provides zero-filled pages, so
		 * there is no need to do so manually.
		 */
		ret = huge_malloc(arena, num * size);
#ifdef USE_BRK
		if ((size_t)ret >= (size_t)brk_base
		    && (size_t)ret < (size_t)brk_max) {
			/* 
			 * This may be a re-used brk chunk.  Therefore, zero
			 * the memory.
			 */
			memset(ret, 0, num * size);
		}
#endif
	}

#ifdef MALLOC_STATS
	malloc_mutex_lock(&arena->mtx);
	arena->stats.ncalloc++;
	malloc_mutex_unlock(&arena->mtx);
#endif

	return (ret);
}

static size_t
isalloc(void *ptr)
{
	size_t ret;
	chunk_node_t *node;

	assert(ptr != NULL);
	assert(ptr != &nil);

	node = CHUNK_ADDR2BASE(ptr);
	if (node != ptr) {
		/* Region. */
		assert(node->arena->magic == ARENA_MAGIC);

		ret = arena_salloc(node->arena, ptr);
	} else {
		chunk_node_t key;

		/* Chunk (huge allocation). */

		malloc_mutex_lock(&chunks_mtx);

		/* Extract from tree of huge allocations. */
		key.chunk = ptr;
		node = RB_FIND(chunk_tree_s, &huge, &key);
		assert(node != NULL);

		ret = node->size - node->extra;

		malloc_mutex_unlock(&chunks_mtx);
	}

	return (ret);
}

static void
idalloc(void *ptr)
{
	chunk_node_t *node;

	assert(ptr != NULL);
	assert(ptr != &nil);

	node = CHUNK_ADDR2BASE(ptr);
	if (node != ptr) {
		/* Region. */
#ifdef MALLOC_STATS
		malloc_mutex_lock(&node->arena->mtx);
		node->arena->stats.ndalloc++;
		malloc_mutex_unlock(&node->arena->mtx);
#endif
		arena_dalloc(node->arena, ptr);
	} else
		huge_dalloc(ptr);
}

static void *
iralloc(arena_t *arena, void *ptr, size_t size)
{
	void *ret;
	size_t oldsize;

	assert(arena != NULL);
	assert(arena->magic == ARENA_MAGIC);
	assert(ptr != NULL);
	assert(ptr != &nil);
	assert(size != 0);

	oldsize = isalloc(ptr);

	if (region_ceiling(size) <= (chunk_size >> 1)) {
		ret = arena_malloc(arena, size);
		if (ret == NULL)
			goto RETURN;
		if (opt_junk)
			memset(ret, 0xa5, size);

		if (size < oldsize)
			memcpy(ret, ptr, size);
		else
			memcpy(ret, ptr, oldsize);
	} else {
		ret = huge_malloc(arena, size);
		if (ret == NULL)
			goto RETURN;
		if (opt_junk)
			memset(ret, 0xa5, size);

		if (CHUNK_ADDR2BASE(ptr) == ptr) {
			/* The old allocation is a chunk. */
			if (size < oldsize)
				memcpy(ret, ptr, size);
			else
				memcpy(ret, ptr, oldsize);
		} else {
			/* The old allocation is a region. */
			assert(oldsize < size);
			memcpy(ret, ptr, oldsize);
		}
	}

	idalloc(ptr);

RETURN:
#ifdef MALLOC_STATS
	malloc_mutex_lock(&arena->mtx);
	arena->stats.nralloc++;
	malloc_mutex_unlock(&arena->mtx);
#endif
	return (ret);
}

#ifdef MALLOC_STATS
static void
istats(size_t *allocated, size_t *total)
{
	size_t tallocated, ttotal;
	size_t rallocated, rtotal;
	unsigned i;

	tallocated = 0;
	ttotal = base_total;

	/* arenas. */
	for (i = 0; i < narenas; i++) {
		if (arenas[i] != NULL) {
			arena_stats(arenas[i], &rallocated, &rtotal);
			tallocated += rallocated;
			ttotal += rtotal;
		}
	}

	/* huge. */
	malloc_mutex_lock(&chunks_mtx);
	tallocated += huge_allocated;
	ttotal += huge_total;
	malloc_mutex_unlock(&chunks_mtx);

	/* Return results. */
	*allocated = tallocated;
	*total = ttotal;
}
#endif

static void
malloc_print_stats(void)
{

	if (opt_print_stats) {
		malloc_printf("___ Begin malloc statistics ___\n");
		malloc_printf("Number of CPUs: %u\n", ncpus);
		malloc_printf("Number of arenas: %u\n", narenas);
		malloc_printf("Cache slots: %u\n", opt_ndelay);
		malloc_printf("Chunk size: %zu (2^%zu)\n", chunk_size,
		    opt_chunk_2pow);
		malloc_printf("Quantum size: %zu (2^%zu)\n", quantum, 
		    opt_quantum_2pow);
		malloc_printf("Pointer size: %u\n", sizeof(size_t));
		malloc_printf("Number of bins: %u\n", NBINS);
		malloc_printf("Maximum bin size: %u\n", bin_maxsize);
		malloc_printf("Assertions %s\n",
#ifdef NDEBUG
		    "disabled"
#else
		    "enabled"
#endif
		    );
		malloc_printf("Redzone size: %u\n", 
#ifdef MALLOC_REDZONES
				MALLOC_RED
#else
				0
#endif
				);

#ifdef MALLOC_STATS
		{
			size_t a, b;

			istats(&a, &b);
			malloc_printf("Allocated: %zu, space used: %zu\n", a,
			    b);
		}

		{
			arena_stats_t stats_arenas;
			arena_t *arena;
			unsigned i;

			/* Print chunk stats. */
			{
				chunk_stats_t chunks_stats;

				malloc_mutex_lock(&chunks_mtx);
				chunks_stats = stats_chunks;
				malloc_mutex_unlock(&chunks_mtx);

				malloc_printf("\nchunks:\n");
				malloc_printf(" %13s%13s%13s\n", "nchunks",
				    "highchunks", "curchunks");
				malloc_printf(" %13llu%13lu%13lu\n",
				    chunks_stats.nchunks, 
				    chunks_stats.highchunks,
				    chunks_stats.curchunks);
			}

#ifdef MALLOC_STATS_ARENAS
			/* Print stats for each arena. */
			for (i = 0; i < narenas; i++) {
				arena = arenas[i];
				if (arena != NULL) {
					malloc_printf(
					    "\narenas[%u] statistics:\n", i);
					malloc_mutex_lock(&arena->mtx);
					stats_print(&arena->stats);
					malloc_mutex_unlock(&arena->mtx);
				} else {
					malloc_printf("\narenas[%u] statistics:"
					    " unused arena\n", i);
				}
			}
#endif

			/* Merge arena stats from arenas. */
			memset(&stats_arenas, 0, sizeof(arena_stats_t));
			for (i = 0; i < narenas; i++) {
				arena = arenas[i];
				if (arena != NULL) {
					malloc_mutex_lock(&arena->mtx);
					stats_merge(arena, &stats_arenas);
					malloc_mutex_unlock(&arena->mtx);
				}
			}

			/* Print arena stats. */
			malloc_printf("\nMerged arena statistics:\n");
			stats_print(&stats_arenas);
		}
#endif /* #ifdef MALLOC_STATS */
		malloc_printf("--- End malloc statistics ---\n");
	}
}

/*
 * FreeBSD's pthreads implementation calls malloc(3), so the malloc
 * implementation has to take pains to avoid infinite recursion during
 * initialization.
 *
 * atomic_init_start() returns true if it started initializing.  In that case,
 * the caller must also call atomic_init_finish(), just before returning
 * to its caller.  This delayed finalization of initialization is critical,
 * since otherwise choose_arena() has no way to know whether it's safe
 * to call _pthread_self().
 */
static __inline bool
malloc_init(void)
{

	/*
	 * We always initialize before threads are created, since any thread
	 * creation first triggers allocations.
	 */
	assert(__isthreaded == 0 || malloc_initialized);

	if (malloc_initialized == false)
		return (malloc_init_hard());

	return (false);
}

static bool
malloc_init_hard(void)
{
	unsigned i, j;
	int linklen;
	char buf[PATH_MAX + 1];
	const char *opts;

	/* Get number of CPUs. */
	{
		int mib[2];
		size_t len;

		mib[0] = CTL_HW;
		mib[1] = HW_NCPU;
		len = sizeof(ncpus);
		if (sysctl(mib, 2, &ncpus, &len, (void *) 0, 0) == -1) {
			/* Error. */
			ncpus = 1;
		}
	}

	/* Get page size. */
	{
		long result;

		result = sysconf(_SC_PAGESIZE);
		assert(result != -1);
		pagesize = (unsigned) result;
	}

	for (i = 0; i < 3; i++) {
		/* Get runtime configuration. */
		switch (i) {
		case 0:
			if ((linklen = readlink("/etc/malloc.conf", buf,
						sizeof(buf) - 1)) != -1) {
				/*
				 * Use the contents of the "/etc/malloc.conf"
				 * symbolic link's name.
				 */
				buf[linklen] = '\0';
				opts = buf;
			} else {
				/* No configuration specified. */
				buf[0] = '\0';
				opts = buf;
			}
			break;
		case 1:
			if (issetugid() == 0 && (opts =
			    getenv("MALLOC_OPTIONS")) != NULL) {
				/*
				 * Do nothing; opts is already initialized to
				 * the value of the MALLOC_OPTIONS environment
				 * variable.
				 */
			} else {
				/* No configuration specified. */
				buf[0] = '\0';
				opts = buf;
			}
			break;
		case 2:
			if (_malloc_options != NULL) {
			    /*
			     * Use options that were compiled into the program.
			     */
			    opts = _malloc_options;
			} else {
				/* No configuration specified. */
				buf[0] = '\0';
				opts = buf;
			}
			break;
		default:
			/* NOTREACHED */
			assert(false);
		}

		for (j = 0; opts[j] != '\0'; j++) {
			switch (opts[j]) {
			case 'a':
				opt_abort = false;
				break;
			case 'A':
				opt_abort = true;
				break;
			case 'c':
				opt_ndelay <<= 1;
				if (opt_ndelay == 0)
					opt_ndelay = 1;
				break;
			case 'C':
				opt_ndelay >>= 1;
				if (opt_ndelay == 0)
					opt_ndelay = 1;
				break;
			case 'j':
				opt_junk = false;
				break;
			case 'J':
				opt_junk = true;
				break;
			case 'k':
				if ((1 << opt_chunk_2pow) > pagesize)
					opt_chunk_2pow--;
				break;
			case 'K':
				if (opt_chunk_2pow < CHUNK_2POW_MAX)
					opt_chunk_2pow++;
				break;
			case 'n':
				opt_narenas_lshift--;
				break;
			case 'N':
				opt_narenas_lshift++;
				break;
			case 'p':
				opt_print_stats = false;
				break;
			case 'P':
				opt_print_stats = true;
				break;
			case 'q':
				if (opt_quantum_2pow > QUANTUM_2POW_MIN)
					opt_quantum_2pow--;
				break;
			case 'Q':
				if ((1 << opt_quantum_2pow) < pagesize)
					opt_quantum_2pow++;
				break;
			case 'u':
				opt_utrace = false;
				break;
			case 'U':
				opt_utrace = true;
				break;
			case 'v':
				opt_sysv = false;
				break;
			case 'V':
				opt_sysv = true;
				break;
			case 'x':
				opt_xmalloc = false;
				break;
			case 'X':
				opt_xmalloc = true;
				break;
			case 'z':
				opt_zero = false;
				break;
			case 'Z':
				opt_zero = true;
				break;
			default:
				malloc_printf("%s: (malloc) Unsupported"
				    " character in malloc options: '%c'\n",
				    _getprogname(), opts[j]);
			}
		}
	}

	/* Take care to call atexit() only once. */
	if (opt_print_stats) {
		/* Print statistics at exit. */
		atexit(malloc_print_stats);
	}

	/* Set variables according to the value of opt_quantum_2pow. */
	quantum = (1 << opt_quantum_2pow);
	quantum_mask = quantum - 1;
	bin_shift = ((QUANTUM_CEILING(sizeof(region_small_sizer_t))
	    >> opt_quantum_2pow));
	bin_maxsize = ((NBINS + bin_shift - 1) * quantum);

	/* Set variables according to the value of opt_chunk_2pow. */
	chunk_size = (1 << opt_chunk_2pow);
	chunk_size_mask = chunk_size - 1;

	UTRACE(0, 0, 0);

#ifdef MALLOC_STATS
	memset(&stats_chunks, 0, sizeof(chunk_stats_t));
#endif

	/* Various sanity checks that regard configuration. */
	assert(quantum >= 2 * sizeof(void *));
	assert(quantum <= pagesize);
	assert(chunk_size >= pagesize);
	assert(quantum * 4 <= chunk_size);

	/* Initialize chunks data. */
	malloc_mutex_init(&chunks_mtx);
	RB_INIT(&huge);
#ifdef USE_BRK
	brk_base = sbrk(0);
	brk_prev = brk_base;
	brk_max = (void *)((size_t)brk_base + MAXDSIZ);
#endif
#ifdef MALLOC_STATS
	huge_allocated = 0;
	huge_total = 0;
#endif
	RB_INIT(&old_chunks);

	/* Initialize base allocation data structures. */
	base_chunk = NULL;
	base_next_addr = NULL;
	base_past_addr = NULL;
	base_chunk_nodes = NULL;
	malloc_mutex_init(&base_mtx);
#ifdef MALLOC_STATS
	base_total = 0;
#endif

	if (ncpus > 1) {
		/* 
		 * For SMP systems, create twice as many arenas as there are
		 * CPUs by default.
		 */
		opt_narenas_lshift++;
	}

	/* Determine how many arenas to use. */
	narenas = 1;
	if (opt_narenas_lshift > 0)
		narenas <<= opt_narenas_lshift;

#ifdef NO_TLS
	if (narenas > 1) {
		static const unsigned primes[] = {1, 3, 5, 7, 11, 13, 17, 19,
		    23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
		    89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,
		    151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211,
		    223, 227, 229, 233, 239, 241, 251, 257, 263};
		unsigned i, nprimes, parenas;

		/*
		 * Pick a prime number of hash arenas that is more than narenas
		 * so that direct hashing of pthread_self() pointers tends to
		 * spread allocations evenly among the arenas.
		 */
		assert((narenas & 1) == 0); /* narenas must be even. */
		nprimes = sizeof(primes) / sizeof(unsigned);
		parenas = primes[nprimes - 1]; /* In case not enough primes. */
		for (i = 1; i < nprimes; i++) {
			if (primes[i] > narenas) {
				parenas = primes[i];
				break;
			}
		}
		narenas = parenas;
	}
#endif

#ifndef NO_TLS
	next_arena = 0;
#endif

	/* Allocate and initialize arenas. */
	arenas = (arena_t **)base_alloc(sizeof(arena_t *) * narenas);
	if (arenas == NULL)
		return (true);
	/*
	 * Zero the array.  In practice, this should always be pre-zeroed,
	 * since it was just mmap()ed, but let's be sure.
	 */
	memset(arenas, 0, sizeof(arena_t *) * narenas);

	/*
	 * Initialize one arena here.  The rest are lazily created in
	 * arena_choose_hard().
	 */
	arenas_extend(0);
	if (arenas[0] == NULL)
		return (true);

	malloc_mutex_init(&arenas_mtx);

	malloc_initialized = true;
	return (false);
}

/*
 * End library-internal functions.
 */
/******************************************************************************/
/*
 * Begin malloc(3)-compatible functions.
 */

void *
malloc(size_t size)
{
	void *ret;
	arena_t *arena;

	if (malloc_init()) {
		ret = NULL;
		goto RETURN;
	}

	if (size == 0) {
		if (opt_sysv == false)
			ret = &nil;
		else
			ret = NULL;
		goto RETURN;
	}

	arena = choose_arena();
	if (arena != NULL)
		ret = imalloc(arena, size);
	else
		ret = NULL;

RETURN:
	if (ret == NULL) {
		if (opt_xmalloc) {
			malloc_printf("%s: (malloc) Error in malloc(%zu):"
			    " out of memory\n", _getprogname(), size);
			abort();
		}
		errno = ENOMEM;
	} else if (opt_zero)
		memset(ret, 0, size);

	UTRACE(0, size, ret);
	return (ret);
}

int
posix_memalign(void **memptr, size_t alignment, size_t size)
{
	int ret;
	arena_t *arena;
	void *result;

	if (malloc_init())
		result = NULL;
	else {
		/* Make sure that alignment is a large enough power of 2. */
		if (((alignment - 1) & alignment) != 0
		    || alignment < sizeof(void *)) {
			if (opt_xmalloc) {
				malloc_printf("%s: (malloc) Error in"
				    " posix_memalign(%zu, %zu):"
				    " invalid alignment\n",
				    _getprogname(), alignment, size);
				abort();
			}
			result = NULL;
			ret = EINVAL;
			goto RETURN;
		}

		arena = choose_arena();
		if (arena != NULL)
			result = ipalloc(arena, alignment, size);
		else
			result = NULL;
	}

	if (result == NULL) {
		if (opt_xmalloc) {
			malloc_printf("%s: (malloc) Error in"
			    " posix_memalign(%zu, %zu): out of memory\n",
			    _getprogname(), alignment, size);
			abort();
		}
		ret = ENOMEM;
		goto RETURN;
	} else if (opt_zero)
		memset(result, 0, size);

	*memptr = result;
	ret = 0;

RETURN:
	UTRACE(0, size, result);
	return (ret);
}

void *
calloc(size_t num, size_t size)
{
	void *ret;
	arena_t *arena;

	if (malloc_init()) {
		ret = NULL;
		goto RETURN;
	}

	if (num * size == 0) {
		if (opt_sysv == false)
			ret = &nil;
		else
			ret = NULL;
		goto RETURN;
	} else if ((num * size) / size != num) {
		/* size_t overflow. */
		ret = NULL;
		goto RETURN;
	}

	arena = choose_arena();
	if (arena != NULL)
		ret = icalloc(arena, num, size);
	else
		ret = NULL;

RETURN:
	if (ret == NULL) {
		if (opt_xmalloc) {
			malloc_printf("%s: (malloc) Error in"
			    " calloc(%zu, %zu): out of memory\n", 
			    _getprogname(), num, size);
			abort();
		}
		errno = ENOMEM;
	} else if (opt_zero) {
		/*
		 * This has the side effect of faulting pages in, even if the
		 * pages are pre-zeroed by the kernel.
		 */
		memset(ret, 0, num * size);
	}

	UTRACE(0, num * size, ret);
	return (ret);
}

void *
realloc(void *ptr, size_t size)
{
	void *ret;

	if (size != 0) {
		arena_t *arena;

		if (ptr != &nil && ptr != NULL) {
			assert(malloc_initialized);

			arena = choose_arena();
			if (arena != NULL)
				ret = iralloc(arena, ptr, size);
			else
				ret = NULL;

			if (ret == NULL) {
				if (opt_xmalloc) {
					malloc_printf("%s: (malloc) Error in"
					    " ralloc(%p, %zu): out of memory\n",
					    _getprogname(), ptr, size);
					abort();
				}
				errno = ENOMEM;
			} else if (opt_zero) {
				size_t old_size;

				old_size = isalloc(ptr);

				if (old_size < size) {
				    memset(&((char *)ret)[old_size], 0,
					    size - old_size);
				}
			}
		} else {
			if (malloc_init())
				ret = NULL;
			else {
				arena = choose_arena();
				if (arena != NULL)
					ret = imalloc(arena, size);
				else
					ret = NULL;
			}

			if (ret == NULL) {
				if (opt_xmalloc) {
					malloc_printf("%s: (malloc) Error in"
					    " ralloc(%p, %zu): out of memory\n",
					    _getprogname(), ptr, size);
					abort();
				}
				errno = ENOMEM;
			} else if (opt_zero)
				memset(ret, 0, size);
		}
	} else {
		if (ptr != &nil && ptr != NULL)
			idalloc(ptr);

		ret = &nil;
	}

	UTRACE(ptr, size, ret);
	return (ret);
}

void
free(void *ptr)
{

	UTRACE(ptr, 0, 0);
	if (ptr != &nil && ptr != NULL) {
		assert(malloc_initialized);

		idalloc(ptr);
	}
}

/*
 * End malloc(3)-compatible functions.
 */
/******************************************************************************/
/*
 * Begin library-private functions, used by threading libraries for protection
 * of malloc during fork().  These functions are only called if the program is
 * running in threaded mode, so there is no need to check whether the program
 * is threaded here.
 */

void
_malloc_prefork(void)
{
	unsigned i;

	/* Acquire all mutexes in a safe order. */

	malloc_mutex_lock(&arenas_mtx);
	for (i = 0; i < narenas; i++) {
		if (arenas[i] != NULL)
			malloc_mutex_lock(&arenas[i]->mtx);
	}
	malloc_mutex_unlock(&arenas_mtx);

	malloc_mutex_lock(&base_mtx);

	malloc_mutex_lock(&chunks_mtx);
}

void
_malloc_postfork(void)
{
	unsigned i;

	/* Release all mutexes, now that fork() has completed. */

	malloc_mutex_unlock(&chunks_mtx);

	malloc_mutex_unlock(&base_mtx);

	malloc_mutex_lock(&arenas_mtx);
	for (i = 0; i < narenas; i++) {
		if (arenas[i] != NULL)
			malloc_mutex_unlock(&arenas[i]->mtx);
	}
	malloc_mutex_unlock(&arenas_mtx);
}

/*
 * End library-private functions.
 */
/******************************************************************************/
OpenPOWER on IntegriCloud