1 /* (CC-BY-NC-SA) ROBIN KRENS - ROBIN @ ROBINKRENS.NL
4 * 2019/7/20 - ROBIN KRENS
8 * Fixed-sized memory pool allocation. A so called
9 * memory-pool (i.e. 4kB * 12 blocks) can be
10 * initialized. Note: this allocator is for use on
11 * processors without an MMU (memory management
12 * unit). A MPU (memory protection unit), if
13 * available can be used to protect certain zones.
15 * This work is based on an article of Ben Kenwright
17 * Preconditions: programmer should make sure the
18 * SRAM entry point + (blocks * blocksize) is free.
21 * KERNEL: can use initialize a big pool for all
24 * USER TASKS/PROCESS: can use this to dynamically
25 * allocate their own memory (i.e. heap)
39 unsigned short blocks;
40 unsigned short block_size;
41 unsigned short free_blocks;
42 unsigned short blocks_alloc;
43 uint32_t * SRAM_entry;
51 void pool_init(size_t size_arg, unsigned int blocks_arg, uint32_t * entry_SRAM) {
53 mem.blocks = blocks_arg;
54 mem.block_size = size_arg;
55 mem.SRAM_entry = entry_SRAM;
56 memset(entry_SRAM, 0x00, (sizeof(char) * (size_arg * blocks_arg)));
57 mem.free_blocks = blocks_arg;
58 mem.m_next = mem.SRAM_entry;
61 /* uint32_t * a = alloc();
62 uint32_t * b = alloc();
63 uint32_t * c = alloc();
65 uint32_t * d = alloc();
75 /* void deletepool() {
76 mem.SRAM_entry = NULL;
79 uint32_t * AddrFromIndex(unsigned int i) {
80 return mem.SRAM_entry + ( i * mem.block_size );
84 unsigned int IndexFromAddr(const uint32_t * p) {
85 return (((unsigned int)(p - mem.SRAM_entry)) / mem.block_size);
90 if (mem.blocks_alloc < mem.blocks ) {
91 unsigned int * p = (unsigned int *)AddrFromIndex( mem.blocks_alloc );
92 *p = mem.blocks_alloc + 1;
97 if ( mem.free_blocks > 0 ) {
98 ret = (void*)mem.m_next;
100 if (mem.free_blocks!=0) {
101 mem.m_next = AddrFromIndex( *((unsigned int*)mem.m_next) );
112 if (mem.m_next != NULL) {
113 (*(unsigned int *)p) = IndexFromAddr( mem.m_next );
114 mem.m_next = (uint32_t *)p;
117 *((unsigned int*)p) = mem.blocks;
118 mem.m_next = (uint32_t *) p;