xref: /aosp_15_r20/external/mesa3d/src/gallium/drivers/r300/compiler/memory_pool.c (revision 6104692788411f58d303aa86923a9ff6ecaded22)
1 /*
2  * Copyright 2009 Nicolai Hähnle <[email protected]>
3  * SPDX-License-Identifier: MIT
4  */
5 
6 #include "memory_pool.h"
7 
8 #include <assert.h>
9 #include <stdlib.h>
10 #include <string.h>
11 
12 
13 #define POOL_LARGE_ALLOC 4096
14 #define POOL_ALIGN 8
15 
16 
17 struct memory_block {
18 	struct memory_block * next;
19 };
20 
memory_pool_init(struct memory_pool * pool)21 void memory_pool_init(struct memory_pool * pool)
22 {
23 	memset(pool, 0, sizeof(struct memory_pool));
24 }
25 
26 
memory_pool_destroy(struct memory_pool * pool)27 void memory_pool_destroy(struct memory_pool * pool)
28 {
29 	while(pool->blocks) {
30 		struct memory_block * block = pool->blocks;
31 		pool->blocks = block->next;
32 		free(block);
33 	}
34 }
35 
refill_pool(struct memory_pool * pool)36 static void refill_pool(struct memory_pool * pool)
37 {
38 	unsigned int blocksize = pool->total_allocated;
39 	struct memory_block * newblock;
40 
41 	if (!blocksize)
42 		blocksize = 2*POOL_LARGE_ALLOC;
43 
44 	newblock = malloc(blocksize);
45 	newblock->next = pool->blocks;
46 	pool->blocks = newblock;
47 
48 	pool->head = (unsigned char*)(newblock + 1);
49 	pool->end = ((unsigned char*)newblock) + blocksize;
50 	pool->total_allocated += blocksize;
51 }
52 
53 
memory_pool_malloc(struct memory_pool * pool,unsigned int bytes)54 void * memory_pool_malloc(struct memory_pool * pool, unsigned int bytes)
55 {
56 	if (bytes < POOL_LARGE_ALLOC) {
57 		void * ptr;
58 
59 		if (pool->head + bytes > pool->end)
60 			refill_pool(pool);
61 
62 		assert(pool->head + bytes <= pool->end);
63 
64 		ptr = pool->head;
65 
66 		pool->head += bytes;
67 		pool->head = (unsigned char*)(((unsigned long)pool->head + POOL_ALIGN - 1) & ~(POOL_ALIGN - 1));
68 
69 		return ptr;
70 	} else {
71 		struct memory_block * block = malloc(bytes + sizeof(struct memory_block));
72 
73 		block->next = pool->blocks;
74 		pool->blocks = block;
75 
76 		return (block + 1);
77 	}
78 }
79 
80 
81