summaryrefslogtreecommitdiff
path: root/external/vpc/tier0/memstd.cpp
blob: 20a8aec4aaa57ec5426865c8a418b938b3d2a48b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
//========= Copyright (c) 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Memory allocation!
//
// $NoKeywords: $
//=============================================================================//

#include "tier0/platform.h"


#if !defined(STEAM) && !defined(NO_MALLOC_OVERRIDE)


//#include <malloc.h>

#include <algorithm>

#include "tier0/dbg.h"
#include "tier0/memalloc.h"
#include "tier0/threadtools.h"
#include "mem_helpers.h"
#include "memstd.h"
#include "tier0/stacktools.h"
#include "tier0/minidump.h"
#ifdef _X360
#include "xbox/xbox_console.h"
#endif

#ifdef _PS3
#include "memoverride_ps3.h"
#endif

#ifndef _WIN32
#define IsDebuggerPresent() false
#endif

#ifdef USE_LIGHT_MEM_DEBUG
#undef USE_MEM_DEBUG
#pragma message("*** USE_LIGHT_MEM_DEBUG is ON ***")
#pragma optimize( "", off )
#endif

#define DEF_REGION 0

#if defined( _WIN32 ) || defined( _PS3 )
#define USE_DLMALLOC
#define MEMALLOC_SEGMENT_MIXED
#define MBH_SIZE_MB ( 45 + MBYTES_STEAM_MBH_USAGE )
//#define MEMALLOC_REGIONS
#endif // _WIN32 || _PS3

#ifndef USE_DLMALLOC
#ifdef _PS3
#define malloc_internal( region, bytes ) (g_pMemOverrideRawCrtFns->pfn_malloc)(bytes)
#define malloc_aligned_internal( region, bytes, align ) (g_pMemOverrideRawCrtFns->pfn_memalign)(align, bytes)
#define realloc_internal (g_pMemOverrideRawCrtFns->pfn_realloc)
#define realloc_aligned_internal (g_pMemOverrideRawCrtFns->pfn_reallocalign)
#define free_internal (g_pMemOverrideRawCrtFns->pfn_free)
#define msize_internal (g_pMemOverrideRawCrtFns->pfn_malloc_usable_size)
#define compact_internal() (0)
#define heapstats_internal(p) (void)(0)
#else // _PS3
#define malloc_internal( region, bytes) malloc(bytes)
#define malloc_aligned_internal( region, bytes, align ) memalign(align, bytes)
#define realloc_internal realloc
#define realloc_aligned_internal realloc
#define free_internal free
#ifdef POSIX
#define msize_internal malloc_usable_size
#else  // POSIX
#define msize_internal _msize
#endif // POSIX
#define compact_internal() (0)
#define heapstats_internal(p) (void)(0)
#endif // _PS3
#else // USE_DLMALLOC
#define MSPACES 1
#include "dlmalloc/malloc-2.8.3.h"

void *g_AllocRegions[] = 
{
#ifndef MEMALLOC_REGIONS
#ifdef MEMALLOC_SEGMENT_MIXED
	create_mspace( 0, 1 ), // unified
	create_mspace( MBH_SIZE_MB*1024*1024, 1 ),
#else
	create_mspace( 100*1024*1024, 1 ),
#endif
#else  // MEMALLOC_REGIONS
	// @TODO: per DLL regions didn't work out very well. flux of usage left too much overhead. need to try lifetime-based management [6/9/2009 tom]
	create_mspace( 82*1024*1024, 1 ), // unified
#endif // MEMALLOC_REGIONS
};

#ifndef MEMALLOC_REGIONS
#ifndef MEMALLOC_SEGMENT_MIXED
#define SelectRegion( region, bytes ) 0
#else
// NOTE: this split is designed to force the 'large block' heap to ONLY perform virtual allocs (see
//       DEFAULT_MMAP_THRESHOLD in malloc.cpp), to avoid ANY fragmentation or waste in an internal arena
#define REGION_SPLIT (256*1024)
#define SelectRegion( region, bytes ) g_AllocRegions[bytes < REGION_SPLIT]
#endif
#else  // MEMALLOC_REGIONS
#define SelectRegion( region, bytes ) g_AllocRegions[region]
#endif // MEMALLOC_REGIONS

#define malloc_internal( region, bytes ) mspace_malloc(SelectRegion(region,bytes), bytes)
#define malloc_aligned_internal( region, bytes, align ) mspace_memalign(SelectRegion(region,bytes), align, bytes)
FORCEINLINE void *realloc_aligned_internal( void *mem, size_t bytes, size_t align )
{
	// TODO: implement realloc_aligned inside dlmalloc (requires splitting realloc's existing
	//       'grow in-place' code into a new function, then call that w/ alloc_align/copy/free on failure)
	byte *newMem = (byte *)dlrealloc( mem, bytes );
	if ( ((size_t)newMem&(align-1)) == 0 )
		return newMem;
	// realloc broke alignment...
	byte *fallback = (byte *)malloc_aligned_internal( DEF_REGION, bytes, align );
	if ( !fallback )
		return NULL;
	memcpy( fallback, newMem, bytes );
	dlfree( newMem );
	return fallback;
}

inline size_t compact_internal()
{
	size_t start = 0, end = 0;

	for ( int i = 0; i < ARRAYSIZE(g_AllocRegions); i++ )
	{
		start += mspace_footprint( g_AllocRegions[i] );
		mspace_trim( g_AllocRegions[i], 0 );
		end += mspace_footprint( g_AllocRegions[i] );
	}
	
	return ( start - end );
}

inline void heapstats_internal( FILE *pFile )
{
	// @TODO: improve this presentation, as a table [6/1/2009 tom]
	char buf[1024];
	for ( int i = 0; i < ARRAYSIZE( g_AllocRegions ); i++ )
	{
		struct mallinfo info = mspace_mallinfo(      g_AllocRegions[ i ] );
		size_t footPrint     = mspace_footprint(     g_AllocRegions[ i ] );
		size_t maxFootPrint  = mspace_max_footprint( g_AllocRegions[ i ] );
		_snprintf( buf, sizeof(buf),
			"\ndlmalloc mspace %d (%s)\n"
				"     %d:footprint     -%10d (total space used by the mspace)\n"
				"     %d:footprint_max -%10d (maximum total space used by the mspace)\n"
				"     %d:arena         -%10d (non-mmapped space allocated from system)\n"
				"     %d:ordblks       -%10d (number of free chunks)\n"
				"     %d:hblkhd        -%10d (space in mmapped regions)\n"
				"     %d:usmblks       -%10d (maximum total allocated space)\n"
				"     %d:uordblks      -%10d (total allocated space)\n"
				"     %d:fordblks      -%10d (total free space)\n"
				"     %d:keepcost      -%10d (releasable (via malloc_trim) space)\n",
				i, i?"medium-block":"large-block", i,footPrint, i,maxFootPrint, i,info.arena, i,info.ordblks, i,info.hblkhd, i,info.usmblks, i,info.uordblks, i,info.fordblks, i,info.keepcost );
		if ( pFile )
			fprintf( pFile, "%s", buf );
		else
			Msg( "%s", buf );
	}
}

#define realloc_internal dlrealloc
#define free_internal dlfree
#define msize_internal dlmalloc_usable_size
#endif // USE_DLMALLOC

#ifdef TIME_ALLOC
CAverageCycleCounter g_MallocCounter;
CAverageCycleCounter g_ReallocCounter;
CAverageCycleCounter g_FreeCounter;

#define PrintOne( name ) \
	Msg("%-48s: %6.4f avg (%8.1f total, %7.3f peak, %5d iters)\n",  \
		#name, \
		g_##name##Counter.GetAverageMilliseconds(), \
		g_##name##Counter.GetTotalMilliseconds(), \
		g_##name##Counter.GetPeakMilliseconds(), \
		g_##name##Counter.GetIters() ); \
	memset( &g_##name##Counter, 0, sizeof(g_##name##Counter) )

void PrintAllocTimes()
{
	PrintOne( Malloc );
	PrintOne( Realloc );
	PrintOne( Free );
}

#define PROFILE_ALLOC(name) CAverageTimeMarker name##_ATM( &g_##name##Counter )

#else  // TIME_ALLOC
#define PROFILE_ALLOC( name ) ((void)0)
#define PrintAllocTimes() ((void)0)
#endif // TIME_ALLOC

#if _MSC_VER < 1400 && defined( MSVC ) && !defined(_STATIC_LINKED) && (defined(_DEBUG) || defined(USE_MEM_DEBUG))
void *operator new( unsigned int nSize, int nBlockUse, const char *pFileName, int nLine )
{
	return ::operator new( nSize );
}

void *operator new[] ( unsigned int nSize, int nBlockUse, const char *pFileName, int nLine )
{
	return ::operator new[]( nSize );
}
#endif

#include "mem_impl_type.h"
#if MEM_IMPL_TYPE_STD

//-----------------------------------------------------------------------------
// Singleton...
//-----------------------------------------------------------------------------
#pragma warning( disable:4074 ) // warning C4074: initializers put in compiler reserved initialization area
#pragma init_seg( compiler )

#if MEM_SBH_ENABLED
CSmallBlockPool< CStdMemAlloc::CFixedAllocator< MBYTES_PRIMARY_SBH, true> >::SharedData_t CSmallBlockPool< CStdMemAlloc::CFixedAllocator< MBYTES_PRIMARY_SBH, true> >::gm_SharedData CONSTRUCT_EARLY;
#ifdef MEMALLOC_USE_SECONDARY_SBH
CSmallBlockPool< CStdMemAlloc::CFixedAllocator< MBYTES_SECONDARY_SBH, false> >::SharedData_t CSmallBlockPool< CStdMemAlloc::CFixedAllocator< MBYTES_SECONDARY_SBH, false> >::gm_SharedData CONSTRUCT_EARLY;
#endif
#ifndef MEMALLOC_NO_FALLBACK
CSmallBlockPool< CStdMemAlloc::CVirtualAllocator >::SharedData_t CSmallBlockPool< CStdMemAlloc::CVirtualAllocator >::gm_SharedData CONSTRUCT_EARLY;
#endif
#endif // MEM_SBH_ENABLED

static CStdMemAlloc s_StdMemAlloc CONSTRUCT_EARLY;

#ifdef _PS3

MemOverrideRawCrtFunctions_t *g_pMemOverrideRawCrtFns;
IMemAlloc *g_pMemAllocInternalPS3 = &s_StdMemAlloc;
PLATFORM_OVERRIDE_MEM_ALLOC_INTERNAL_PS3_IMPL

#else // !_PS3

#ifndef TIER0_VALIDATE_HEAP
IMemAlloc *g_pMemAlloc = &s_StdMemAlloc;
#else
IMemAlloc *g_pActualAlloc = &s_StdMemAlloc;
#endif

#endif // _PS3

CStdMemAlloc::CStdMemAlloc()
:	m_pfnFailHandler( DefaultFailHandler ),
	m_sMemoryAllocFailed( (size_t)0 ),
	m_bInCompact( false )
{
#ifdef _PS3
	g_pMemAllocInternalPS3 = &s_StdMemAlloc;
	PLATFORM_OVERRIDE_MEM_ALLOC_INTERNAL_PS3.m_pMemAllocCached = &s_StdMemAlloc;
	malloc_managed_size mms;
	mms.current_inuse_size = 0x12345678;
	mms.current_system_size = 0x09ABCDEF;
	mms.max_system_size = reinterpret_cast< size_t >( this );
	int iResult = malloc_stats( &mms );
	g_pMemOverrideRawCrtFns = reinterpret_cast< MemOverrideRawCrtFunctions_t * >( iResult );
#endif
}

#if MEM_SBH_ENABLED
//-----------------------------------------------------------------------------
// Small block heap (multi-pool)
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
template <typename T>
inline T MemAlign( T val, unsigned alignment )
{
	return (T)( ( (unsigned)val + alignment - 1 ) & ~( alignment - 1 ) );
}

//-----------------------------------------------------------------------------
// 
//-----------------------------------------------------------------------------

template <typename CAllocator>
void CSmallBlockPool<CAllocator>::Init( unsigned nBlockSize )
{
	SharedData_t *pSharedData = GetSharedData();
	if ( !pSharedData->m_pBase )
	{
		pSharedData->m_pBase = pSharedData->m_Allocator.AllocatePoolMemory();
		pSharedData->m_pLimit = pSharedData->m_pBase + CAllocator::TOTAL_BYTES;
		pSharedData->m_pNextBlock = pSharedData->m_pBase;
	}

	if ( !( nBlockSize % MIN_SBH_ALIGN == 0 && nBlockSize >= MIN_SBH_BLOCK && nBlockSize >= sizeof(TSLNodeBase_t) ) )
		DebuggerBreak();

	m_nBlockSize = nBlockSize;
	m_pNextAlloc = NULL;
	m_nCommittedPages = 0;
}

template <typename CAllocator>
size_t CSmallBlockPool<CAllocator>::GetBlockSize()
{
	return m_nBlockSize;
}

// Define VALIDATE_SBH_FREE_LIST to a given block size to validate that pool's freelist (it'll crash on the next alloc/free after the list is corrupted)
// NOTE: this may affect perf more than USE_LIGHT_MEM_DEBUG
//#define VALIDATE_SBH_FREE_LIST 320
template <typename CAllocator>
void CSmallBlockPool<CAllocator>::ValidateFreelist( SharedData_t *pSharedData )
{
#ifdef VALIDATE_SBH_FREE_LIST
	if ( m_nBlockSize != VALIDATE_SBH_FREE_LIST )
		return;
	static int count = 0;
	count++; // Track when the corruption occurs, if repeatable
	pSharedData->m_Lock.LockForWrite();
#ifdef USE_NATIVE_SLIST
	TSLNodeBase_t *pNode = (TSLNodeBase_t *)(m_FreeList.AccessUnprotected()->Next.Next);
#else
	TSLNodeBase_t *pNode = (TSLNodeBase_t *)(m_FreeList.AccessUnprotected()->value.Next);
#endif
	while( pNode )
		pNode = pNode->Next;
	pSharedData->m_Lock.UnlockWrite();
#endif // VALIDATE_SBH_FREE_LIST
}

template <typename CAllocator>
void *CSmallBlockPool<CAllocator>::Alloc()
{
	SharedData_t *pSharedData = GetSharedData();

	ValidateFreelist( pSharedData );

	CThreadSpinRWLock &sharedLock = pSharedData->m_Lock;
	if ( !sharedLock.TryLockForRead() )
	{
		sharedLock.LockForRead();
	}
	byte *pResult;
	intp iPage = -1;
	int iThreadPriority = INT_MAX;

	while (1)
	{
		pResult = m_FreeList.Pop();
		if ( !pResult )
		{
			int nBlockSize = m_nBlockSize;
			byte *pNextAlloc;
			while (1)
			{
				pResult = m_pNextAlloc;
				if ( pResult )
				{
					pNextAlloc = pResult + nBlockSize;
					if ( ( ( (uintp)(pNextAlloc) - 1 ) % BYTES_PAGE ) + nBlockSize > BYTES_PAGE  )
					{
						// Crossed a page boundary
						pNextAlloc = 0;
					}
					if ( m_pNextAlloc.AssignIf( pResult, pNextAlloc ) )
					{
						iPage = (size_t)((byte *)pResult - pSharedData->m_pBase) / BYTES_PAGE;
						break;
					}
				}
				else if ( m_CommitMutex.TryLock() )
				{
					if ( !m_pNextAlloc )
					{
						PageStatus_t *pAllocatedPageStatus = (PageStatus_t *)pSharedData->m_FreePages.Pop();
						if ( pAllocatedPageStatus )
						{
							iPage = pAllocatedPageStatus - &pSharedData->m_PageStatus[0];
						}
						else
						{
							while (1)
							{
								byte *pBlock = pSharedData->m_pNextBlock;
								if ( pBlock >= pSharedData->m_pLimit )
								{
									break;
								}
								if ( ThreadInterlockedAssignPointerIf( (void **)&pSharedData->m_pNextBlock, (void *)( pBlock + BYTES_PAGE ), (void *)pBlock ) )
								{
									iPage = (size_t)((byte *)pBlock - pSharedData->m_pBase) / BYTES_PAGE;
									pAllocatedPageStatus = &pSharedData->m_PageStatus[iPage];
									break;
								}
							}
						}

						if ( pAllocatedPageStatus )
						{
							byte *pBlock = pSharedData->m_pBase + ( iPage * BYTES_PAGE );
							if ( pAllocatedPageStatus->m_nAllocated == NOT_COMMITTED )
							{
								pSharedData->m_Allocator.Commit( pBlock );
							}

							pAllocatedPageStatus->m_pPool = this;
							pAllocatedPageStatus->m_nAllocated = 0;
							pAllocatedPageStatus->m_pNextPageInPool = m_pFirstPage;
							m_pFirstPage = pAllocatedPageStatus;
#ifdef TRACK_SBH_COUNTS
							m_nFreeBlocks += ( BYTES_PAGE / m_nBlockSize );
#endif
							m_nCommittedPages++;
							m_pNextAlloc = pBlock;
						}
						else
						{
							m_pNextAlloc = NULL;
							m_CommitMutex.Unlock();
							sharedLock.UnlockRead();
							return NULL;
						}
					}
					m_CommitMutex.Unlock();
				}
				else
				{
					if ( iThreadPriority == INT_MAX)
					{
						iThreadPriority = ThreadGetPriority();
					}

					if ( iThreadPriority > 0 )
					{
						ThreadSleep( 0 );
					}
				}
			}

			if ( pResult )
			{
				break;
			}
		}
		else
		{
			iPage = (size_t)((byte *)pResult - pSharedData->m_pBase) / BYTES_PAGE;
			break;
		}
	}

#ifdef TRACK_SBH_COUNTS
	--m_nFreeBlocks;
#endif
	++pSharedData->m_PageStatus[iPage].m_nAllocated;
	sharedLock.UnlockRead();

	return pResult;
}

template <typename CAllocator>
void CSmallBlockPool<CAllocator>::Free( void *p )
{
	SharedData_t *pSharedData = GetSharedData();
	size_t iPage = (size_t)((byte *)p - pSharedData->m_pBase) / BYTES_PAGE;

	CThreadSpinRWLock &sharedLock = pSharedData->m_Lock;
	if ( !sharedLock.TryLockForRead() )
	{
		sharedLock.LockForRead();
	}
	--pSharedData->m_PageStatus[iPage].m_nAllocated;
#ifdef TRACK_SBH_COUNTS
	++m_nFreeBlocks;
#endif
	m_FreeList.Push( p );
	pSharedData->m_Lock.UnlockRead();

	ValidateFreelist( pSharedData );
}

// Count the free blocks.  
template <typename CAllocator>
int CSmallBlockPool<CAllocator>::CountFreeBlocks()
{
#ifdef TRACK_SBH_COUNTS
	return m_nFreeBlocks;
#else
	return 0;
#endif
}

// Size of committed memory managed by this heap:
template <typename CAllocator>
int CSmallBlockPool<CAllocator>::GetCommittedSize()
{
	return m_nCommittedPages * BYTES_PAGE;
}

// Return the total blocks memory is committed for in the heap
template <typename CAllocator>
int CSmallBlockPool<CAllocator>::CountCommittedBlocks()
{		 
	return m_nCommittedPages * ( BYTES_PAGE / m_nBlockSize );
}

// Count the number of allocated blocks in the heap:
template <typename CAllocator>
int CSmallBlockPool<CAllocator>::CountAllocatedBlocks()
{
#ifdef TRACK_SBH_COUNTS
	return CountCommittedBlocks() - CountFreeBlocks();
#else
	return 0;
#endif
}

template <typename CAllocator>
int CSmallBlockPool<CAllocator>::PageSort( const void *p1, const void *p2 ) 
{
	SharedData_t *pSharedData = GetSharedData();
	return pSharedData->m_PageStatus[*((int *)p1)].m_SortList.Count() - pSharedData->m_PageStatus[*((int *)p2)].m_SortList.Count();
}


template <typename CAllocator>
bool CSmallBlockPool<CAllocator>::RemovePagesFromFreeList( byte **pPages, int nPages, bool bSortList )
{
	// Since we don't use the depth of the tslist, and sequence is only used for push, we can remove in-place
	int i;
	byte **pLimits = (byte **)stackalloc( nPages * sizeof(byte *) );
	int nBlocksNotInFreeList = 0;
	for ( i = 0; i < nPages; i++ )
	{
		pLimits[i] = pPages[i] + BYTES_PAGE;

		if ( m_pNextAlloc >= pPages[i] && m_pNextAlloc < pLimits[i] )
		{
			nBlocksNotInFreeList = ( pLimits[i] - m_pNextAlloc ) / m_nBlockSize;
			m_pNextAlloc = NULL;
		}
	}

	int iTarget = ( ( BYTES_PAGE/m_nBlockSize ) * nPages ) - nBlocksNotInFreeList;
	int iCount = 0;

	TSLHead_t *pRawFreeList = m_FreeList.AccessUnprotected();
	bool bRemove;
	if ( !bSortList || m_nCommittedPages - nPages == 1 )
	{
#ifdef USE_NATIVE_SLIST
		TSLNodeBase_t **ppPrevNext = (TSLNodeBase_t **)&(pRawFreeList->Next);
#else
		TSLNodeBase_t **ppPrevNext = (TSLNodeBase_t **)&(pRawFreeList->value.Next);
#endif
		TSLNodeBase_t *pNode = *ppPrevNext;
		while ( pNode && iCount != iTarget )
		{
			bRemove = false;
			for ( i = 0; i < nPages; i++ )
			{
				if ( (byte *)pNode >= pPages[i] && (byte *)pNode < pLimits[i] )
				{
					bRemove = true;
					break;
				}
			}

			if ( bRemove )
			{
				iCount++;
				*ppPrevNext = pNode->Next;
			}
			else
			{
				*ppPrevNext = pNode;
				ppPrevNext = &pNode->Next;
			}
			pNode = pNode->Next;
		}
	}
	else
	{
		SharedData_t *pSharedData = GetSharedData();
		byte *pSharedBase = pSharedData->m_pBase;
		TSLNodeBase_t *pNode = m_FreeList.Detach();
		TSLNodeBase_t *pNext;
		int iSortPage;

		int nSortPages = 0;
		int *sortPages = (int *)stackalloc( m_nCommittedPages * sizeof(int) );
		while ( pNode )
		{
			pNext = pNode->Next;
			bRemove = false;
			for ( i = 0; i < nPages; i++ )
			{
				if ( (byte *)pNode >= pPages[i] && (byte *)pNode < pLimits[i] )
				{
					iCount++;
					bRemove = true;
					break;
				}
			}

			if ( !bRemove )
			{
				iSortPage = ( (byte *)pNode - pSharedBase ) / BYTES_PAGE;
				if ( !pSharedData->m_PageStatus[iSortPage].m_SortList.Count() )
				{
					sortPages[nSortPages++] = iSortPage;
				}
				pSharedData->m_PageStatus[iSortPage].m_SortList.Push( pNode );
			}

			pNode = pNext;
		}
	
		if ( nSortPages > 1 )
		{
			qsort( sortPages, nSortPages, sizeof(int), &PageSort );
		}
		for ( i = 0; i < nSortPages; i++ )
		{
			while ( ( pNode = pSharedData->m_PageStatus[sortPages[i]].m_SortList.Pop() ) != NULL )
			{
				m_FreeList.Push( pNode );
			}
		}
	}
	if ( iTarget != iCount )
	{
		DebuggerBreakIfDebugging();
	}

	return ( iTarget == iCount );
}


template <typename CAllocator>
size_t CSmallBlockPool<CAllocator>::Compact( bool bIncremental )
{
	static bool bWarnedCorruption;
	bool bIsCorrupt = false;
	int i;
	size_t nFreed = 0;
	SharedData_t *pSharedData = GetSharedData();
	pSharedData->m_Lock.LockForWrite();

	if ( m_pFirstPage )
	{
		PageStatus_t **pReleasedPages = (PageStatus_t **)stackalloc( m_nCommittedPages * sizeof(PageStatus_t *) );
		PageStatus_t **pReleasedPagesPrevs = (PageStatus_t **)stackalloc( m_nCommittedPages * sizeof(PageStatus_t *) );
		byte **pPageBases = (byte **)stackalloc( m_nCommittedPages * sizeof(byte *) );
		int nPages = 0;
		
		// Gather the pages to return to the backing pool
		PageStatus_t *pPage = m_pFirstPage;
		PageStatus_t *pPagePrev = NULL;
		while ( pPage )
		{
			if ( pPage->m_nAllocated == 0 )
			{
				pReleasedPages[nPages] = pPage;
				pPageBases[nPages] = pSharedData->m_pBase + ( pPage - &pSharedData->m_PageStatus[0] ) * BYTES_PAGE;
				pReleasedPagesPrevs[nPages] = pPagePrev;
				nPages++;

				if ( bIncremental )
				{
					break;
				}
			}
			pPagePrev = pPage;
			pPage = pPage->m_pNextPageInPool;
		}

		if ( nPages )
		{
			// Remove the pages from the pool's free list
			if ( !RemovePagesFromFreeList( pPageBases, nPages, !bIncremental ) && !bWarnedCorruption )
			{
				// We don't know which of the pages encountered an incomplete free list
				// so we'll just push them all back in and hope for the best. This isn't
				// ventilator control software!
				bWarnedCorruption = true;
				bIsCorrupt = true;
			}

			nFreed = nPages * BYTES_PAGE;
			m_nCommittedPages -= nPages;

#ifdef TRACK_SBH_COUNTS
			m_nFreeBlocks -= nPages * ( BYTES_PAGE / m_nBlockSize );
#endif

			// Unlink the pages
			for ( i = nPages - 1; i >= 0; --i )
			{
				if ( pReleasedPagesPrevs[i] )
				{
					pReleasedPagesPrevs[i]->m_pNextPageInPool = pReleasedPages[i]->m_pNextPageInPool;
				}
				else
				{
					m_pFirstPage = pReleasedPages[i]->m_pNextPageInPool;
				}
				pReleasedPages[i]->m_pNextPageInPool = NULL;
				pReleasedPages[i]->m_pPool = NULL;
			}

			// Push them onto the backing free lists
			if ( !pSharedData->m_Allocator.IsVirtual() )
			{
				for ( i = 0; i < nPages; i++ )
				{
					pSharedData->m_FreePages.Push( pReleasedPages[i] );
				}
			}
			else
			{
				int nMinReserve = ( bIncremental ) ? CAllocator::MIN_RESERVE_PAGES * 8 : CAllocator::MIN_RESERVE_PAGES;
				int nReserveNeeded = nMinReserve - pSharedData->m_FreePages.Count();
				if ( nReserveNeeded > 0 )
				{
					int nToKeepCommitted = MIN( nReserveNeeded, nPages );
					while ( nToKeepCommitted-- )
					{
						nPages--;
						pSharedData->m_FreePages.Push( pReleasedPages[nPages] );
					}
				}

				if ( nPages )
				{
					// Detach the list, push the decommitted page on, iterate up to previous 
					// decommits, but them on, then push the committed pages on
					TSLNodeBase_t *pNodes = pSharedData->m_FreePages.Detach();
					for ( i = 0; i < nPages; i++ )
					{
						pReleasedPages[i]->m_nAllocated = NOT_COMMITTED;
						pSharedData->m_Allocator.Decommit( pPageBases[i] );
						pSharedData->m_FreePages.Push( pReleasedPages[i] );
					}

					TSLNodeBase_t *pCur, *pTemp = NULL;
					pCur = pNodes;
					while ( pCur )
					{
						if ( ((PageStatus_t *)pCur)->m_nAllocated == NOT_COMMITTED )
						{
							if ( pTemp )
							{
								pTemp->Next = NULL;
							}
							else
							{
								pNodes = NULL; // The list only has decommitted pages, don't go circular
							}

							while ( pCur )
							{
								pTemp = pCur->Next;
								pSharedData->m_FreePages.Push( pCur );
								pCur = pTemp;
							}
							break;
						}
						pTemp = pCur;
						pCur = pCur->Next;
					}

					while ( pNodes )
					{
						pTemp = pNodes->Next;
						pSharedData->m_FreePages.Push( pNodes );
						pNodes = pTemp;
					}
				}
			}
		}
	}
	pSharedData->m_Lock.UnlockWrite();
	if ( bIsCorrupt )
	{
		Warning( "***** HEAP IS CORRUPT (free compromised for block size %d,in %s heap, possible write after free *****)\n", m_nBlockSize, ( pSharedData->m_Allocator.IsVirtual() ) ? "virtual" : "physical" );
	}
	return nFreed;
}

template <typename CAllocator>
bool CSmallBlockPool<CAllocator>::Validate()
{
#ifdef NO_SBH
	return true;
#else
	int invalid = 0;

	SharedData_t *pSharedData = GetSharedData();
	pSharedData->m_Lock.LockForWrite();

	byte **pPageBases = (byte **)stackalloc( m_nCommittedPages * sizeof(byte *) );
	unsigned *pageCounts = (unsigned *)stackalloc( m_nCommittedPages * sizeof(unsigned) );
	memset( pageCounts, 0, m_nCommittedPages * sizeof(int) );
	unsigned nPages = 0;
	unsigned sumAllocated = 0;
	unsigned freeNotInFreeList = 0;

	// Validate page list is consistent
	if ( !m_pFirstPage )
	{
		if ( m_nCommittedPages != 0 )
		{
			invalid = __LINE__;
			goto notValid;
		}
	}
	else
	{
		PageStatus_t *pPage = m_pFirstPage;
		while ( pPage )
		{
			pPageBases[nPages] = pSharedData->m_pBase + ( pPage - &pSharedData->m_PageStatus[0] ) * BYTES_PAGE;
			if ( pPage->m_pPool != this )
			{
				invalid = __LINE__;
				goto notValid;
			}
			if ( nPages > m_nCommittedPages )
			{
				invalid = __LINE__;
				goto notValid;
			}
			sumAllocated += pPage->m_nAllocated;
			if ( m_pNextAlloc >= pPageBases[nPages] && m_pNextAlloc < pPageBases[nPages] + BYTES_PAGE )
			{
				freeNotInFreeList = pageCounts[nPages] = ( ( pPageBases[nPages] + BYTES_PAGE ) - m_pNextAlloc ) / m_nBlockSize;
			}

			nPages++;
			pPage = pPage->m_pNextPageInPool;
		};

		if ( nPages != m_nCommittedPages )
		{
			invalid = __LINE__;
			goto notValid;
		}
	}

	// Validate block counts
	{
		unsigned blocksPerPage = ( BYTES_PAGE / m_nBlockSize );
#ifdef USE_NATIVE_SLIST
		TSLNodeBase_t *pNode = (TSLNodeBase_t *)(m_FreeList.AccessUnprotected()->Next.Next);
#else
		TSLNodeBase_t *pNode = (TSLNodeBase_t *)(m_FreeList.AccessUnprotected()->value.Next);
#endif
		unsigned i;
		while ( pNode )
		{
			for ( i = 0; i < nPages; i++ )
			{
				if ( (byte *)pNode >= pPageBases[i] && (byte *)pNode < pPageBases[i] + BYTES_PAGE )
				{
					pageCounts[i]++;
					break;
				}
			}

			if ( i == nPages )
			{
				invalid = __LINE__;
				goto notValid;
			}

			pNode = pNode->Next;
		}

		PageStatus_t *pPage = m_pFirstPage;
		i = 0;
		while ( pPage )
		{
			unsigned nFreeOnPage = blocksPerPage - pPage->m_nAllocated;
			if ( nFreeOnPage != pageCounts[i++] )
			{
				invalid = __LINE__;
				goto notValid;
			}
			pPage = pPage->m_pNextPageInPool;
		}
	}

notValid:
	pSharedData->m_Lock.UnlockWrite();

	if ( invalid != 0 )
	{
		return false;
	}

	return true;
#endif
}


//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
template <typename CAllocator>
CSmallBlockHeap<CAllocator>::CSmallBlockHeap()
{
	m_pSharedData = CPool::GetSharedData();

	// Build a lookup table used to find the correct pool based on size
	const int MAX_TABLE = MAX_SBH_BLOCK >> 2;
	int i = 0;
	int nBytesElement = 0;
	CPool *pCurPool = NULL;
	int iCurPool = 0;

	// Blocks sized 0 - 128 are in pools in increments of 8
	for ( ; i < 32; i++ )
	{
		if ( (i + 1) % 2 == 1)
		{
			nBytesElement += 8;
			pCurPool = &m_Pools[iCurPool];
			pCurPool->Init( nBytesElement );
			iCurPool++;
			m_PoolLookup[i] = pCurPool;
		}
		else
		{
			m_PoolLookup[i] = pCurPool;
		}
	}

	// Blocks sized 129 - 256 are in pools in increments of 16
	for ( ; i < 64; i++ )
	{
		if ( (i + 1) % 4 == 1)
		{
			nBytesElement += 16;
			pCurPool = &m_Pools[iCurPool];
			pCurPool->Init( nBytesElement );
			iCurPool++;
			m_PoolLookup[i] = pCurPool;
		}
		else
		{
			m_PoolLookup[i] = pCurPool;
		}
	}


	// Blocks sized 257 - 512 are in pools in increments of 32
	for ( ; i < 128; i++ )
	{
		if ( (i + 1) % 8 == 1)
		{
			nBytesElement += 32;
			pCurPool = &m_Pools[iCurPool];
			pCurPool->Init( nBytesElement );
			iCurPool++;
			m_PoolLookup[i] = pCurPool;
		}
		else
		{
			m_PoolLookup[i] = pCurPool;
		}
	}

	// Blocks sized 513 - 768 are in pools in increments of 64
	for ( ; i < 192; i++ )
	{
		if ( (i + 1) % 16 == 1)
		{
			nBytesElement += 64;
			pCurPool = &m_Pools[iCurPool];
			pCurPool->Init( nBytesElement );
			iCurPool++;
			m_PoolLookup[i] = pCurPool;
		}
		else
		{
			m_PoolLookup[i] = pCurPool;
		}
	}

	// Blocks sized 769 - 1024 are in pools in increments of 128
	for ( ; i < 256; i++ )
	{
		if ( (i + 1) % 32 == 1)
		{
			nBytesElement += 128;
			pCurPool = &m_Pools[iCurPool];
			pCurPool->Init( nBytesElement );
			iCurPool++;
			m_PoolLookup[i] = pCurPool;
		}
		else
		{
			m_PoolLookup[i] = pCurPool;
		}
	}

	// Blocks sized 1025 - 2048 are in pools in increments of 256
	for ( ; i < MAX_TABLE; i++ )
	{
		if ( (i + 1) % 64 == 1)
		{
			nBytesElement += 256;
			pCurPool = &m_Pools[iCurPool];
			pCurPool->Init( nBytesElement );
			iCurPool++;
			m_PoolLookup[i] = pCurPool;
		}
		else
		{
			m_PoolLookup[i] = pCurPool;
		}
	}

	Assert( iCurPool == NUM_POOLS );
}

template <typename CAllocator>
bool CSmallBlockHeap<CAllocator>::ShouldUse( size_t nBytes )
{
	return ( nBytes <= MAX_SBH_BLOCK );
}

template <typename CAllocator>
bool CSmallBlockHeap<CAllocator>::IsOwner( void * p )
{
	if ( uintp(p) >= uintp(m_pSharedData->m_pBase) )
	{
		intp index = (intp)((byte *)p - m_pSharedData->m_pBase) / BYTES_PAGE;
		return ( index < ARRAYSIZE(m_pSharedData->m_PageStatus) );
	}
	return false;
}

template <typename CAllocator>
void *CSmallBlockHeap<CAllocator>::Alloc( size_t nBytes )
{
	if ( nBytes == 0)
	{
		nBytes = 1;
	}
	Assert( ShouldUse( nBytes ) );
	CPool *pPool = FindPool( nBytes );
	void *p = pPool->Alloc();
	return p;
}

template <typename CAllocator>
void *CSmallBlockHeap<CAllocator>::Realloc( void *p, size_t nBytes )
{
	if ( nBytes == 0)
	{
		nBytes = 1;
	}

	CPool *pOldPool = FindPool( p );
	CPool *pNewPool = ( ShouldUse( nBytes ) ) ? FindPool( nBytes ) : NULL;

	if ( pOldPool == pNewPool )
	{
		return p;
	}

	void *pNewBlock = NULL;

	if ( !pNewBlock )
	{
		pNewBlock = MemAlloc_Alloc( nBytes ); // Call back out so blocks can move from the secondary to the primary pools
	}

	if ( !pNewBlock )
	{
		pNewBlock = malloc_internal( DEF_REGION, nBytes );
	}

	if ( pNewBlock )
	{
		size_t nBytesCopy = MIN( nBytes, pOldPool->GetBlockSize() );
		memcpy( pNewBlock, p, nBytesCopy );
	} 
	else if ( nBytes < pOldPool->GetBlockSize() )
	{
		return p;
	}

	pOldPool->Free( p );

	return pNewBlock;
}

template <typename CAllocator>
void CSmallBlockHeap<CAllocator>::Free( void *p )
{
	CPool *pPool = FindPool( p );
	if ( pPool )
	{
		pPool->Free( p );
	}
	else
	{
		// we probably didn't hook some allocation and now we're freeing it or the heap has been trashed!
		DebuggerBreakIfDebugging();
	}
}

template <typename CAllocator>
size_t CSmallBlockHeap<CAllocator>::GetSize( void *p )
{
	CPool *pPool = FindPool( p );
	return pPool->GetBlockSize();
}

template <typename CAllocator>
void CSmallBlockHeap<CAllocator>::Usage( size_t &bytesCommitted, size_t &bytesAllocated )
{
	bytesCommitted = 0;
	bytesAllocated = 0;
	for ( int i = 0; i < NUM_POOLS; i++ )
	{
		bytesCommitted += m_Pools[i].GetCommittedSize();
		bytesAllocated += ( m_Pools[i].CountAllocatedBlocks() * m_Pools[i].GetBlockSize() );
	}
}

template <typename CAllocator>
void CSmallBlockHeap<CAllocator>::DumpStats( const char *pszTag, FILE *pFile )
{
	size_t bytesCommitted, bytesAllocated;
	Usage( bytesCommitted, bytesAllocated );

	if ( pFile )
	{

		for ( int i = 0; i < NUM_POOLS; i++ )
		{
			// output for vxconsole parsing
			fprintf( pFile, "Pool %2i: (size: %4u) blocks: allocated:%5i free:%5i committed:%5i (committed size:%4u kb)\n", 
				i, 
				m_Pools[i].GetBlockSize(), 
				m_Pools[i].CountAllocatedBlocks(), 
				m_Pools[i].CountFreeBlocks(),
				m_Pools[i].CountCommittedBlocks(), 
				m_Pools[i].GetCommittedSize() );
		}
		fprintf( pFile, "Totals (%s): Committed:%5u kb Allocated:%5u kb\n", pszTag, bytesCommitted / 1024, bytesAllocated / 1024 );
	}
	else
	{
		for ( int i = 0; i < NUM_POOLS; i++ )
		{
			Msg( "Pool %2i: (size: %4u) blocks: allocated:%5i free:%5i committed:%5i (committed size:%4u kb)\n",i, m_Pools[i].GetBlockSize(),m_Pools[i].CountAllocatedBlocks(), m_Pools[i].CountFreeBlocks(),m_Pools[i].CountCommittedBlocks(), m_Pools[i].GetCommittedSize() / 1024);
		}

		Msg( "Totals (%s): Committed:%5u kb Allocated:%5u kb\n", pszTag, bytesCommitted / 1024, bytesAllocated / 1024 );
	}
}

template <typename CAllocator>
CSmallBlockPool<CAllocator> *CSmallBlockHeap<CAllocator>::FindPool( size_t nBytes )
{
	return m_PoolLookup[(nBytes - 1) >> 2];
}

template <typename CAllocator>
CSmallBlockPool<CAllocator> *CSmallBlockHeap<CAllocator>::FindPool( void *p )
{
	// NOTE: If p < m_pBase, cast to unsigned size_t will cause it to be large
	size_t index = (size_t)((byte *)p - m_pSharedData->m_pBase) / BYTES_PAGE;
	if ( index < ARRAYSIZE(m_pSharedData->m_PageStatus) )
		return m_pSharedData->m_PageStatus[index].m_pPool;
	return NULL;
}

template <typename CAllocator>
size_t CSmallBlockHeap<CAllocator>::Compact( bool bIncremental )
{
	size_t nRecovered = 0;
	if ( bIncremental )
	{
		static int iLastIncremental;

		iLastIncremental++;
		for ( int i = 0; i < NUM_POOLS; i++ )
		{
			int idx = ( i + iLastIncremental ) % NUM_POOLS;
			nRecovered = m_Pools[idx].Compact( bIncremental );
			if ( nRecovered )
			{
				iLastIncremental = idx;
				break;
			}

		}
	}
	else
	{
		for ( int i = 0; i < NUM_POOLS; i++ )
		{
			nRecovered += m_Pools[i].Compact( bIncremental );
		}
	}
	return nRecovered;
}

template <typename CAllocator>
bool CSmallBlockHeap<CAllocator>::Validate()
{
	bool valid = true;
	for ( int i = 0; i < NUM_POOLS; i++ )
	{
		valid = m_Pools[i].Validate() && valid;
	}
	return valid;
}

#endif // MEM_SBH_ENABLED


//-----------------------------------------------------------------------------
// Lightweight memory tracking
//-----------------------------------------------------------------------------

#ifdef USE_LIGHT_MEM_DEBUG

#ifndef LIGHT_MEM_DEBUG_REQUIRES_CMD_LINE_SWITCH
#define UsingLMD() true
#else // LIGHT_MEM_DEBUG_REQUIRES_CMD_LINE_SWITCH
bool g_bUsingLMD = ( Plat_GetCommandLineA() ) ? ( strstr( Plat_GetCommandLineA(), "-uselmd" ) != NULL ) : false;
#define UsingLMD() g_bUsingLMD
#if defined( _PS3 )
#error "Plat_GetCommandLineA() not implemented on PS3"
#endif
#endif // LIGHT_MEM_DEBUG_REQUIRES_CMD_LINE_SWITCH

const char *g_pszUnknown = "unknown";

struct Sentinal_t
{
	DWORD value[4];
};

Sentinal_t g_HeadSentinel = 
{
	0xdeadbeef,
	0xbaadf00d,
	0xbd122969,
	0xdeadbeef,
};

Sentinal_t g_TailSentinel = 
{
	0xbaadf00d,
	0xbd122969,
	0xdeadbeef,
	0xbaadf00d,
};

const byte g_FreeFill = 0xdd;

static const uint LWD_FREE = 0;
static const uint LWD_ALLOCATED = 1;

#define LMD_STATUS_BITS ( 1 )
#define LMD_ALIGN_BITS  ( 32 - LMD_STATUS_BITS )
#define LMD_MAX_ALIGN   ( 1 << ( LMD_ALIGN_BITS - 1) )

struct AllocHeader_t
{
	const char *pszModule;
	int line;
	size_t nBytes;
	uint status : LMD_STATUS_BITS;
	uint align : LMD_ALIGN_BITS;
	Sentinal_t sentinal;
};

const int g_nRecentFrees = ( IsPC() ) ? 8192 : 512;
AllocHeader_t **g_pRecentFrees = (AllocHeader_t **)calloc( g_nRecentFrees, sizeof(AllocHeader_t *) );
int g_iNextFreeSlot;

#define INTERNAL_INLINE

#define LMDToHeader( pUserPtr )		( ((AllocHeader_t *)(pUserPtr)) - 1 )
#define LMDFromHeader( pHeader )	( (byte *)((pHeader) + 1) )

CThreadFastMutex g_LMDMutex;

const char *g_pLMDFileName = NULL;
int g_nLMDLine;
int g_iLMDDepth;

void LMDPushAllocDbgInfo( const char *pFileName, int nLine )
{
	if ( ThreadInMainThread() )
	{
		if ( !g_iLMDDepth )
		{
			g_pLMDFileName = pFileName;
			g_nLMDLine = nLine;
		}
		g_iLMDDepth++;
	}
}

void LMDPopAllocDbgInfo()
{
	if ( ThreadInMainThread() && g_iLMDDepth > 0 )
	{
		g_iLMDDepth--;
		if ( g_iLMDDepth == 0 )
		{
			g_pLMDFileName = NULL;
			g_nLMDLine = 0;
		}
	}
}


void LMDReportInvalidBlock( AllocHeader_t *pHeader, const char *pszMessage )
{
	char szMsg[256];
	if ( pHeader )
	{
		sprintf( szMsg, "HEAP IS CORRUPT: %s (block 0x%x, size %d, alignment %d)\n", pszMessage, (size_t)LMDFromHeader( pHeader ), pHeader->nBytes, pHeader->align );
	}
	else
	{
		sprintf( szMsg, "HEAP IS CORRUPT: %s\n", pszMessage );
	}
	if ( Plat_IsInDebugSession() )
	{
		DebuggerBreak();
	}
	else
	{
		WriteMiniDump();
	}
#ifdef IS_WINDOWS_PC
	::MessageBox( NULL, szMsg, "Error", MB_SYSTEMMODAL | MB_OK );
#else
	Warning( szMsg );
#endif
}

void LMDValidateBlock( AllocHeader_t *pHeader, bool bFreeList )
{
	if ( !pHeader )
		return;

	if ( memcmp( &pHeader->sentinal, &g_HeadSentinel, sizeof(Sentinal_t) ) != 0 )
	{
		LMDReportInvalidBlock( pHeader, "Head sentinel corrupt" );
	}
	if ( memcmp( ((Sentinal_t *)(LMDFromHeader( pHeader ) + pHeader->nBytes)), &g_TailSentinel, sizeof(Sentinal_t) ) != 0 )
	{
		LMDReportInvalidBlock( pHeader, "Tail sentinel corrupt" );
	}
	if ( bFreeList )
	{
		byte *pCur = (byte *)pHeader + sizeof(AllocHeader_t);
		byte *pLimit = pCur + pHeader->nBytes;
		while ( pCur != pLimit )
		{
			if ( *pCur++ != g_FreeFill )
			{
				LMDReportInvalidBlock( pHeader, "Write after free" );
			}
		}
	}
}


size_t LMDComputeHeaderSize( size_t align = 0 )
{
	if ( !align )
		return sizeof(AllocHeader_t);
	// For aligned allocs, the header is preceded by padding which maintains alignment
	if ( align > LMD_MAX_ALIGN )
		s_StdMemAlloc.SetCRTAllocFailed( align ); // TODO: could convert alignment to exponent to get around this, or use a flag for alignments over 1KB or 1MB...
	return ( ( sizeof( AllocHeader_t ) + (align-1) ) & ~(align-1) );
}

size_t LMDAdjustSize( size_t &nBytes, size_t align = 0 )
{
	if ( !UsingLMD() )
		return nBytes;
	// Add data before+after each alloc
	return ( nBytes + LMDComputeHeaderSize( align ) + sizeof(Sentinal_t) );
}

void *LMDNoteAlloc( void *p, size_t nBytes, size_t align = 0, const char *pszModule = g_pszUnknown, int line = 0 )
{
	if ( !UsingLMD() )
	{
		return p;
	}

	if ( g_pLMDFileName )
	{
		pszModule = g_pLMDFileName;
		line = g_nLMDLine;
	}

	if ( p )
	{
		byte *pUserPtr = ((byte*)p) + LMDComputeHeaderSize( align );
		AllocHeader_t *pHeader = LMDToHeader( pUserPtr );
		pHeader->pszModule = pszModule;
		pHeader->line = line;
		pHeader->status = LWD_ALLOCATED;
		pHeader->nBytes = nBytes;
		pHeader->align = (uint)align;
		pHeader->sentinal = g_HeadSentinel;
		*((Sentinal_t *)(pUserPtr + pHeader->nBytes)) = g_TailSentinel;
		LMDValidateBlock( pHeader, false );
		return pUserPtr;
	}
	return NULL;

	// Some SBH clients rely on allocations > 16 bytes being 16-byte aligned, so we mustn't break that assumption:
	MEMSTD_COMPILE_TIME_ASSERT( sizeof( AllocHeader_t ) % 16 == 0 );
}

void *LMDNoteFree( void *p )
{
	if ( !UsingLMD() )
	{
		return p;
	}

	AUTO_LOCK( g_LMDMutex );
	if ( !p )
	{
		return NULL;
	}

	AllocHeader_t *pHeader = LMDToHeader( p );
	if ( pHeader->status == LWD_FREE )
	{
		LMDReportInvalidBlock( pHeader, "Double free" );
	}
	LMDValidateBlock( pHeader, false );

	AllocHeader_t *pToReturn;
	if ( pHeader->nBytes < 16*1024 )
	{
		pToReturn = g_pRecentFrees[g_iNextFreeSlot];
		LMDValidateBlock( pToReturn, true );

		g_pRecentFrees[g_iNextFreeSlot] = pHeader;
		g_iNextFreeSlot = (g_iNextFreeSlot + 1 ) % g_nRecentFrees;
	}
	else
	{
		pToReturn = pHeader;
		LMDValidateBlock( g_pRecentFrees[rand() % g_nRecentFrees], true );
	}

	pHeader->status = LWD_FREE;
	memset( pHeader + 1, g_FreeFill, pHeader->nBytes );

	if ( pToReturn && ( pToReturn->align ) )
	{
		// For aligned allocations, the actual system allocation starts *before* the LMD header:
		size_t headerPadding = LMDComputeHeaderSize( pToReturn->align ) - sizeof( AllocHeader_t );
		return ( ((byte*)pToReturn) - headerPadding );
	}

	return pToReturn;
}

size_t LMDGetSize( void *p )
{
	if ( !UsingLMD() )
	{
		return (size_t)(-1);
	}

	AllocHeader_t *pHeader = LMDToHeader( p );
	return pHeader->nBytes;
}

bool LMDValidateHeap()
{
	if ( !UsingLMD() )
	{
		return true;
	}

	AUTO_LOCK( g_LMDMutex );
	for ( int i = 0; i < g_nRecentFrees && g_pRecentFrees[i]; i++ )
	{
		LMDValidateBlock( g_pRecentFrees[i], true );
	}
	return true;
}

void *LMDRealloc( void *pMem, size_t nSize, size_t align = 0, const char *pszModule = g_pszUnknown, int line = 0 )
{
	if ( nSize == 0 )
	{
		s_StdMemAlloc.Free( pMem );
		return NULL;
	}
	void *pNew;
#ifdef MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS
	if ( align )
		pNew = s_StdMemAlloc.AllocAlign( nSize, align, pszModule, line );
	else
#endif // MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS
		pNew = s_StdMemAlloc.Alloc( nSize, pszModule, line );
	if ( !pMem )
	{
		return pNew;
	}
	AllocHeader_t *pHeader = LMDToHeader( pMem );
	if ( align != pHeader->align )
	{
		LMDReportInvalidBlock( pHeader, "Realloc changed alignment!" );
	}
	size_t nCopySize = MIN( nSize, pHeader->nBytes );
	memcpy( pNew, pMem, nCopySize );
	s_StdMemAlloc.Free( pMem, pszModule, line );
	return pNew;
}

#else // USE_LIGHT_MEM_DEBUG

#define INTERNAL_INLINE FORCEINLINE
#define UsingLMD() false
FORCEINLINE size_t LMDAdjustSize( size_t &nBytes, size_t align = 0 ) { return nBytes; }
#define LMDNoteAlloc( pHeader, ... ) (pHeader)
#define LMDNoteFree( pHeader, ... ) (pHeader)
#define LMDGetSize( pHeader ) (size_t)(-1)
#define LMDToHeader( pHeader ) (pHeader)
#define LMDFromHeader( pHeader ) (pHeader)
#define LMDValidateHeap() (true)
#define LMDPushAllocDbgInfo( pFileName, nLine ) ((void)0)
#define LMDPopAllocDbgInfo() ((void)0)
FORCEINLINE void *LMDRealloc( void *pMem, size_t nSize, size_t align = 0, const char *pszModule = NULL, int line = 0 ) { return NULL; }

#endif // USE_LIGHT_MEM_DEBUG

//-----------------------------------------------------------------------------
// Internal versions
//-----------------------------------------------------------------------------

INTERNAL_INLINE void *CStdMemAlloc::InternalAllocFromPools( size_t nSize )
{
#if MEM_SBH_ENABLED
	void *pMem;

	pMem = m_PrimarySBH.Alloc( nSize );
	if ( pMem )
	{
		return pMem;
	}

#ifdef MEMALLOC_USE_SECONDARY_SBH
	pMem = m_SecondarySBH.Alloc( nSize );
	if ( pMem )
	{
		return pMem;
	}
#endif // MEMALLOC_USE_SECONDARY_SBH

#ifndef MEMALLOC_NO_FALLBACK
	pMem = m_FallbackSBH.Alloc( nSize );
	if ( pMem )
	{
		return pMem;
	}
#endif // MEMALLOC_NO_FALLBACK

	CallAllocFailHandler( nSize );
#endif // MEM_SBH_ENABLED
	return NULL;
}

INTERNAL_INLINE void *CStdMemAlloc::InternalAlloc( int region, size_t nSize )
{
	PROFILE_ALLOC(Malloc);
	
	void *pMem;

#if MEM_SBH_ENABLED
	if ( m_PrimarySBH.ShouldUse( nSize ) ) // test valid for either pool
	{
		pMem = InternalAllocFromPools( nSize );
		if ( !pMem )
		{
			CompactOnFail();
			pMem = InternalAllocFromPools( nSize );
		}
		if ( pMem )
		{
			ApplyMemoryInitializations( pMem, nSize );
			return pMem;
		}

		ExecuteOnce( DevWarning( "\n\nDRASTIC MEMORY OVERFLOW: Fell out of small block heap!\n\n\n") );
	}
#endif // MEM_SBH_ENABLED

	pMem = malloc_internal( region, nSize );
	if ( !pMem )
	{
		CompactOnFail();
		pMem = malloc_internal( region, nSize );
		if ( !pMem )
		{
			SetCRTAllocFailed( nSize );
			return NULL;
		}
	}

	ApplyMemoryInitializations( pMem, nSize );
	return pMem;
}

#ifdef MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS
INTERNAL_INLINE void *CStdMemAlloc::InternalAllocAligned( int region, size_t nSize, size_t align )
{
	PROFILE_ALLOC(MallocAligned);
	
	void *pMem;

#if MEM_SBH_ENABLED
	size_t nSizeAligned = ( nSize + align - 1 ) & ~( align - 1 );
	if ( m_PrimarySBH.ShouldUse( nSizeAligned ) ) // test valid for either pool
	{
		pMem = InternalAllocFromPools( nSizeAligned  );
		if ( !pMem )
		{
			CompactOnFail();
			pMem = InternalAllocFromPools( nSizeAligned  );
		}
		if ( pMem )
		{
			ApplyMemoryInitializations( pMem, nSizeAligned  );
			return pMem;
		}

		ExecuteOnce( DevWarning( "Warning: Fell out of small block heap!\n") );
	}
#endif // MEM_SBH_ENABLED

	pMem = malloc_aligned_internal( region, nSize, align );
	if ( !pMem )
	{
		CompactOnFail();
		pMem = malloc_aligned_internal( region, nSize, align );
		if ( !pMem )
		{
			SetCRTAllocFailed( nSize );
			return NULL;
		}
	}

	ApplyMemoryInitializations( pMem, nSize );
	return pMem;
}
#endif // MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS

INTERNAL_INLINE void *CStdMemAlloc::InternalRealloc( void *pMem, size_t nSize )
{
	if ( !pMem )
	{
		return RegionAlloc( DEF_REGION, nSize );
	}

	PROFILE_ALLOC(Realloc);

#if MEM_SBH_ENABLED
	if ( m_PrimarySBH.IsOwner( pMem ) )
	{
		return m_PrimarySBH.Realloc( pMem, nSize );
	}

#ifdef MEMALLOC_USE_SECONDARY_SBH
	if ( m_SecondarySBH.IsOwner( pMem ) )
	{
		return m_SecondarySBH.Realloc( pMem, nSize );
	}

#endif // MEMALLOC_USE_SECONDARY_SBH

#ifndef MEMALLOC_NO_FALLBACK
	if ( m_FallbackSBH.IsOwner( pMem ) )
	{
		return m_FallbackSBH.Realloc( pMem, nSize );
	}
#endif // MEMALLOC_NO_FALLBACK

#endif // MEM_SBH_ENABLED

	void *pRet = realloc_internal( pMem, nSize );
	if ( !pRet )
	{
		CompactOnFail();
		pRet = realloc_internal( pMem, nSize );
		if ( !pRet )
		{
			SetCRTAllocFailed( nSize );
		}
	}

	return pRet;
}

#ifdef MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS
INTERNAL_INLINE void *CStdMemAlloc::InternalReallocAligned( void *pMem, size_t nSize, size_t align )
{
	if ( !pMem )
	{
		return InternalAllocAligned( DEF_REGION, nSize, align );
	}

	PROFILE_ALLOC(ReallocAligned);

#if MEM_SBH_ENABLED
	if ( m_PrimarySBH.IsOwner( pMem ) )
	{
		return m_PrimarySBH.Realloc( pMem, nSize );
	}

#ifdef MEMALLOC_USE_SECONDARY_SBH
	if ( m_SecondarySBH.IsOwner( pMem ) )
	{
		return m_SecondarySBH.Realloc( pMem, nSize );
	}
#endif // MEMALLOC_USE_SECONDARY_SBH

#ifndef MEMALLOC_NO_FALLBACK
	if ( m_FallbackSBH.IsOwner( pMem ) )
	{
		return m_FallbackSBH.Realloc( pMem, nSize );
	}
#endif // MEMALLOC_NO_FALLBACK

#endif // MEM_SBH_ENABLED

	void *pRet = realloc_aligned_internal( pMem, nSize, align );
	if ( !pRet )
	{
		CompactOnFail();
		pRet = realloc_aligned_internal( pMem, nSize, align );
		if ( !pRet )
		{
			SetCRTAllocFailed( nSize );
		}
	}

	return pRet;
}
#endif

INTERNAL_INLINE void CStdMemAlloc::InternalFree( void *pMem )
{
	if ( !pMem )
	{
		return;
	}

	PROFILE_ALLOC(Free);

#if MEM_SBH_ENABLED
	if ( m_PrimarySBH.IsOwner( pMem ) )
	{
		m_PrimarySBH.Free( pMem );
		return;
	}

#ifdef MEMALLOC_USE_SECONDARY_SBH
	if ( m_SecondarySBH.IsOwner( pMem ) )
	{
		return m_SecondarySBH.Free( pMem );
	}
#endif // MEMALLOC_USE_SECONDARY_SBH

#ifndef MEMALLOC_NO_FALLBACK
	if ( m_FallbackSBH.IsOwner( pMem ) )
	{
		m_FallbackSBH.Free( pMem );
		return;
	}
#endif // MEMALLOC_NO_FALLBACK

#endif // MEM_SBH_ENABLED

	free_internal( pMem );
}

void CStdMemAlloc::CompactOnFail()
{
	CompactHeap();
}

//-----------------------------------------------------------------------------
// Release versions
//-----------------------------------------------------------------------------

void *CStdMemAlloc::Alloc( size_t nSize )
{
	size_t nAdjustedSize = LMDAdjustSize( nSize );
	return LMDNoteAlloc( CStdMemAlloc::InternalAlloc( DEF_REGION, nAdjustedSize ), nSize );
}

#ifdef MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS
void * CStdMemAlloc::AllocAlign( size_t nSize, size_t align )
{
	size_t nAdjustedSize = LMDAdjustSize( nSize, align );
	return LMDNoteAlloc( CStdMemAlloc::InternalAllocAligned( DEF_REGION, nAdjustedSize, align ), nSize, align );
}
#endif // MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS

void *CStdMemAlloc::Realloc( void *pMem, size_t nSize )
{
	if ( UsingLMD() )
		return LMDRealloc( pMem, nSize );
	return CStdMemAlloc::InternalRealloc( pMem, nSize );
}

#ifdef MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS
void * CStdMemAlloc::ReallocAlign( void *pMem, size_t nSize, size_t align )
{
	if ( UsingLMD() )
		return LMDRealloc( pMem, nSize, align );
	return CStdMemAlloc::InternalReallocAligned( pMem, nSize, align );
}
#endif // MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS

void  CStdMemAlloc::Free( void *pMem )
{
	pMem = LMDNoteFree( pMem );
	CStdMemAlloc::InternalFree( pMem );
}

void *CStdMemAlloc::Expand_NoLongerSupported( void *pMem, size_t nSize )
{
	return NULL;
}

//-----------------------------------------------------------------------------
// Debug versions
//-----------------------------------------------------------------------------
void *CStdMemAlloc::Alloc( size_t nSize, const char *pFileName, int nLine )
{
	size_t nAdjustedSize = LMDAdjustSize( nSize );
	return LMDNoteAlloc( CStdMemAlloc::InternalAlloc( DEF_REGION, nAdjustedSize ), nSize, 0, pFileName, nLine );
}

#ifdef MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS
void *CStdMemAlloc::AllocAlign( size_t nSize, size_t align, const char *pFileName, int nLine )
{
	size_t nAdjustedSize = LMDAdjustSize( nSize, align );
	return LMDNoteAlloc( CStdMemAlloc::InternalAllocAligned( DEF_REGION, nAdjustedSize, align ), nSize, align, pFileName, nLine );
}
#endif // MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS

void *CStdMemAlloc::Realloc( void *pMem, size_t nSize, const char *pFileName, int nLine )
{
	if ( UsingLMD() )
		return LMDRealloc( pMem, nSize, 0, pFileName, nLine );
	return CStdMemAlloc::InternalRealloc( pMem, nSize );
}

#ifdef MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS
void * CStdMemAlloc::ReallocAlign( void *pMem, size_t nSize, size_t align, const char *pFileName, int nLine )
{
	if ( UsingLMD() )
		return LMDRealloc( pMem, nSize, align, pFileName, nLine );
	return CStdMemAlloc::InternalReallocAligned( pMem, nSize, align );
}
#endif // MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS

void  CStdMemAlloc::Free( void *pMem, const char *pFileName, int nLine )
{
	pMem = LMDNoteFree( pMem );
	CStdMemAlloc::InternalFree( pMem );
}

void *CStdMemAlloc::Expand_NoLongerSupported( void *pMem, size_t nSize, const char *pFileName, int nLine )
{
	return NULL;
}

//-----------------------------------------------------------------------------
// Region support
//-----------------------------------------------------------------------------
void *CStdMemAlloc::RegionAlloc( int region, size_t nSize ) 
{
	size_t nAdjustedSize = LMDAdjustSize( nSize );
	return LMDNoteAlloc( CStdMemAlloc::InternalAlloc( region, nAdjustedSize ), nSize );
}

void *CStdMemAlloc::RegionAlloc( int region, size_t nSize, const char *pFileName, int nLine )
{
	size_t nAdjustedSize = LMDAdjustSize( nSize );
	return LMDNoteAlloc( CStdMemAlloc::InternalAlloc( region, nAdjustedSize ), nSize, 0, pFileName, nLine );
}

#if defined (LINUX)
#include <malloc.h>
#elif defined (OSX)
#define malloc_usable_size( ptr ) malloc_size( ptr )
extern "C" {
	extern size_t malloc_size( const void *ptr );
}
#endif // LINUX/OSX

//-----------------------------------------------------------------------------
// Returns the size of a particular allocation (NOTE: may be larger than the size requested!)
//-----------------------------------------------------------------------------
size_t CStdMemAlloc::GetSize( void *pMem )
{
	if ( !pMem )
		return CalcHeapUsed();

	if ( UsingLMD() )
	{
		return LMDGetSize( pMem );
	}

#if MEM_SBH_ENABLED
	if ( m_PrimarySBH.IsOwner( pMem ) )
	{
		return m_PrimarySBH.GetSize( pMem );
	}

#ifdef MEMALLOC_USE_SECONDARY_SBH
	if ( m_SecondarySBH.IsOwner( pMem ) )
	{
		return m_SecondarySBH.GetSize( pMem );
	}
#endif // MEMALLOC_USE_SECONDARY_SBH

#ifndef MEMALLOC_NO_FALLBACK
	if ( m_FallbackSBH.IsOwner( pMem ) )
	{
		return m_FallbackSBH.GetSize( pMem );
	}
#endif // MEMALLOC_NO_FALLBACK

#endif // MEM_SBH_ENABLED

	return msize_internal( pMem );
}


//-----------------------------------------------------------------------------
// Force file + line information for an allocation
//-----------------------------------------------------------------------------
void CStdMemAlloc::PushAllocDbgInfo( const char *pFileName, int nLine )
{
	LMDPushAllocDbgInfo( pFileName, nLine );
}

void CStdMemAlloc::PopAllocDbgInfo()
{
	LMDPopAllocDbgInfo();
}

//-----------------------------------------------------------------------------
// FIXME: Remove when we make our own heap! Crt stuff we're currently using
//-----------------------------------------------------------------------------
int32 CStdMemAlloc::CrtSetBreakAlloc( int32 lNewBreakAlloc )
{
	return 0;
}

int CStdMemAlloc::CrtSetReportMode( int nReportType, int nReportMode )
{
	return 0;
}

int CStdMemAlloc::CrtIsValidHeapPointer( const void *pMem )
{
	return 1;
}

int CStdMemAlloc::CrtIsValidPointer( const void *pMem, unsigned int size, int access )
{
	return 1;
}

int CStdMemAlloc::CrtCheckMemory( void )
{
#ifndef _CERT
	LMDValidateHeap();
#if MEM_SBH_ENABLED
	if ( !m_PrimarySBH.Validate() )
	{
		ExecuteOnce( Msg( "Small block heap is corrupt (primary)\n " ) );
	}
#ifdef MEMALLOC_USE_SECONDARY_SBH
	if ( !m_SecondarySBH.Validate() )
	{
		ExecuteOnce( Msg( "Small block heap is corrupt (secondary)\n " ) );
	}
#endif // MEMALLOC_USE_SECONDARY_SBH
#ifndef MEMALLOC_NO_FALLBACK
	if ( !m_FallbackSBH.Validate() )
	{
		ExecuteOnce( Msg( "Small block heap is corrupt (fallback)\n " ) );
	}
#endif // MEMALLOC_NO_FALLBACK
#endif // MEM_SBH_ENABLED
#endif // _CERT
	return 1;
}

int CStdMemAlloc::CrtSetDbgFlag( int nNewFlag )
{
	return 0;
}

void CStdMemAlloc::CrtMemCheckpoint( _CrtMemState *pState )
{
}

// FIXME: Remove when we have our own allocator
void* CStdMemAlloc::CrtSetReportFile( int nRptType, void* hFile )
{
	return 0;
}

void* CStdMemAlloc::CrtSetReportHook( void* pfnNewHook )
{
	return 0;
}

int CStdMemAlloc::CrtDbgReport( int nRptType, const char * szFile,
		int nLine, const char * szModule, const char * pMsg )
{
	return 0;
}

int CStdMemAlloc::heapchk()
{
#ifdef _WIN32
	CrtCheckMemory();
	return _HEAPOK;
#else
	return 1;
#endif
}

void CStdMemAlloc::DumpStats() 
{ 
	DumpStatsFileBase( "memstats" );
}

void CStdMemAlloc::DumpStatsFileBase( char const *pchFileBase )
{
#if defined( _WIN32 ) || defined( _GAMECONSOLE )
	char filename[ 512 ];
	_snprintf( filename, sizeof( filename ) - 1,
#ifdef _X360
		"D:\\%s.txt",
#elif defined( _PS3 )
		"/app_home/%s.txt",
#else
		"%s.txt",
#endif
		pchFileBase );
	filename[ sizeof( filename ) - 1 ] = 0;
	FILE *pFile = ( IsGameConsole() ) ? NULL : fopen( filename, "wt" );

#if MEM_SBH_ENABLED
	if ( pFile )
		fprintf( pFile, "Fixed Page SBH:\n" );
	else
		Msg( "Fixed Page SBH:\n" );
	m_PrimarySBH.DumpStats("Fixed Page SBH", pFile);
#ifdef MEMALLOC_USE_SECONDARY_SBH
	if ( pFile )
		fprintf( pFile, "Secondary Fixed Page SBH:\n" );
	else
		Msg( "Secondary Page SBH:\n" );
	m_SecondarySBH.DumpStats("Secondary Page SBH", pFile);
#endif // MEMALLOC_USE_SECONDARY_SBH
#ifndef MEMALLOC_NO_FALLBACK
	if ( pFile )
		fprintf( pFile, "\nFallback SBH:\n" );
	else
		Msg( "\nFallback SBH:\n" );
	m_FallbackSBH.DumpStats("Fallback SBH", pFile);	// Dump statistics to small block heap
#endif // MEMALLOC_NO_FALLBACK
#endif // MEM_SBH_ENABLED

#ifdef _PS3
	malloc_managed_size mms;
	(g_pMemOverrideRawCrtFns->pfn_malloc_stats)( &mms );
	Msg( "PS3 malloc_stats: %u / %u / %u \n", mms.current_inuse_size, mms.current_system_size, mms.max_system_size );
#endif // _PS3

	heapstats_internal( pFile );
#if defined( _X360 )
	XBX_rMemDump( filename );
#endif

	if ( pFile )
		fclose( pFile );
#endif // _WIN32 || _GAMECONSOLE
}

IVirtualMemorySection * CStdMemAlloc::AllocateVirtualMemorySection( size_t numMaxBytes )
{
#if defined( _GAMECONSOLE ) || defined( _WIN32 )
	extern IVirtualMemorySection * VirtualMemoryManager_AllocateVirtualMemorySection( size_t numMaxBytes );
	return VirtualMemoryManager_AllocateVirtualMemorySection( numMaxBytes );
#else
	return NULL;
#endif
}

size_t CStdMemAlloc::ComputeMemoryUsedBy( char const *pchSubStr )
{
	return 0;//dbg heap only.
}

static inline size_t ExtraDevkitMemory( void )
{
#if defined( _PS3 )
	// 213MB are available in retail mode, so adjust free mem to reflect that even if we're in devkit mode
	const size_t RETAIL_SIZE = 213*1024*1024;
	static sys_memory_info stat;
	sys_memory_get_user_memory_size( &stat );
	if ( stat.total_user_memory > RETAIL_SIZE )
		return ( stat.total_user_memory - RETAIL_SIZE );
#elif defined( _X360 )
	// TODO: detect the new 1GB devkit...
#endif // _PS3/_X360
	return 0;
}

void CStdMemAlloc::GlobalMemoryStatus( size_t *pUsedMemory, size_t *pFreeMemory )
{
	if ( !pUsedMemory || !pFreeMemory )
		return;

	size_t dlMallocFree = 0;
#if defined( USE_DLMALLOC )
	// Account for free memory contained within DLMalloc's FIRST region. The rationale is as follows:
	//  - the first region is supposed to service large allocations via virtual allocation, and to grow as
	//    needed (until all physical pages are used), so true 'out of memory' failures should occur there.
	//  - other regions (the 2-256kb 'medium block heap', or per-DLL heaps, and the Small Block Heap)
	//    are sized to a pre-determined high watermark, and not intended to grow. Free memory within
	//    those regions is not available for large allocations, so adding that to the 'free memory'
	//    yields confusing data which does not correspond well with out-of-memory failures.
	mallinfo info = mspace_mallinfo( g_AllocRegions[ 0 ] );
	dlMallocFree += info.fordblks;
#endif // USE_DLMALLOC

#if defined ( _X360 )

	// GlobalMemoryStatus tells us how much physical memory is free
	MEMORYSTATUS stat;
	::GlobalMemoryStatus( &stat );
	*pFreeMemory  = stat.dwAvailPhys;
	*pFreeMemory += dlMallocFree;
	// Adjust free mem to reflect a retail box, even if we're using a devkit with extra memory
	*pFreeMemory -= ExtraDevkitMemory();

	// Used is total minus free (discount the 32MB system reservation)
	*pUsedMemory = ( stat.dwTotalPhys - 32*1024*1024 ) - *pFreeMemory;

#elif defined( _PS3 )

	// NOTE: we use dlmalloc instead of the system heap, so we do NOT count the system heap's free space!
	//static malloc_managed_size mms;
	//(g_pMemOverrideRawCrtFns->pfn_malloc_stats)( &mms );
	//int heapFree = mms.current_system_size - mms.current_inuse_size;

	// sys_memory_get_user_memory_size tells us how much PPU memory is used/free
	static sys_memory_info stat;
	sys_memory_get_user_memory_size( &stat );
	*pFreeMemory  = stat.available_user_memory;
	*pFreeMemory += dlMallocFree;
	*pUsedMemory  = stat.total_user_memory - *pFreeMemory;
	// Adjust free mem to reflect a retail box, even if we're using a devkit with extra memory
	*pFreeMemory -= ExtraDevkitMemory();

#else // _X360/_PS3/other

	// no data
	*pFreeMemory = 0;
	*pUsedMemory = 0;

#endif // _X360/_PS3//other
}

#define MAX_GENERIC_MEMORY_STATS 64
GenericMemoryStat_t g_MemStats[MAX_GENERIC_MEMORY_STATS];
int g_nMemStats = 0;
static inline int AddGenericMemoryStat( const char *name, int value )
{
	Assert( g_nMemStats < MAX_GENERIC_MEMORY_STATS );
	if ( g_nMemStats < MAX_GENERIC_MEMORY_STATS )
	{
		g_MemStats[ g_nMemStats ].name  = name;
		g_MemStats[ g_nMemStats ].value = value;
		g_nMemStats++;
	}
	return g_nMemStats;
}

int CStdMemAlloc::GetGenericMemoryStats( GenericMemoryStat_t **ppMemoryStats )
{
	if ( !ppMemoryStats )
		return 0;
	g_nMemStats = 0;

#if MEM_SBH_ENABLED
	{
		// Small block heap
		size_t SBHCommitted = 0, SBHAllocated = 0;
		size_t commitTmp, allocTmp;
#if MEM_SBH_ENABLED
		m_PrimarySBH.Usage( commitTmp, allocTmp );
		SBHCommitted += commitTmp; SBHAllocated += allocTmp;
#ifdef MEMALLOC_USE_SECONDARY_SBH
		m_SecondarySBH.Usage( commitTmp, allocTmp );
		SBHCommitted += commitTmp; SBHAllocated += allocTmp;
#endif // MEMALLOC_USE_SECONDARY_SBH
#ifndef MEMALLOC_NO_FALLBACK
		m_FallbackSBH.Usage( commitTmp, allocTmp );
		SBHCommitted += commitTmp; SBHAllocated += allocTmp;
#endif // MEMALLOC_NO_FALLBACK
#endif // MEM_SBH_ENABLED

		static size_t SBHMaxCommitted = 0; SBHMaxCommitted = MAX( SBHMaxCommitted, SBHCommitted );
		AddGenericMemoryStat( "SBH_cur", (int)SBHCommitted );
		AddGenericMemoryStat( "SBH_max", (int)SBHMaxCommitted );
	}
#endif // MEM_SBH_ENABLED

#if defined( USE_DLMALLOC )
#if !defined( MEMALLOC_REGIONS ) && defined( MEMALLOC_SEGMENT_MIXED )
	{
		// Medium block heap
		mallinfo infoMBH = mspace_mallinfo( g_AllocRegions[ 1 ] );
		size_t nMBHCurUsed = infoMBH.uordblks;// nMBH_WRONG_MaxUsed = infoMBH.usmblks; // TODO: figure out why dlmalloc mis-reports MBH max usage (it just returns the footprint)
		static size_t nMBHMaxUsed = 0; nMBHMaxUsed = MAX( nMBHMaxUsed, nMBHCurUsed );
		AddGenericMemoryStat( "MBH_cur", (int)nMBHCurUsed );
		AddGenericMemoryStat( "MBH_max", (int)nMBHMaxUsed );

		// Large block heap
		mallinfo infoLBH = mspace_mallinfo( g_AllocRegions[ 0 ] );
		size_t nLBHCurUsed = mspace_footprint( g_AllocRegions[ 0 ] ), nLBHMaxUsed = mspace_max_footprint( g_AllocRegions[ 0 ] ), nLBHArenaSize = infoLBH.arena, nLBHFree = infoLBH.fordblks;
		AddGenericMemoryStat( "LBH_cur", (int)nLBHCurUsed );
		AddGenericMemoryStat( "LBH_max", (int)nLBHMaxUsed );
		// LBH arena used+free (these are non-virtual allocations - there should be none, since we only allocate 256KB+ items in the LBH)
		// TODO: I currently see the arena grow to 320KB due to a larger allocation being realloced down... if this gets worse, add an 'ALWAYS use VMM' flag to the mspace.
		AddGenericMemoryStat( "LBH_arena", (int)nLBHArenaSize );
		AddGenericMemoryStat( "LBH_free",  (int)nLBHFree );
	}
#else // (!MEMALLOC_REGIONS && MEMALLOC_SEGMENT_MIXED)
	{
		// Single dlmalloc heap (TODO: per-DLL heap stats, if we resurrect that)
		mallinfo info = mspace_mallinfo(  g_AllocRegions[ 0 ] );
		AddGenericMemoryStat( "mspace_cur",  (int)info.uordblks );
		AddGenericMemoryStat( "mspace_max",  (int)info.usmblks );
		AddGenericMemoryStat( "mspace_size", (int)mspace_footprint( g_AllocRegions[ 0 ] ) );
	}
#endif // (!MEMALLOC_REGIONS && MEMALLOC_SEGMENT_MIXED)
#endif // USE_DLMALLOC

	size_t nMaxPhysMemUsed_Delta;
	nMaxPhysMemUsed_Delta = 0;
#ifdef _PS3
	{
		// System heap (should not exist!)
		static malloc_managed_size mms;
		(g_pMemOverrideRawCrtFns->pfn_malloc_stats)( &mms );
		if ( mms.current_system_size )
			AddGenericMemoryStat( "sys_heap",		(int)mms.current_system_size );

		// Virtual Memory Manager
		size_t nReserved = 0, nReservedMax = 0, nCommitted = 0, nCommittedMax = 0;
		extern void VirtualMemoryManager_GetStats( size_t &nReserved, size_t &nReservedMax, size_t &nCommitted, size_t &nCommittedMax );
		VirtualMemoryManager_GetStats( nReserved, nReservedMax, nCommitted, nCommittedMax );
		AddGenericMemoryStat( "VMM_reserved",		(int)nReserved );
		AddGenericMemoryStat( "VMM_reserved_max",	(int)nReservedMax );
		AddGenericMemoryStat( "VMM_committed",		(int)nCommitted );
		AddGenericMemoryStat( "VMM_committed_max",	(int)nCommittedMax );

		// Estimate memory committed by memory stacks (these account for all VMM allocations other than the SBH/MBH/LBH)
		size_t nHeapTotal = 1024*1024*MBYTES_PRIMARY_SBH;
#if defined( USE_DLMALLOC )
		for ( int i = 0; i < ARRAYSIZE(g_AllocRegions); i++ )
		{
			nHeapTotal += mspace_footprint( g_AllocRegions[i] );
		}
#endif // USE_DLMALLOC
		size_t nMemStackTotal = nCommitted - nHeapTotal;
		AddGenericMemoryStat( "MemStacks",	(int)nMemStackTotal );

		// On PS3, we can more accurately determine 'phys_free_min', since we know nCommittedMax
		// (otherwise nPhysFreeMin is only updated intermittently; when this function is called):
		nMaxPhysMemUsed_Delta = nCommittedMax - nCommitted;
	}
#endif // _PS3

#if defined( _GAMECONSOLE )
	// Total/free/min-free physical pages
	{
#if defined( _X360 )
		MEMORYSTATUS stat;
		::GlobalMemoryStatus( &stat );
		size_t nPhysTotal = stat.dwTotalPhys,       nPhysFree = stat.dwAvailPhys           - ExtraDevkitMemory();
#elif defined( _PS3 )
		static sys_memory_info stat;
		sys_memory_get_user_memory_size( &stat );
		size_t nPhysTotal = stat.total_user_memory, nPhysFree = stat.available_user_memory - ExtraDevkitMemory();
#endif // _X360/_PS3
		static size_t nPhysFreeMin = nPhysTotal;
		nPhysFreeMin = MIN( nPhysFreeMin, ( nPhysFree - nMaxPhysMemUsed_Delta ) );
		AddGenericMemoryStat( "phys_total",		(int)nPhysTotal );
		AddGenericMemoryStat( "phys_free",		(int)nPhysFree );
		AddGenericMemoryStat( "phys_free_min",	(int)nPhysFreeMin );
	}
#endif // _GAMECONSOLE

	*ppMemoryStats = &g_MemStats[0];
	return g_nMemStats;
}

void CStdMemAlloc::CompactHeap()
{
#if MEM_SBH_ENABLED
	if ( !m_CompactMutex.TryLock() )
	{
		return;
	}
	if ( m_bInCompact )
	{
		m_CompactMutex.Unlock();
		return;
	}

	m_bInCompact = true;
	size_t nBytesRecovered;
#ifndef MEMALLOC_NO_FALLBACK
	nBytesRecovered = m_FallbackSBH.Compact( false );
	if ( nBytesRecovered && IsGameConsole() )
	{
		Msg( "Compact freed %d bytes from virtual heap (up to 256k still committed)\n", nBytesRecovered );
	}
#endif // MEMALLOC_NO_FALLBACK
	nBytesRecovered = m_PrimarySBH.Compact( false );
#ifdef MEMALLOC_USE_SECONDARY_SBH
	nBytesRecovered += m_SecondarySBH.Compact( false );
#endif
	if ( nBytesRecovered && IsGameConsole() )
	{
		Msg( "Compact released %d bytes from the SBH\n", nBytesRecovered );
	}

	nBytesRecovered = compact_internal();
	if ( nBytesRecovered && IsGameConsole() )
	{
		Msg( "Compact released %d bytes from the mixed block heap\n", nBytesRecovered );
	}

	m_bInCompact = false;
	m_CompactMutex.Unlock();
#endif // MEM_SBH_ENABLED
}

void CStdMemAlloc::CompactIncremental()
{
#if MEM_SBH_ENABLED
	if ( !m_CompactMutex.TryLock() )
	{
		return;
	}
	if ( m_bInCompact )
	{
		m_CompactMutex.Unlock();
		return;
	}

	m_bInCompact = true;
#ifndef MEMALLOC_NO_FALLBACK
	m_FallbackSBH.Compact( true );
#endif
	m_PrimarySBH.Compact( true );
#ifdef MEMALLOC_USE_SECONDARY_SBH
	m_SecondarySBH.Compact( true );
#endif
	m_bInCompact = false;
	m_CompactMutex.Unlock();
#endif // MEM_SBH_ENABLED
}

MemAllocFailHandler_t CStdMemAlloc::SetAllocFailHandler( MemAllocFailHandler_t pfnMemAllocFailHandler )
{
	MemAllocFailHandler_t pfnPrevious = m_pfnFailHandler;
	m_pfnFailHandler = pfnMemAllocFailHandler;
	return pfnPrevious;
}

size_t CStdMemAlloc::DefaultFailHandler( size_t nBytes )
{
	if ( IsX360() )
	{
#ifdef _X360 
		ExecuteOnce(
		{
			char buffer[256];
			_snprintf( buffer, sizeof( buffer ), "***** Memory pool overflow, attempted allocation size: %u (not a critical error)\n", nBytes );
			XBX_OutputDebugString( buffer ); 
		}
		);
#endif // _X360
	}
	return 0;
}

void CStdMemAlloc::SetStatsExtraInfo( const char *pMapName, const char *pComment )
{
}

void CStdMemAlloc::SetCRTAllocFailed( size_t nSize )
{
	m_sMemoryAllocFailed = nSize;

	DebuggerBreakIfDebugging();
#if defined( _PS3 ) && defined( _DEBUG )
	DebuggerBreak();
#endif // _PS3

	char buffer[256];
#ifdef COMPILER_GCC
	_snprintf( buffer, sizeof( buffer ), "***** OUT OF MEMORY! attempted allocation size: %u ****\n", nSize );
#else
	_snprintf( buffer, sizeof( buffer ), "***** OUT OF MEMORY! attempted allocation size: %u ****\n", nSize );
#endif // COMPILER_GCC

#ifdef _X360 
	XBX_OutputDebugString( buffer );
	if ( !Plat_IsInDebugSession() )
	{
		XBX_CrashDump( true );
#if defined( _DEMO )
		XLaunchNewImage( XLAUNCH_KEYWORD_DEFAULT_APP, 0 );
#else
		XLaunchNewImage( "default.xex", 0 );
#endif // _DEMO
	}
#elif defined(_WIN32 )
	OutputDebugString( buffer );
	if ( !Plat_IsInDebugSession() )
	{
		WriteMiniDump();
		abort();
	}
#else // _X360/_WIN32/other
	printf( "%s\n", buffer );
	if ( !Plat_IsInDebugSession() )
	{
		WriteMiniDump();
#if defined( _PS3 )
		DumpStats();
#endif
		Plat_ExitProcess( 0 );
	}
#endif // _X360/_WIN32/other

}

size_t CStdMemAlloc::MemoryAllocFailed()
{
	return m_sMemoryAllocFailed;
}

#endif // MEM_IMPL_TYPE_STD

#endif // STEAM