1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
|
#include "types.h"
#include "consts.h"
#include "OS/OSAlloc.h"
static inline Cell* DLAddFront(Cell* list, Cell* cell)
{
cell->next = list;
cell->prev = NULL;
if (list != NULL)
list->prev = cell;
return cell;
}
static inline Cell* DLExtract(Cell* list, Cell* cell)
{
if (cell->next) {
cell->next->prev = cell->prev;
}
if (cell->prev == NULL) {
list = cell->next;
} else {
cell->prev->next = cell->next;
}
return list;
}
Cell *DLInsert(Cell *original, Cell *inserted)
{
Cell *prevCell = NULL;
Cell *nextCell = original;
for (nextCell = original, prevCell = NULL; nextCell; prevCell = nextCell, nextCell = nextCell->next)
{
if (inserted <= nextCell)
break;
}
inserted->next = nextCell;
inserted->prev = prevCell;
if (nextCell != NULL)
{
nextCell->prev = inserted;
Cell * temp = (Cell *)((char *)inserted + inserted->size);
if (temp == nextCell)
{
inserted->size += nextCell->size;
nextCell = nextCell->next;
inserted->next = nextCell;
if (nextCell != NULL)
nextCell->prev = inserted;
}
}
if (prevCell != NULL)
{
prevCell->next = inserted;
Cell * temp = (Cell *)((char *)prevCell + prevCell->size);
if (temp != inserted)
return original;
prevCell->size += inserted->size;
prevCell->next = nextCell;
if (nextCell != NULL)
nextCell->prev = prevCell;
return original;
}
return inserted;
}
extern HeapDesc *HeapArray;
#define HEADERSIZE OSi_ROUND(sizeof(Cell), 32)
#define MINOBJSIZE (HEADERSIZE+32)
void* OSAllocFromHeap(OSHeapHandle heap, u32 size)
{
HeapDesc* hd;
Cell* cell;
Cell* newCell;
long leftoverSize;
hd = &HeapArray[heap];
size += HEADERSIZE;
size = OSi_ROUND(size, 32);
for (cell = hd->free; cell != NULL; cell = cell->next) {
if ((long)size <= cell->size) {
break;
}
}
if (cell == NULL) {
return NULL;
}
leftoverSize = cell->size - (long)size;
if (leftoverSize < MINOBJSIZE) {
hd->free = DLExtract(hd->free, cell);
} else {
cell->size = (long)size;
newCell = (Cell *) ((char *)cell + size);
newCell->size = leftoverSize;
newCell->prev = cell->prev;
newCell->next = cell->next;
if (newCell->next != NULL) {
newCell->next->prev = newCell;
}
if (newCell->prev != NULL) {
newCell->prev->next = newCell;
} else {
hd->free = newCell;
}
}
hd->allocated = DLAddFront(hd->allocated, cell);
return (void *)((char *)cell + HEADERSIZE);
}
void OSFreeToHeap(OSHeapHandle heap, void* ptr)
{
HeapDesc *hd;
Cell *cell;
cell = (Cell *) ((char *)ptr - HEADERSIZE);
hd = &HeapArray[heap];
hd->allocated = DLExtract(hd->allocated, cell);
hd->free = DLInsert(hd->free, cell);
}
|