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
|
//-----------------------------------------------------------------------------
// NOTE! This should never be called directly from leaf code
// Just use new,delete,malloc,free etc. They will call into this eventually
//-----------------------------------------------------------------------------
#include "pch_tier0.h"
#if IS_WINDOWS_PC
#define WIN_32_LEAN_AND_MEAN
#include <windows.h>
#define VA_COMMIT_FLAGS MEM_COMMIT
#define VA_RESERVE_FLAGS MEM_RESERVE
#elif defined( _X360 )
#undef Verify
#define _XBOX
#include <xtl.h>
#undef _XBOX
#include "xbox/xbox_win32stubs.h"
#define VA_COMMIT_FLAGS (MEM_COMMIT|MEM_NOZERO|MEM_LARGE_PAGES)
#define VA_RESERVE_FLAGS (MEM_RESERVE|MEM_LARGE_PAGES)
#elif defined( _PS3 )
#include "sys/memory.h"
#include "sys/mempool.h"
#include "sys/process.h"
#include <sys/vm.h>
#endif
//#include <malloc.h>
#include <algorithm>
#include "tier0/dbg.h"
#include "tier0/memalloc.h"
#include "tier0/threadtools.h"
#include "tier0/tslist.h"
#include "mem_helpers.h"
#ifndef _PS3
#pragma pack(4)
#endif
#define MIN_SBH_BLOCK 8
#define MIN_SBH_ALIGN 8
#define MAX_SBH_BLOCK 2048
#define MAX_POOL_REGION (4*1024*1024)
#define NUM_POOLS 42
#if defined( _WIN32 ) || defined( _PS3 )
// FIXME: Disable small block heap on win64 for now; it's busted because
// it's expecting SLIST_HEADER to look different than it does on win64
#if !defined( PLATFORM_WINDOWS_PC64 )
#define MEM_SBH_ENABLED 1
#endif
#endif
#if !defined(_CERT) && ( defined(_X360) || defined(_PS3) )
#define TRACK_SBH_COUNTS
#endif
#if defined(_X360)
// 360 uses a 48MB primary (physical) SBH and 10MB secondary (virtual) SBH, with no fallback
#define MBYTES_PRIMARY_SBH 48
#define MEMALLOC_USE_SECONDARY_SBH
#define MBYTES_SECONDARY_SBH 10
#define MEMALLOC_NO_FALLBACK
#elif defined(_PS3)
// PS3 uses just a 32MB SBH - this was enough to avoid overflow when Portal 2 shipped.
// NOTE: when Steam uses the game's tier0 allocator (see memalloc.h), we increase the size
// of the SBH and MBH (see memstd.cpp) to accommodate those extra allocations.
#define MBYTES_PRIMARY_SBH ( 32 + MBYTES_STEAM_SBH_USAGE )
#define MEMALLOC_NO_FALLBACK
#else // _X360 | _PS3
// Other platforms use a 48MB primary SBH and a (32MB) fallback SBH
#define MBYTES_PRIMARY_SBH 48
#endif // _X360 | _PS3
#define MEMSTD_COMPILE_TIME_ASSERT( pred ) switch(0){case 0:case pred:;}
//-----------------------------------------------------------------------------
// Small block pool
//-----------------------------------------------------------------------------
class CFreeList : public CTSListBase
{
public:
void Push( void *p ) { CTSListBase::Push( (TSLNodeBase_t *)p ); }
byte *Pop() { return (byte *)CTSListBase::Pop(); }
};
template <typename CAllocator>
class CSmallBlockHeap;
template <typename CAllocator>
class CSmallBlockPool
{
public:
CSmallBlockPool()
{
m_nBlockSize = 0;
m_nCommittedPages = 0;
m_pFirstPage = NULL;
}
void Init( unsigned nBlockSize );
size_t GetBlockSize();
void *Alloc();
void Free( void *p );
int CountFreeBlocks();
int GetCommittedSize();
int CountCommittedBlocks();
int CountAllocatedBlocks();
size_t Compact( bool bIncremental );
bool Validate();
enum
{
BYTES_PAGE = CAllocator::BYTES_PAGE,
NOT_COMMITTED = -1
};
private:
typedef CSmallBlockHeap<CAllocator> CHeap;
friend class CSmallBlockHeap<CAllocator>;
struct PageStatus_t : public TSLNodeBase_t
{
PageStatus_t()
{
m_pPool = NULL;
m_nAllocated = NOT_COMMITTED;
m_pNextPageInPool = NULL;
}
CSmallBlockPool<CAllocator> * m_pPool;
PageStatus_t * m_pNextPageInPool;
CInterlockedInt m_nAllocated;
CTSListBase m_SortList;
};
struct SharedData_t
{
CAllocator m_Allocator;
CTSListBase m_FreePages;
CThreadSpinRWLock m_Lock;
PageStatus_t m_PageStatus[CAllocator::TOTAL_BYTES/CAllocator::BYTES_PAGE];
byte * m_pNextBlock;
byte * m_pBase;
byte * m_pLimit;
};
static int PageSort( const void *p1, const void *p2 ) ;
bool RemovePagesFromFreeList( byte **pPages, int nPages, bool bSortList );
void ValidateFreelist( SharedData_t *pSharedData );
CFreeList m_FreeList;
CInterlockedPtr<byte> m_pNextAlloc;
PageStatus_t * m_pFirstPage;
unsigned m_nBlockSize;
unsigned m_nCommittedPages;
CThreadFastMutex m_CommitMutex;
#ifdef TRACK_SBH_COUNTS
CInterlockedInt m_nFreeBlocks;
#endif
static SharedData_t *GetSharedData()
{
return &gm_SharedData;
}
static SharedData_t gm_SharedData;
};
//-----------------------------------------------------------------------------
// Small block heap (multi-pool)
//-----------------------------------------------------------------------------
template <typename CAllocator>
class CSmallBlockHeap
{
public:
CSmallBlockHeap();
bool ShouldUse( size_t nBytes );
bool IsOwner( void * p );
void *Alloc( size_t nBytes );
void *Realloc( void *p, size_t nBytes );
void Free( void *p );
size_t GetSize( void *p );
void DumpStats( const char *pszTag, FILE *pFile = NULL );
void Usage( size_t &bytesCommitted, size_t &bytesAllocated );
size_t Compact( bool bIncremental );
bool Validate();
enum
{
BYTES_PAGE = CAllocator::BYTES_PAGE
};
private:
typedef CSmallBlockPool<CAllocator> CPool;
typedef struct CSmallBlockPool<CAllocator>::SharedData_t SharedData_t;
CPool *FindPool( size_t nBytes );
CPool *FindPool( void *p );
// Map size to a pool address to a pool
CPool *m_PoolLookup[MAX_SBH_BLOCK >> 2];
CPool m_Pools[NUM_POOLS];
SharedData_t *m_pSharedData;
};
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
class CStdMemAlloc : public IMemAlloc
{
public:
CStdMemAlloc();
// Internal versions
void *InternalAlloc( int region, size_t nSize );
#ifdef MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS
void *InternalAllocAligned( int region, size_t nSize, size_t align );
#endif
void *InternalAllocFromPools( size_t nSize );
void *InternalRealloc( void *pMem, size_t nSize );
#ifdef MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS
void *InternalReallocAligned( void *pMem, size_t nSize, size_t align );
#endif
void InternalFree( void *pMem );
void CompactOnFail();
// Release versions
virtual void *Alloc( size_t nSize );
virtual void *Realloc( void *pMem, size_t nSize );
virtual void Free( void *pMem );
virtual void *Expand_NoLongerSupported( void *pMem, size_t nSize );
// Debug versions
virtual void *Alloc( size_t nSize, const char *pFileName, int nLine );
virtual void *Realloc( void *pMem, size_t nSize, const char *pFileName, int nLine );
virtual void Free( void *pMem, const char *pFileName, int nLine );
virtual void *Expand_NoLongerSupported( void *pMem, size_t nSize, const char *pFileName, int nLine );
#ifdef MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS
virtual void *AllocAlign( size_t nSize, size_t align );
virtual void *AllocAlign( size_t nSize, size_t align, const char *pFileName, int nLine );
virtual void *ReallocAlign( void *pMem, size_t nSize, size_t align );
virtual void *ReallocAlign( void *pMem, size_t nSize, size_t align, const char *pFileName, int nLine );
#endif
virtual void *RegionAlloc( int region, size_t nSize );
virtual void *RegionAlloc( int region, size_t nSize, const char *pFileName, int nLine );
// Returns size of a particular allocation
virtual size_t GetSize( void *pMem );
// Force file + line information for an allocation
virtual void PushAllocDbgInfo( const char *pFileName, int nLine );
virtual void PopAllocDbgInfo();
virtual int32 CrtSetBreakAlloc( int32 lNewBreakAlloc );
virtual int CrtSetReportMode( int nReportType, int nReportMode );
virtual int CrtIsValidHeapPointer( const void *pMem );
virtual int CrtIsValidPointer( const void *pMem, unsigned int size, int access );
virtual int CrtCheckMemory( void );
virtual int CrtSetDbgFlag( int nNewFlag );
virtual void CrtMemCheckpoint( _CrtMemState *pState );
void* CrtSetReportFile( int nRptType, void* hFile );
void* CrtSetReportHook( void* pfnNewHook );
int CrtDbgReport( int nRptType, const char * szFile,
int nLine, const char * szModule, const char * pMsg );
virtual int heapchk();
virtual void DumpStats();
virtual void DumpStatsFileBase( char const *pchFileBase );
virtual size_t ComputeMemoryUsedBy( char const *pchSubStr );
virtual void GlobalMemoryStatus( size_t *pUsedMemory, size_t *pFreeMemory );
virtual bool IsDebugHeap() { return false; }
virtual void GetActualDbgInfo( const char *&pFileName, int &nLine ) {}
virtual void RegisterAllocation( const char *pFileName, int nLine, size_t nLogicalSize, size_t nActualSize, unsigned nTime ) {}
virtual void RegisterDeallocation( const char *pFileName, int nLine, size_t nLogicalSize, size_t nActualSize, unsigned nTime ) {}
virtual int GetVersion() { return MEMALLOC_VERSION; }
virtual void OutOfMemory( size_t nBytesAttempted = 0 ) { SetCRTAllocFailed( nBytesAttempted ); }
virtual IVirtualMemorySection * AllocateVirtualMemorySection( size_t numMaxBytes );
virtual int GetGenericMemoryStats( GenericMemoryStat_t **ppMemoryStats );
virtual void CompactHeap();
virtual void CompactIncremental();
virtual MemAllocFailHandler_t SetAllocFailHandler( MemAllocFailHandler_t pfnMemAllocFailHandler );
size_t CallAllocFailHandler( size_t nBytes ) { return (*m_pfnFailHandler)( nBytes); }
virtual uint32 GetDebugInfoSize() { return 0; }
virtual void SaveDebugInfo( void *pvDebugInfo ) { }
virtual void RestoreDebugInfo( const void *pvDebugInfo ) {}
virtual void InitDebugInfo( void *pvDebugInfo, const char *pchRootFileName, int nLine ) {}
static size_t DefaultFailHandler( size_t );
void DumpBlockStats( void *p ) {}
#if MEM_SBH_ENABLED
class CVirtualAllocator
{
public:
enum
{
BYTES_PAGE = (64*1024),
TOTAL_BYTES = (32*1024*1024),
MIN_RESERVE_PAGES = 4,
};
byte *AllocatePoolMemory()
{
#ifdef _WIN32
return (byte *)VirtualAlloc( NULL, TOTAL_BYTES, VA_RESERVE_FLAGS, PAGE_NOACCESS );
#elif defined( _PS3 )
Error( "" );
return NULL;
#else
#error
#endif
}
bool IsVirtual()
{
return true;
}
bool Decommit( void *pPage )
{
#ifdef _WIN32
return ( VirtualFree( pPage, BYTES_PAGE, MEM_DECOMMIT ) != 0 );
#elif defined( _PS3 )
return false;
#else
#error
#endif
}
bool Commit( void *pPage )
{
#ifdef _WIN32
return ( VirtualAlloc( pPage, BYTES_PAGE, VA_COMMIT_FLAGS, PAGE_READWRITE ) != NULL );
#elif defined( _PS3 )
return false;
#else
#error
#endif
}
};
typedef CSmallBlockHeap<CVirtualAllocator> CVirtualSmallBlockHeap;
template <size_t SIZE_MB, bool bPhysical>
class CFixedAllocator
{
public:
enum
{
BYTES_PAGE = (16*1024),
TOTAL_BYTES = (SIZE_MB*1024*1024),
MIN_RESERVE_PAGES = TOTAL_BYTES/BYTES_PAGE,
};
byte *AllocatePoolMemory()
{
#ifdef _WIN32
#ifdef _X360
if ( bPhysical )
return (byte *)XPhysicalAlloc( TOTAL_BYTES, MAXULONG_PTR, 4096, PAGE_READWRITE | MEM_16MB_PAGES );
#endif
return (byte *)VirtualAlloc( NULL, TOTAL_BYTES, VA_COMMIT_FLAGS, PAGE_READWRITE );
#elif defined( _PS3 )
// TODO: release this section on shutdown (use GetMemorySectionForAddress)
extern IVirtualMemorySection * VirtualMemoryManager_AllocateVirtualMemorySection( size_t numMaxBytes );
IVirtualMemorySection *pSection = VirtualMemoryManager_AllocateVirtualMemorySection( TOTAL_BYTES );
if ( !pSection )
Error( "CFixedAllocator::AllocatePoolMemory() failed in VirtualMemoryManager_AllocateVirtualMemorySection\n" );
if ( !pSection->CommitPages( pSection->GetBaseAddress(), TOTAL_BYTES ) )
Error( "CFixedAllocator::AllocatePoolMemory() failed in IVirtualMemorySection::CommitPages\n" );
return reinterpret_cast<byte *>( pSection->GetBaseAddress() );
#else
#error
#endif
}
bool IsVirtual()
{
return false;
}
bool Decommit( void *pPage )
{
return false;
}
bool Commit( void *pPage )
{
return false;
}
};
typedef CSmallBlockHeap<CFixedAllocator< MBYTES_PRIMARY_SBH, true> > CFixedSmallBlockHeap;
#ifdef MEMALLOC_USE_SECONDARY_SBH
typedef CSmallBlockHeap<CFixedAllocator< MBYTES_SECONDARY_SBH, false> > CFixedVirtualSmallBlockHeap; // @TODO: move back into above heap if number stays at 16 [7/15/2009 tom]
#endif
CFixedSmallBlockHeap m_PrimarySBH;
#ifdef MEMALLOC_USE_SECONDARY_SBH
CFixedVirtualSmallBlockHeap m_SecondarySBH;
#endif
#ifndef MEMALLOC_NO_FALLBACK
CVirtualSmallBlockHeap m_FallbackSBH;
#endif
#endif // MEM_SBH_ENABLED
virtual void SetStatsExtraInfo( const char *pMapName, const char *pComment );
virtual size_t MemoryAllocFailed();
void SetCRTAllocFailed( size_t nMemSize );
MemAllocFailHandler_t m_pfnFailHandler;
size_t m_sMemoryAllocFailed;
CThreadFastMutex m_CompactMutex;
bool m_bInCompact;
};
#ifndef _PS3
#pragma pack()
#endif
|