1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
30
31
32
33
34
35
45
46
51
56
57
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
83
84
85
86
87
88
89
94
95
96
97
98
99
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
123
124
125
126
127
130
131
/* ... */
#include "k_mem.h"
/* ... */
/* ... */
Includes
#define MEM_BASE 0x10000000
#if (defined ( __CC_ARM ))
mem_TypeDef memory_pool __attribute__((at(MEM_BASE)));
#elif (defined (__ICCARM__))
#pragma location = MEM_BASE
__no_init mem_TypeDef memory_pool;/* ... */
#elif defined ( __GNUC__ )
mem_TypeDef memory_pool __attribute__((section(".ExtRAMData")));
#endif
Private variables
/* ... */
void k_MemInit(void)
{
memset(&memory_pool, 0, sizeof(mem_TypeDef));
memory_pool.mallocBase = MEM_BASE + sizeof(mem_TypeDef);
}{ ... }
/* ... */
void * k_malloc(size_t size)
{
__IO uint8_t index = 0, counter = 0, start = 0;
uint8_t PageCount = 0, NewStart = 0;
if (size > 0)
{
while ( index < (MAX_PAGE_NUMBER))
{
if (memory_pool.PageTable[index++] == 0)
{
counter++;
if (size <= (counter * SIZE_OF_PAGE))
{
PageCount = counter - 1;
NewStart = start;
for (index = 0; index <= PageCount;index++)
{
memory_pool.PageTable[NewStart + index] = 1;
}for (index = 0; index <= PageCount;index++) { ... }
memory_pool.size[NewStart] = counter;
return (void *)((memory_pool.mallocBase + (start << 10)) + 1 * sizeof(uint32_t));
}if (size <= (counter * SIZE_OF_PAGE)) { ... }
}if (memory_pool.PageTable[index++] == 0) { ... }
else
{
start = index;
counter = 0;
}else { ... }
}while (index < (MAX_PAGE_NUMBER)) { ... }
}if (size > 0) { ... }
return NULL;
}{ ... }
/* ... */
void k_free(void * p)
{
__IO uint8_t index = 0;
uint8_t counter = 0, start = 0;
if (p == NULL)
return;
start = ((((uint32_t)p - sizeof(uint32_t)) - memory_pool.mallocBase) >> 10);
counter = memory_pool.size[start];
memory_pool.size[start] = 0;
for (index = 0; index < counter; index++)
{
memory_pool.PageTable[start + index] = 0;
}for (index = 0; index < counter; index++) { ... }
return;
}{ ... }
/* ... */
/* ... */