added sv_threaded cvar, the server can now be moved to another thread
[xonotic/darkplaces.git] / zone.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // Z_zone.c
21
22 #include "quakedef.h"
23 #include "thread.h"
24
25 #ifdef WIN32
26 #include <windows.h>
27 #include <winbase.h>
28 #else
29 #include <unistd.h>
30 #endif
31
32 #ifdef _MSC_VER
33 #include <vadefs.h>
34 #else
35 #include <stdint.h>
36 #endif
37 #define MEMHEADER_SENTINEL_FOR_ADDRESS(p) ((sentinel_seed ^ (unsigned int) (uintptr_t) (p)) + sentinel_seed)
38 unsigned int sentinel_seed;
39
40 qboolean mem_bigendian = false;
41 void *mem_mutex = NULL;
42
43 // LordHavoc: enables our own low-level allocator (instead of malloc)
44 #define MEMCLUMPING 0
45 #define MEMCLUMPING_FREECLUMPS 0
46
47 #if MEMCLUMPING
48 // smallest unit we care about is this many bytes
49 #define MEMUNIT 128
50 // try to do 32MB clumps, but overhead eats into this
51 #define MEMWANTCLUMPSIZE (1<<27)
52 // give malloc padding so we can't waste most of a page at the end
53 #define MEMCLUMPSIZE (MEMWANTCLUMPSIZE - MEMWANTCLUMPSIZE/MEMUNIT/32 - 128)
54 #define MEMBITS (MEMCLUMPSIZE / MEMUNIT)
55 #define MEMBITINTS (MEMBITS / 32)
56
57 typedef struct memclump_s
58 {
59         // contents of the clump
60         unsigned char block[MEMCLUMPSIZE];
61         // should always be MEMCLUMP_SENTINEL
62         unsigned int sentinel1;
63         // if a bit is on, it means that the MEMUNIT bytes it represents are
64         // allocated, otherwise free
65         unsigned int bits[MEMBITINTS];
66         // should always be MEMCLUMP_SENTINEL
67         unsigned int sentinel2;
68         // if this drops to 0, the clump is freed
69         size_t blocksinuse;
70         // largest block of memory available (this is reset to an optimistic
71         // number when anything is freed, and updated when alloc fails the clump)
72         size_t largestavailable;
73         // next clump in the chain
74         struct memclump_s *chain;
75 }
76 memclump_t;
77
78 #if MEMCLUMPING == 2
79 static memclump_t masterclump;
80 #endif
81 static memclump_t *clumpchain = NULL;
82 #endif
83
84
85 cvar_t developer_memory = {0, "developer_memory", "0", "prints debugging information about memory allocations"};
86 cvar_t developer_memorydebug = {0, "developer_memorydebug", "0", "enables memory corruption checks (very slow)"};
87 cvar_t sys_memsize_physical = {CVAR_READONLY, "sys_memsize_physical", "", "physical memory size in MB (or empty if unknown)"};
88 cvar_t sys_memsize_virtual = {CVAR_READONLY, "sys_memsize_virtual", "", "virtual memory size in MB (or empty if unknown)"};
89
90 static mempool_t *poolchain = NULL;
91
92 void Mem_PrintStats(void);
93 void Mem_PrintList(size_t minallocationsize);
94
95 #if MEMCLUMPING != 2
96 // some platforms have a malloc that returns NULL but succeeds later
97 // (Windows growing its swapfile for example)
98 static void *attempt_malloc(size_t size)
99 {
100         void *base;
101         // try for half a second or so
102         unsigned int attempts = 500;
103         while (attempts--)
104         {
105                 base = (void *)malloc(size);
106                 if (base)
107                         return base;
108                 Sys_Sleep(1000);
109         }
110         return NULL;
111 }
112 #endif
113
114 #if MEMCLUMPING
115 static memclump_t *Clump_NewClump(void)
116 {
117         memclump_t **clumpchainpointer;
118         memclump_t *clump;
119 #if MEMCLUMPING == 2
120         if (clumpchain)
121                 return NULL;
122         clump = &masterclump;
123 #else
124         clump = (memclump_t*)attempt_malloc(sizeof(memclump_t));
125         if (!clump)
126                 return NULL;
127 #endif
128
129         // initialize clump
130         if (developer_memorydebug.integer)
131                 memset(clump, 0xEF, sizeof(*clump));
132         clump->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1);
133         memset(clump->bits, 0, sizeof(clump->bits));
134         clump->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2);
135         clump->blocksinuse = 0;
136         clump->largestavailable = 0;
137         clump->chain = NULL;
138
139         // link clump into chain
140         for (clumpchainpointer = &clumpchain;*clumpchainpointer;clumpchainpointer = &(*clumpchainpointer)->chain)
141                 ;
142         *clumpchainpointer = clump;
143
144         return clump;
145 }
146 #endif
147
148 // low level clumping functions, all other memory functions use these
149 static void *Clump_AllocBlock(size_t size)
150 {
151         unsigned char *base;
152 #if MEMCLUMPING
153         if (size <= MEMCLUMPSIZE)
154         {
155                 int index;
156                 unsigned int bit;
157                 unsigned int needbits;
158                 unsigned int startbit;
159                 unsigned int endbit;
160                 unsigned int needints;
161                 int startindex;
162                 int endindex;
163                 unsigned int value;
164                 unsigned int mask;
165                 unsigned int *array;
166                 memclump_t **clumpchainpointer;
167                 memclump_t *clump;
168                 needbits = (size + MEMUNIT - 1) / MEMUNIT;
169                 needints = (needbits+31)>>5;
170                 for (clumpchainpointer = &clumpchain;;clumpchainpointer = &(*clumpchainpointer)->chain)
171                 {
172                         clump = *clumpchainpointer;
173                         if (!clump)
174                         {
175                                 clump = Clump_NewClump();
176                                 if (!clump)
177                                         return NULL;
178                         }
179                         if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
180                                 Sys_Error("Clump_AllocBlock: trashed sentinel1\n");
181                         if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
182                                 Sys_Error("Clump_AllocBlock: trashed sentinel2\n");
183                         startbit = 0;
184                         endbit = startbit + needbits;
185                         array = clump->bits;
186                         // do as fast a search as possible, even if it means crude alignment
187                         if (needbits >= 32)
188                         {
189                                 // large allocations are aligned to large boundaries
190                                 // furthermore, they are allocated downward from the top...
191                                 endindex = MEMBITINTS;
192                                 startindex = endindex - needints;
193                                 index = endindex;
194                                 while (--index >= startindex)
195                                 {
196                                         if (array[index])
197                                         {
198                                                 endindex = index;
199                                                 startindex = endindex - needints;
200                                                 if (startindex < 0)
201                                                         goto nofreeblock;
202                                         }
203                                 }
204                                 startbit = startindex*32;
205                                 goto foundblock;
206                         }
207                         else
208                         {
209                                 // search for a multi-bit gap in a single int
210                                 // (not dealing with the cases that cross two ints)
211                                 mask = (1<<needbits)-1;
212                                 endbit = 32-needbits;
213                                 bit = endbit;
214                                 for (index = 0;index < MEMBITINTS;index++)
215                                 {
216                                         value = array[index];
217                                         if (value != 0xFFFFFFFFu)
218                                         {
219                                                 // there may be room in this one...
220                                                 for (bit = 0;bit < endbit;bit++)
221                                                 {
222                                                         if (!(value & (mask<<bit)))
223                                                         {
224                                                                 startbit = index*32+bit;
225                                                                 goto foundblock;
226                                                         }
227                                                 }
228                                         }
229                                 }
230                                 goto nofreeblock;
231                         }
232 foundblock:
233                         endbit = startbit + needbits;
234                         // mark this range as used
235                         // TODO: optimize
236                         for (bit = startbit;bit < endbit;bit++)
237                                 if (clump->bits[bit>>5] & (1<<(bit & 31)))
238                                         Sys_Error("Clump_AllocBlock: internal error (%i needbits)\n", needbits);
239                         for (bit = startbit;bit < endbit;bit++)
240                                 clump->bits[bit>>5] |= (1<<(bit & 31));
241                         clump->blocksinuse += needbits;
242                         base = clump->block + startbit * MEMUNIT;
243                         if (developer_memorydebug.integer)
244                                 memset(base, 0xBF, needbits * MEMUNIT);
245                         return base;
246 nofreeblock:
247                         ;
248                 }
249                 // never reached
250                 return NULL;
251         }
252         // too big, allocate it directly
253 #endif
254 #if MEMCLUMPING == 2
255         return NULL;
256 #else
257         base = (unsigned char *)attempt_malloc(size);
258         if (base && developer_memorydebug.integer)
259                 memset(base, 0xAF, size);
260         return base;
261 #endif
262 }
263 static void Clump_FreeBlock(void *base, size_t size)
264 {
265 #if MEMCLUMPING
266         unsigned int needbits;
267         unsigned int startbit;
268         unsigned int endbit;
269         unsigned int bit;
270         memclump_t **clumpchainpointer;
271         memclump_t *clump;
272         unsigned char *start = (unsigned char *)base;
273         for (clumpchainpointer = &clumpchain;(clump = *clumpchainpointer);clumpchainpointer = &(*clumpchainpointer)->chain)
274         {
275                 if (start >= clump->block && start < clump->block + MEMCLUMPSIZE)
276                 {
277                         if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
278                                 Sys_Error("Clump_FreeBlock: trashed sentinel1\n");
279                         if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
280                                 Sys_Error("Clump_FreeBlock: trashed sentinel2\n");
281                         if (start + size > clump->block + MEMCLUMPSIZE)
282                                 Sys_Error("Clump_FreeBlock: block overrun\n");
283                         // the block belongs to this clump, clear the range
284                         needbits = (size + MEMUNIT - 1) / MEMUNIT;
285                         startbit = (start - clump->block) / MEMUNIT;
286                         endbit = startbit + needbits;
287                         // first verify all bits are set, otherwise this may be misaligned or a double free
288                         for (bit = startbit;bit < endbit;bit++)
289                                 if ((clump->bits[bit>>5] & (1<<(bit & 31))) == 0)
290                                         Sys_Error("Clump_FreeBlock: double free\n");
291                         for (bit = startbit;bit < endbit;bit++)
292                                 clump->bits[bit>>5] &= ~(1<<(bit & 31));
293                         clump->blocksinuse -= needbits;
294                         memset(base, 0xFF, needbits * MEMUNIT);
295                         // if all has been freed, free the clump itself
296                         if (clump->blocksinuse == 0)
297                         {
298                                 *clumpchainpointer = clump->chain;
299                                 if (developer_memorydebug.integer)
300                                         memset(clump, 0xFF, sizeof(*clump));
301 #if MEMCLUMPING != 2
302                                 free(clump);
303 #endif
304                         }
305                         return;
306                 }
307         }
308         // does not belong to any known chunk...  assume it was a direct allocation
309 #endif
310 #if MEMCLUMPING != 2
311         memset(base, 0xFF, size);
312         free(base);
313 #endif
314 }
315
316 void *_Mem_Alloc(mempool_t *pool, void *olddata, size_t size, size_t alignment, const char *filename, int fileline)
317 {
318         unsigned int sentinel1;
319         unsigned int sentinel2;
320         size_t realsize;
321         size_t sharedsize;
322         size_t remainsize;
323         memheader_t *mem;
324         memheader_t *oldmem;
325         unsigned char *base;
326
327         if (size <= 0)
328         {
329                 if (olddata)
330                         _Mem_Free(olddata, filename, fileline);
331                 return NULL;
332         }
333         if (pool == NULL)
334                 Sys_Error("Mem_Alloc: pool == NULL (alloc at %s:%i)", filename, fileline);
335         if (mem_mutex)
336                 Thread_LockMutex(mem_mutex);
337         if (developer_memory.integer)
338                 Con_DPrintf("Mem_Alloc: pool %s, file %s:%i, size %i bytes\n", pool->name, filename, fileline, (int)size);
339         //if (developer.integer > 0 && developer_memorydebug.integer)
340         //      _Mem_CheckSentinelsGlobal(filename, fileline);
341         pool->totalsize += size;
342         realsize = alignment + sizeof(memheader_t) + size + sizeof(sentinel2);
343         pool->realsize += realsize;
344         base = (unsigned char *)Clump_AllocBlock(realsize);
345         if (base== NULL)
346         {
347                 Mem_PrintList(0);
348                 Mem_PrintStats();
349                 Mem_PrintList(1<<30);
350                 Mem_PrintStats();
351                 Sys_Error("Mem_Alloc: out of memory (alloc at %s:%i)", filename, fileline);
352         }
353         // calculate address that aligns the end of the memheader_t to the specified alignment
354         mem = (memheader_t*)((((size_t)base + sizeof(memheader_t) + (alignment-1)) & ~(alignment-1)) - sizeof(memheader_t));
355         mem->baseaddress = (void*)base;
356         mem->filename = filename;
357         mem->fileline = fileline;
358         mem->size = size;
359         mem->pool = pool;
360
361         // calculate sentinels (detects buffer overruns, in a way that is hard to exploit)
362         sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
363         sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
364         mem->sentinel = sentinel1;
365         memcpy((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2));
366
367         // append to head of list
368         mem->next = pool->chain;
369         mem->prev = NULL;
370         pool->chain = mem;
371         if (mem->next)
372                 mem->next->prev = mem;
373
374         if (mem_mutex)
375                 Thread_UnlockMutex(mem_mutex);
376
377         // copy the shared portion in the case of a realloc, then memset the rest
378         sharedsize = 0;
379         remainsize = size;
380         if (olddata)
381         {
382                 oldmem = (memheader_t*)olddata - 1;
383                 sharedsize = min(oldmem->size, size);
384                 memcpy((void *)((unsigned char *) mem + sizeof(memheader_t)), olddata, sharedsize);
385                 remainsize -= sharedsize;
386                 _Mem_Free(olddata, filename, fileline);
387         }
388         memset((void *)((unsigned char *) mem + sizeof(memheader_t) + sharedsize), 0, remainsize);
389         return (void *)((unsigned char *) mem + sizeof(memheader_t));
390 }
391
392 // only used by _Mem_Free and _Mem_FreePool
393 static void _Mem_FreeBlock(memheader_t *mem, const char *filename, int fileline)
394 {
395         mempool_t *pool;
396         size_t size;
397         size_t realsize;
398         unsigned int sentinel1;
399         unsigned int sentinel2;
400
401         // check sentinels (detects buffer overruns, in a way that is hard to exploit)
402         sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
403         sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
404         if (mem->sentinel != sentinel1)
405                 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
406         if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
407                 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
408
409         pool = mem->pool;
410         if (developer_memory.integer)
411                 Con_DPrintf("Mem_Free: pool %s, alloc %s:%i, free %s:%i, size %i bytes\n", pool->name, mem->filename, mem->fileline, filename, fileline, (int)(mem->size));
412         // unlink memheader from doubly linked list
413         if ((mem->prev ? mem->prev->next != mem : pool->chain != mem) || (mem->next && mem->next->prev != mem))
414                 Sys_Error("Mem_Free: not allocated or double freed (free at %s:%i)", filename, fileline);
415         if (mem_mutex)
416                 Thread_LockMutex(mem_mutex);
417         if (mem->prev)
418                 mem->prev->next = mem->next;
419         else
420                 pool->chain = mem->next;
421         if (mem->next)
422                 mem->next->prev = mem->prev;
423         // memheader has been unlinked, do the actual free now
424         size = mem->size;
425         realsize = sizeof(memheader_t) + size + sizeof(sentinel2);
426         pool->totalsize -= size;
427         pool->realsize -= realsize;
428         Clump_FreeBlock(mem->baseaddress, realsize);
429         if (mem_mutex)
430                 Thread_UnlockMutex(mem_mutex);
431 }
432
433 void _Mem_Free(void *data, const char *filename, int fileline)
434 {
435         if (data == NULL)
436         {
437                 Con_DPrintf("Mem_Free: data == NULL (called at %s:%i)\n", filename, fileline);
438                 return;
439         }
440
441         if (developer_memorydebug.integer)
442         {
443                 //_Mem_CheckSentinelsGlobal(filename, fileline);
444                 if (!Mem_IsAllocated(NULL, data))
445                         Sys_Error("Mem_Free: data is not allocated (called at %s:%i)", filename, fileline);
446         }
447
448         _Mem_FreeBlock((memheader_t *)((unsigned char *) data - sizeof(memheader_t)), filename, fileline);
449 }
450
451 mempool_t *_Mem_AllocPool(const char *name, int flags, mempool_t *parent, const char *filename, int fileline)
452 {
453         mempool_t *pool;
454         if (developer_memorydebug.integer)
455                 _Mem_CheckSentinelsGlobal(filename, fileline);
456         pool = (mempool_t *)Clump_AllocBlock(sizeof(mempool_t));
457         if (pool == NULL)
458         {
459                 Mem_PrintList(0);
460                 Mem_PrintStats();
461                 Mem_PrintList(1<<30);
462                 Mem_PrintStats();
463                 Sys_Error("Mem_AllocPool: out of memory (allocpool at %s:%i)", filename, fileline);
464         }
465         memset(pool, 0, sizeof(mempool_t));
466         pool->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1);
467         pool->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2);
468         pool->filename = filename;
469         pool->fileline = fileline;
470         pool->flags = flags;
471         pool->chain = NULL;
472         pool->totalsize = 0;
473         pool->realsize = sizeof(mempool_t);
474         strlcpy (pool->name, name, sizeof (pool->name));
475         pool->parent = parent;
476         pool->next = poolchain;
477         poolchain = pool;
478         return pool;
479 }
480
481 void _Mem_FreePool(mempool_t **poolpointer, const char *filename, int fileline)
482 {
483         mempool_t *pool = *poolpointer;
484         mempool_t **chainaddress, *iter, *temp;
485
486         if (developer_memorydebug.integer)
487                 _Mem_CheckSentinelsGlobal(filename, fileline);
488         if (pool)
489         {
490                 // unlink pool from chain
491                 for (chainaddress = &poolchain;*chainaddress && *chainaddress != pool;chainaddress = &((*chainaddress)->next));
492                 if (*chainaddress != pool)
493                         Sys_Error("Mem_FreePool: pool already free (freepool at %s:%i)", filename, fileline);
494                 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
495                         Sys_Error("Mem_FreePool: trashed pool sentinel 1 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
496                 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
497                         Sys_Error("Mem_FreePool: trashed pool sentinel 2 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
498                 *chainaddress = pool->next;
499
500                 // free memory owned by the pool
501                 while (pool->chain)
502                         _Mem_FreeBlock(pool->chain, filename, fileline);
503
504                 // free child pools, too
505                 for(iter = poolchain; iter; temp = iter = iter->next)
506                         if(iter->parent == pool)
507                                 _Mem_FreePool(&temp, filename, fileline);
508
509                 // free the pool itself
510                 Clump_FreeBlock(pool, sizeof(*pool));
511
512                 *poolpointer = NULL;
513         }
514 }
515
516 void _Mem_EmptyPool(mempool_t *pool, const char *filename, int fileline)
517 {
518         mempool_t *chainaddress;
519
520         if (developer_memorydebug.integer)
521         {
522                 //_Mem_CheckSentinelsGlobal(filename, fileline);
523                 // check if this pool is in the poolchain
524                 for (chainaddress = poolchain;chainaddress;chainaddress = chainaddress->next)
525                         if (chainaddress == pool)
526                                 break;
527                 if (!chainaddress)
528                         Sys_Error("Mem_EmptyPool: pool is already free (emptypool at %s:%i)", filename, fileline);
529         }
530         if (pool == NULL)
531                 Sys_Error("Mem_EmptyPool: pool == NULL (emptypool at %s:%i)", filename, fileline);
532         if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
533                 Sys_Error("Mem_EmptyPool: trashed pool sentinel 1 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
534         if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
535                 Sys_Error("Mem_EmptyPool: trashed pool sentinel 2 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
536
537         // free memory owned by the pool
538         while (pool->chain)
539                 _Mem_FreeBlock(pool->chain, filename, fileline);
540
541         // empty child pools, too
542         for(chainaddress = poolchain; chainaddress; chainaddress = chainaddress->next)
543                 if(chainaddress->parent == pool)
544                         _Mem_EmptyPool(chainaddress, filename, fileline);
545
546 }
547
548 void _Mem_CheckSentinels(void *data, const char *filename, int fileline)
549 {
550         memheader_t *mem;
551         unsigned int sentinel1;
552         unsigned int sentinel2;
553
554         if (data == NULL)
555                 Sys_Error("Mem_CheckSentinels: data == NULL (sentinel check at %s:%i)", filename, fileline);
556
557         mem = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
558         sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
559         sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
560         if (mem->sentinel != sentinel1)
561                 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
562         if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
563                 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
564 }
565
566 #if MEMCLUMPING
567 static void _Mem_CheckClumpSentinels(memclump_t *clump, const char *filename, int fileline)
568 {
569         // this isn't really very useful
570         if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
571                 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 1 (sentinel check at %s:%i)", filename, fileline);
572         if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
573                 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 2 (sentinel check at %s:%i)", filename, fileline);
574 }
575 #endif
576
577 void _Mem_CheckSentinelsGlobal(const char *filename, int fileline)
578 {
579         memheader_t *mem;
580 #if MEMCLUMPING
581         memclump_t *clump;
582 #endif
583         mempool_t *pool;
584         for (pool = poolchain;pool;pool = pool->next)
585         {
586                 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
587                         Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 1 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
588                 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
589                         Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 2 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
590         }
591         for (pool = poolchain;pool;pool = pool->next)
592                 for (mem = pool->chain;mem;mem = mem->next)
593                         _Mem_CheckSentinels((void *)((unsigned char *) mem + sizeof(memheader_t)), filename, fileline);
594 #if MEMCLUMPING
595         for (pool = poolchain;pool;pool = pool->next)
596                 for (clump = clumpchain;clump;clump = clump->chain)
597                         _Mem_CheckClumpSentinels(clump, filename, fileline);
598 #endif
599 }
600
601 qboolean Mem_IsAllocated(mempool_t *pool, void *data)
602 {
603         memheader_t *header;
604         memheader_t *target;
605
606         if (pool)
607         {
608                 // search only one pool
609                 target = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
610                 for( header = pool->chain ; header ; header = header->next )
611                         if( header == target )
612                                 return true;
613         }
614         else
615         {
616                 // search all pools
617                 for (pool = poolchain;pool;pool = pool->next)
618                         if (Mem_IsAllocated(pool, data))
619                                 return true;
620         }
621         return false;
622 }
623
624 void Mem_ExpandableArray_NewArray(memexpandablearray_t *l, mempool_t *mempool, size_t recordsize, int numrecordsperarray)
625 {
626         memset(l, 0, sizeof(*l));
627         l->mempool = mempool;
628         l->recordsize = recordsize;
629         l->numrecordsperarray = numrecordsperarray;
630 }
631
632 void Mem_ExpandableArray_FreeArray(memexpandablearray_t *l)
633 {
634         size_t i;
635         if (l->maxarrays)
636         {
637                 for (i = 0;i != l->numarrays;i++)
638                         Mem_Free(l->arrays[i].data);
639                 Mem_Free(l->arrays);
640         }
641         memset(l, 0, sizeof(*l));
642 }
643
644 // VorteX: hacked Mem_ExpandableArray_AllocRecord, it does allocate record at certain index
645 void *Mem_ExpandableArray_AllocRecordAtIndex(memexpandablearray_t *l, size_t index)
646 {
647         size_t j;
648         if (index >= l->numarrays)
649         {
650                 if (l->numarrays == l->maxarrays)
651                 {
652                         memexpandablearray_array_t *oldarrays = l->arrays;
653                         l->maxarrays = max(l->maxarrays * 2, 128);
654                         l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
655                         if (oldarrays)
656                         {
657                                 memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
658                                 Mem_Free(oldarrays);
659                         }
660                 }
661                 l->arrays[index].numflaggedrecords = 0;
662                 l->arrays[index].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
663                 l->arrays[index].allocflags = l->arrays[index].data + l->recordsize * l->numrecordsperarray;
664                 l->numarrays++;
665         }
666         if (l->arrays[index].numflaggedrecords < l->numrecordsperarray)
667         {
668                 for (j = 0;j < l->numrecordsperarray;j++)
669                 {
670                         if (!l->arrays[index].allocflags[j])
671                         {
672                                 l->arrays[index].allocflags[j] = true;
673                                 l->arrays[index].numflaggedrecords++;
674                                 memset(l->arrays[index].data + l->recordsize * j, 0, l->recordsize);
675                                 return (void *)(l->arrays[index].data + l->recordsize * j);
676                         }
677                 }
678         }
679         return NULL;
680 }
681
682 void *Mem_ExpandableArray_AllocRecord(memexpandablearray_t *l)
683 {
684         size_t i, j;
685         for (i = 0;;i++)
686         {
687                 if (i == l->numarrays)
688                 {
689                         if (l->numarrays == l->maxarrays)
690                         {
691                                 memexpandablearray_array_t *oldarrays = l->arrays;
692                                 l->maxarrays = max(l->maxarrays * 2, 128);
693                                 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
694                                 if (oldarrays)
695                                 {
696                                         memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
697                                         Mem_Free(oldarrays);
698                                 }
699                         }
700                         l->arrays[i].numflaggedrecords = 0;
701                         l->arrays[i].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
702                         l->arrays[i].allocflags = l->arrays[i].data + l->recordsize * l->numrecordsperarray;
703                         l->numarrays++;
704                 }
705                 if (l->arrays[i].numflaggedrecords < l->numrecordsperarray)
706                 {
707                         for (j = 0;j < l->numrecordsperarray;j++)
708                         {
709                                 if (!l->arrays[i].allocflags[j])
710                                 {
711                                         l->arrays[i].allocflags[j] = true;
712                                         l->arrays[i].numflaggedrecords++;
713                                         memset(l->arrays[i].data + l->recordsize * j, 0, l->recordsize);
714                                         return (void *)(l->arrays[i].data + l->recordsize * j);
715                                 }
716                         }
717                 }
718         }
719 }
720
721 /*****************************************************************************
722  * IF YOU EDIT THIS:
723  * If this function was to change the size of the "expandable" array, you have
724  * to update r_shadow.c
725  * Just do a search for "range =", R_ShadowClearWorldLights would be the first
726  * function to look at. (And also seems like the only one?) You  might have to
727  * move the  call to Mem_ExpandableArray_IndexRange  back into for(...) loop's
728  * condition
729  */
730 void Mem_ExpandableArray_FreeRecord(memexpandablearray_t *l, void *record) // const!
731 {
732         size_t i, j;
733         unsigned char *p = (unsigned char *)record;
734         for (i = 0;i != l->numarrays;i++)
735         {
736                 if (p >= l->arrays[i].data && p < (l->arrays[i].data + l->recordsize * l->numrecordsperarray))
737                 {
738                         j = (p - l->arrays[i].data) / l->recordsize;
739                         if (p != l->arrays[i].data + j * l->recordsize)
740                                 Sys_Error("Mem_ExpandableArray_FreeRecord: no such record %p\n", p);
741                         if (!l->arrays[i].allocflags[j])
742                                 Sys_Error("Mem_ExpandableArray_FreeRecord: record %p is already free!\n", p);
743                         l->arrays[i].allocflags[j] = false;
744                         l->arrays[i].numflaggedrecords--;
745                         return;
746                 }
747         }
748 }
749
750 size_t Mem_ExpandableArray_IndexRange(const memexpandablearray_t *l)
751 {
752         size_t i, j, k, end = 0;
753         for (i = 0;i < l->numarrays;i++)
754         {
755                 for (j = 0, k = 0;k < l->arrays[i].numflaggedrecords;j++)
756                 {
757                         if (l->arrays[i].allocflags[j])
758                         {
759                                 end = l->numrecordsperarray * i + j + 1;
760                                 k++;
761                         }
762                 }
763         }
764         return end;
765 }
766
767 void *Mem_ExpandableArray_RecordAtIndex(const memexpandablearray_t *l, size_t index)
768 {
769         size_t i, j;
770         i = index / l->numrecordsperarray;
771         j = index % l->numrecordsperarray;
772         if (i >= l->numarrays || !l->arrays[i].allocflags[j])
773                 return NULL;
774         return (void *)(l->arrays[i].data + j * l->recordsize);
775 }
776
777
778 // used for temporary memory allocations around the engine, not for longterm
779 // storage, if anything in this pool stays allocated during gameplay, it is
780 // considered a leak
781 mempool_t *tempmempool;
782 // only for zone
783 mempool_t *zonemempool;
784
785 void Mem_PrintStats(void)
786 {
787         size_t count = 0, size = 0, realsize = 0;
788         mempool_t *pool;
789         memheader_t *mem;
790         Mem_CheckSentinelsGlobal();
791         for (pool = poolchain;pool;pool = pool->next)
792         {
793                 count++;
794                 size += pool->totalsize;
795                 realsize += pool->realsize;
796         }
797         Con_Printf("%lu memory pools, totalling %lu bytes (%.3fMB)\n", (unsigned long)count, (unsigned long)size, size / 1048576.0);
798         Con_Printf("total allocated size: %lu bytes (%.3fMB)\n", (unsigned long)realsize, realsize / 1048576.0);
799         for (pool = poolchain;pool;pool = pool->next)
800         {
801                 if ((pool->flags & POOLFLAG_TEMP) && pool->chain)
802                 {
803                         Con_Printf("Memory pool %p has sprung a leak totalling %lu bytes (%.3fMB)!  Listing contents...\n", (void *)pool, (unsigned long)pool->totalsize, pool->totalsize / 1048576.0);
804                         for (mem = pool->chain;mem;mem = mem->next)
805                                 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
806                 }
807         }
808 }
809
810 void Mem_PrintList(size_t minallocationsize)
811 {
812         mempool_t *pool;
813         memheader_t *mem;
814         Mem_CheckSentinelsGlobal();
815         Con_Print("memory pool list:\n"
816                    "size    name\n");
817         for (pool = poolchain;pool;pool = pool->next)
818         {
819                 Con_Printf("%10luk (%10luk actual) %s (%+li byte change) %s\n", (unsigned long) ((pool->totalsize + 1023) / 1024), (unsigned long)((pool->realsize + 1023) / 1024), pool->name, (long)(pool->totalsize - pool->lastchecksize), (pool->flags & POOLFLAG_TEMP) ? "TEMP" : "");
820                 pool->lastchecksize = pool->totalsize;
821                 for (mem = pool->chain;mem;mem = mem->next)
822                         if (mem->size >= minallocationsize)
823                                 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
824         }
825 }
826
827 void MemList_f(void)
828 {
829         switch(Cmd_Argc())
830         {
831         case 1:
832                 Mem_PrintList(1<<30);
833                 Mem_PrintStats();
834                 break;
835         case 2:
836                 Mem_PrintList(atoi(Cmd_Argv(1)) * 1024);
837                 Mem_PrintStats();
838                 break;
839         default:
840                 Con_Print("MemList_f: unrecognized options\nusage: memlist [all]\n");
841                 break;
842         }
843 }
844
845 extern void R_TextureStats_Print(qboolean printeach, qboolean printpool, qboolean printtotal);
846 void MemStats_f(void)
847 {
848         Mem_CheckSentinelsGlobal();
849         R_TextureStats_Print(false, false, true);
850         GL_Mesh_ListVBOs(false);
851         Mem_PrintStats();
852 }
853
854
855 char* Mem_strdup (mempool_t *pool, const char* s)
856 {
857         char* p;
858         size_t sz;
859         if (s == NULL)
860                 return NULL;
861         sz = strlen (s) + 1;
862         p = (char*)Mem_Alloc (pool, sz);
863         strlcpy (p, s, sz);
864         return p;
865 }
866
867 /*
868 ========================
869 Memory_Init
870 ========================
871 */
872 void Memory_Init (void)
873 {
874         static union {unsigned short s;unsigned char b[2];} u;
875         u.s = 0x100;
876         mem_bigendian = u.b[0] != 0;
877
878         if (Thread_HasThreads())
879                 mem_mutex = Thread_CreateMutex();
880
881         sentinel_seed = rand();
882         poolchain = NULL;
883         tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
884         zonemempool = Mem_AllocPool("Zone", 0, NULL);
885 }
886
887 void Memory_Shutdown (void)
888 {
889 //      Mem_FreePool (&zonemempool);
890 //      Mem_FreePool (&tempmempool);
891
892         if (mem_mutex)
893                 Thread_DestroyMutex(mem_mutex);
894         mem_mutex = NULL;
895 }
896
897 void Memory_Init_Commands (void)
898 {
899         Cmd_AddCommand ("memstats", MemStats_f, "prints memory system statistics");
900         Cmd_AddCommand ("memlist", MemList_f, "prints memory pool information (or if used as memlist 5 lists individual allocations of 5K or larger, 0 lists all allocations)");
901         Cvar_RegisterVariable (&developer_memory);
902         Cvar_RegisterVariable (&developer_memorydebug);
903         Cvar_RegisterVariable (&sys_memsize_physical);
904         Cvar_RegisterVariable (&sys_memsize_virtual);
905
906 #if defined(WIN32)
907 #ifdef _WIN64
908         {
909                 MEMORYSTATUSEX status;
910                 // first guess
911                 Cvar_SetValueQuick(&sys_memsize_virtual, 8388608);
912                 // then improve
913                 status.dwLength = sizeof(status);
914                 if(GlobalMemoryStatusEx(&status))
915                 {
916                         Cvar_SetValueQuick(&sys_memsize_physical, status.ullTotalPhys / 1048576.0);
917                         Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.ullTotalVirtual / 1048576.0));
918                 }
919         }
920 #else
921         {
922                 MEMORYSTATUS status;
923                 // first guess
924                 Cvar_SetValueQuick(&sys_memsize_virtual, 2048);
925                 // then improve
926                 status.dwLength = sizeof(status);
927                 GlobalMemoryStatus(&status);
928                 Cvar_SetValueQuick(&sys_memsize_physical, status.dwTotalPhys / 1048576.0);
929                 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.dwTotalVirtual / 1048576.0));
930         }
931 #endif
932 #else
933         {
934                 // first guess
935                 Cvar_SetValueQuick(&sys_memsize_virtual, (sizeof(void*) == 4) ? 2048 : 268435456);
936                 // then improve
937                 {
938                         // Linux, and BSD with linprocfs mounted
939                         FILE *f = fopen("/proc/meminfo", "r");
940                         if(f)
941                         {
942                                 static char buf[1024];
943                                 while(fgets(buf, sizeof(buf), f))
944                                 {
945                                         const char *p = buf;
946                                         if(!COM_ParseToken_Console(&p))
947                                                 continue;
948                                         if(!strcmp(com_token, "MemTotal:"))
949                                         {
950                                                 if(!COM_ParseToken_Console(&p))
951                                                         continue;
952                                                 Cvar_SetValueQuick(&sys_memsize_physical, atof(com_token) / 1024.0);
953                                         }
954                                         if(!strcmp(com_token, "SwapTotal:"))
955                                         {
956                                                 if(!COM_ParseToken_Console(&p))
957                                                         continue;
958                                                 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value , atof(com_token) / 1024.0 + sys_memsize_physical.value));
959                                         }
960                                 }
961                                 fclose(f);
962                         }
963                 }
964         }
965 #endif
966 }
967