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 * memory-pool
9 * (i.e. 4kB * 12 blocks) can be initialized. Note: this allocator
10 * is for use on processors without an MMU (memory management
11 * unit). A MPU (memory protection unit), if available can be used
12 * to protect certain zones.
14 * This work is based on an article of Ben Kenwright.
16 * Preconditions: programmer should make sure the SRAM entry point
17 * + (blocks * blocksize) is free.
20 * KERNEL: can initialize a big pool for all user tasks
22 * USER TASKS/PROCESS: can use this to dynamically allocate their
23 * own memory (i.e. heap)
33 #include <lib/string.h>
36 void kpool_init(mem_pool_t * pool, size_t size_arg, unsigned int blocks_arg, uint32_t * entry_SRAM) {
38 pool->blocks = blocks_arg;
39 pool->block_size = size_arg;
40 pool->blocks_init = 0;
41 pool->SRAM_entry = entry_SRAM;
42 memset(entry_SRAM, 0x00, (sizeof(char) * (size_arg * blocks_arg)));
43 pool->free_blocks = blocks_arg;
44 pool->m_next = pool->SRAM_entry;
47 /* void deletepool() {
48 pool->SRAM_entry = NULL;
51 /* Helper functions */
52 uint32_t * AddrFromIndex(mem_pool_t * pool, unsigned int i) {
53 return pool->SRAM_entry + ( i * pool->block_size );
57 unsigned int IndexFromAddr(mem_pool_t * pool, const uint32_t * p) {
58 return (((unsigned int)(p - pool->SRAM_entry)) / pool->block_size);
63 void * kalloc(mem_pool_t * pool) {
64 if (pool->blocks_init < pool->blocks ) {
65 unsigned int * p = (unsigned int *)AddrFromIndex(pool, pool->blocks_init );
66 *p = pool->blocks_init + 1;
71 if ( pool->free_blocks > 0 ) {
72 ret = (void*)pool->m_next;
74 if (pool->free_blocks!=0) {
75 pool->m_next = AddrFromIndex(pool, *((unsigned int*)pool->m_next) );
85 void kfree(mem_pool_t * pool, void* p) {
86 if (pool->m_next != NULL) {
87 (*(unsigned int *)p) = IndexFromAddr(pool, pool->m_next );
88 pool->m_next = (uint32_t *)p;
91 *((unsigned int*)p) = pool->blocks;
92 pool->m_next = (uint32_t *) p;