-
Notifications
You must be signed in to change notification settings - Fork 4
/
mm.c
432 lines (361 loc) · 15.1 KB
/
mm.c
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/*-------------------------------------------------------------------
* UW CSE 351 Sprint 2010 Lab 7 Starter code:
* single doubly-linked free block list with LIFO policy
* with support for coalescing adjacent free blocks
*
* Terminology:
* o We will implement an explicit free list allocator
* o We use "next" and "previous" to refer to blocks as ordered in
* the free list.
* o We use "following" and "preceding" to refer to adjacent blocks
* in memory.
*-------------------------------------------------------------------- */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include "memlib.h"
#include "mm.h"
/* Macros for pointer arithmetic to keep other code cleaner. Casting
to a char* has the effect that pointer arithmetic happens at the
byte granularity (i.e. POINTER_ADD(0x1, 1) would be 0x2). (By
default, incrementing a pointer in C has the effect of incrementing
it by the size of the type to which it points (e.g. BlockInfo).) */
#define POINTER_ADD(p,x) ((char*)(p) + (x))
#define POINTER_SUB(p,x) ((char*)(p) - (x))
/******** FREE LIST IMPLEMENTATION ***********************************/
/* A BlockInfo contains information about a block, including the size
and usage tags, as well as pointers to the next and previous blocks
in the free list. This is exactly the "explicit free list" structure
illustrated in the lecture slides.
Note that the next and prev pointers and the boundary tag are only
needed when the block is free. To achieve better utilization, mm_malloc
should use the space for next and prev as part of the space it returns.
+--------------+
| sizeAndTags | <- BlockInfo pointers in free list point here
| (header) |
+--------------+
| next | <- Pointers returned by mm_malloc point here
+--------------+
| prev |
+--------------+
| space and |
| padding |
| ... |
| ... |
+--------------+
| boundary tag |
| (footer) |
+--------------+
*/
struct BlockInfo {
// Size of the block (in the high bits) and tags for whether the
// block and its predecessor in memory are in use. See the SIZE()
// and TAG macros, below, for more details.
size_t sizeAndTags;
// Pointer to the next block in the free list.
struct BlockInfo* next;
// Pointer to the previous block in the free list.
struct BlockInfo* prev;
};
typedef struct BlockInfo BlockInfo;
/* Pointer to the first BlockInfo in the free list, the list's head.
A pointer to the head of the free list in this implementation is
always stored in the first word in the heap. mem_heap_lo() returns
a pointer to the first word in the heap, so we cast the result of
mem_heap_lo() to a BlockInfo** (a pointer to a pointer to
BlockInfo) and dereference this to get a pointer to the first
BlockInfo in the free list. */
#define FREE_LIST_HEAD *((BlockInfo **)mem_heap_lo())
/* Size of a word on this architecture. */
#define WORD_SIZE sizeof(void*)
/* Minimum block size (to account for size header, next ptr, prev ptr,
and boundary tag) */
#define MIN_BLOCK_SIZE (sizeof(BlockInfo) + WORD_SIZE)
/* Alignment of blocks returned by mm_malloc. */
#define ALIGNMENT 8
/* SIZE(blockInfo->sizeAndTags) extracts the size of a 'sizeAndTags' field.
Also, calling SIZE(size) selects just the higher bits of 'size' to ensure
that 'size' is properly aligned. We align 'size' so we can use the low
bits of the sizeAndTags field to tag a block as free/used, etc, like this:
sizeAndTags:
+-------------------------------------------+
| 63 | 62 | 61 | 60 | . . . . | 2 | 1 | 0 |
+-------------------------------------------+
^ ^
high bit low bit
Since ALIGNMENT == 8, we reserve the low 3 bits of sizeAndTags for tag
bits, and we use bits 3-63 to store the size.
Bit 0 (2^0 == 1): TAG_USED
Bit 1 (2^1 == 2): TAG_PRECEDING_USED
*/
#define SIZE(x) ((x) & ~(ALIGNMENT - 1))
/* TAG_USED is the bit mask used in sizeAndTags to mark a block as used. */
#define TAG_USED 1
/* TAG_PRECEDING_USED is the bit mask used in sizeAndTags to indicate
that the block preceding it in memory is used. (used in turn for
coalescing). If the previous block is not used, we can learn the size
of the previous block from its boundary tag */
#define TAG_PRECEDING_USED 2
/* Find a free block of the requested size in the free list. Returns
NULL if no free block is large enough. */
static void * searchFreeList(size_t reqSize) {
BlockInfo* freeBlock;
freeBlock = FREE_LIST_HEAD;
while (freeBlock != NULL){
if (SIZE(freeBlock->sizeAndTags) >= reqSize) {
return freeBlock;
} else {
freeBlock = freeBlock->next;
}
}
return NULL;
}
/* Insert freeBlock at the head of the list. (LIFO) */
static void insertFreeBlock(BlockInfo* freeBlock) {
BlockInfo* oldHead = FREE_LIST_HEAD;
freeBlock->next = oldHead;
if (oldHead != NULL) {
oldHead->prev = freeBlock;
}
// freeBlock->prev = NULL;
FREE_LIST_HEAD = freeBlock;
}
/* Remove a free block from the free list. */
static void removeFreeBlock(BlockInfo* freeBlock) {
BlockInfo *nextFree, *prevFree;
nextFree = freeBlock->next;
prevFree = freeBlock->prev;
// If the next block is not null, patch its prev pointer.
if (nextFree != NULL) {
nextFree->prev = prevFree;
}
// If we're removing the head of the free list, set the head to be
// the next block, otherwise patch the previous block's next pointer.
if (freeBlock == FREE_LIST_HEAD) {
FREE_LIST_HEAD = nextFree;
} else {
prevFree->next = nextFree;
}
}
/* Coalesce 'oldBlock' with any preceeding or following free blocks. */
static void coalesceFreeBlock(BlockInfo* oldBlock) {
BlockInfo *blockCursor;
BlockInfo *newBlock;
BlockInfo *freeBlock;
// size of old block
size_t oldSize = SIZE(oldBlock->sizeAndTags);
// running sum to be size of final coalesced block
size_t newSize = oldSize;
// Coalesce with any preceding free block
blockCursor = oldBlock;
while ((blockCursor->sizeAndTags & TAG_PRECEDING_USED)==0) {
// While the block preceding this one in memory (not the
// prev. block in the free list) is free:
// Get the size of the previous block from its boundary tag.
size_t size = SIZE(*((size_t*)POINTER_SUB(blockCursor, WORD_SIZE)));
// Use this size to find the block info for that block.
freeBlock = (BlockInfo*)POINTER_SUB(blockCursor, size);
// Remove that block from free list.
removeFreeBlock(freeBlock);
// Count that block's size and update the current block pointer.
newSize += size;
blockCursor = freeBlock;
}
newBlock = blockCursor;
// Coalesce with any following free block.
// Start with the block following this one in memory
blockCursor = (BlockInfo*)POINTER_ADD(oldBlock, oldSize);
while ((blockCursor->sizeAndTags & TAG_USED)==0) {
// While the block is free:
size_t size = SIZE(blockCursor->sizeAndTags);
// Remove it from the free list.
removeFreeBlock(blockCursor);
// Count its size and step to the following block.
newSize += size;
blockCursor = (BlockInfo*)POINTER_ADD(blockCursor, size);
}
// If the block actually grew, remove the old entry from the free
// list and add the new entry.
if (newSize != oldSize) {
// Remove the original block from the free list
removeFreeBlock(oldBlock);
// Save the new size in the block info and in the boundary tag
// and tag it to show the preceding block is used (otherwise, it
// would have become part of this one!).
newBlock->sizeAndTags = newSize | TAG_PRECEDING_USED;
// The boundary tag of the preceding block is the word immediately
// preceding block in memory where we left off advancing blockCursor.
*(size_t*)POINTER_SUB(blockCursor, WORD_SIZE) = newSize | TAG_PRECEDING_USED;
// Put the new block in the free list.
insertFreeBlock(newBlock);
}
return;
}
/* Get more heap space of size at least reqSize. */
static void requestMoreSpace(size_t reqSize) {
size_t pagesize = mem_pagesize();
size_t numPages = (reqSize + pagesize - 1) / pagesize;
BlockInfo *newBlock;
size_t totalSize = numPages * pagesize;
size_t prevLastWordMask;
void* mem_sbrk_result = mem_sbrk(totalSize);
if ((size_t)mem_sbrk_result == -1) {
printf("ERROR: mem_sbrk failed in requestMoreSpace\n");
exit(0);
}
newBlock = (BlockInfo*)POINTER_SUB(mem_sbrk_result, WORD_SIZE);
/* initialize header, inherit TAG_PRECEDING_USED status from the
previously useless last word however, reset the fake TAG_USED
bit */
prevLastWordMask = newBlock->sizeAndTags & TAG_PRECEDING_USED;
newBlock->sizeAndTags = totalSize | prevLastWordMask;
// Initialize boundary tag.
((BlockInfo*)POINTER_ADD(newBlock, totalSize - WORD_SIZE))->sizeAndTags =
totalSize | prevLastWordMask;
/* initialize "new" useless last word
the previous block is free at this moment
but this word is useless, so its use bit is set
This trick lets us do the "normal" check even at the end of
the heap and avoid a special check to see if the following
block is the end of the heap... */
*((size_t*)POINTER_ADD(newBlock, totalSize)) = TAG_USED;
// Add the new block to the free list and immediately coalesce newly
// allocated memory space
insertFreeBlock(newBlock);
coalesceFreeBlock(newBlock);
}
/* Initialize the allocator. */
int mm_init () {
// Head of the free list.
BlockInfo *firstFreeBlock;
// Initial heap size: WORD_SIZE byte heap-header (stores pointer to head
// of free list), MIN_BLOCK_SIZE bytes of space, WORD_SIZE byte heap-footer.
size_t initSize = WORD_SIZE+MIN_BLOCK_SIZE+WORD_SIZE;
size_t totalSize;
void* mem_sbrk_result = mem_sbrk(initSize);
// printf("mem_sbrk returned %p\n", mem_sbrk_result);
if ((ssize_t)mem_sbrk_result == -1) {
printf("ERROR: mem_sbrk failed in mm_init, returning %p\n",
mem_sbrk_result);
exit(1);
}
firstFreeBlock = (BlockInfo*)POINTER_ADD(mem_heap_lo(), WORD_SIZE);
// Total usable size is full size minus heap-header and heap-footer words
// NOTE: These are different than the "header" and "footer" of a block!
// The heap-header is a pointer to the first free block in the free list.
// The heap-footer is used to keep the data structures consistent (see
// requestMoreSpace() for more info, but you should be able to ignore it).
totalSize = initSize - WORD_SIZE - WORD_SIZE;
// The heap starts with one free block, which we initialize now.
firstFreeBlock->sizeAndTags = totalSize | TAG_PRECEDING_USED;
firstFreeBlock->next = NULL;
firstFreeBlock->prev = NULL;
// boundary tag
*((size_t*)POINTER_ADD(firstFreeBlock, totalSize - WORD_SIZE)) = totalSize | TAG_PRECEDING_USED;
// Tag "useless" word at end of heap as used.
// This is the is the heap-footer.
*((size_t*)POINTER_SUB(mem_heap_hi(), WORD_SIZE - 1)) = TAG_USED;
// set the head of the free list to this new free block.
FREE_LIST_HEAD = firstFreeBlock;
return 0;
}
// TOP-LEVEL ALLOCATOR INTERFACE ------------------------------------
/* Allocate a block of size size and return a pointer to it. */
void* mm_malloc (size_t size) {
size_t reqSize;
BlockInfo * ptrFreeBlock = NULL;
BlockInfo * splitBlock;
size_t blockSize;
size_t precedingBlockUseTag;
// Zero-size requests get NULL.
if (size == 0) {
return NULL;
}
// Add one word for the initial size header.
// Note that we don't need to boundary tag when the block is used!
size += WORD_SIZE;
if (size <= MIN_BLOCK_SIZE) {
// Make sure we allocate enough space for a blockInfo in case we
// free this block (when we free this block, we'll need to use the
// next pointer, the prev pointer, and the boundary tag).
reqSize = MIN_BLOCK_SIZE;
} else {
// Round up for correct alignment
reqSize = ALIGNMENT * ((size + ALIGNMENT - 1) / ALIGNMENT);
}
// Implement mm_malloc. You can change or remove any of the above
// code. It is included as a suggestion of where to start.
// You will want to replace this return statement...
// find free block of reqSize
ptrFreeBlock = searchFreeList(reqSize);
while ( ptrFreeBlock == NULL ) {
requestMoreSpace(1 << 14);
ptrFreeBlock = searchFreeList(reqSize);
}
// check free block size vs reqSize vs alignment requirements,
// split if necessary. If split, reformat newly created free
// block (add header, set bits, add footer).
blockSize = SIZE(ptrFreeBlock->sizeAndTags);
if ( blockSize - reqSize >= MIN_BLOCK_SIZE ) {
// Split, set size and tags of new block
splitBlock = (BlockInfo*) POINTER_ADD(ptrFreeBlock, reqSize);
blockSize -= reqSize;
splitBlock->sizeAndTags = blockSize | TAG_PRECEDING_USED;
splitBlock->sizeAndTags &= ~0 << 1; // turn off use bit - preserve others
// set footer equal to header. Current ptr + blockSize - one word = boundary
// tag of current block (word prior to start of next block)
*((size_t*) POINTER_ADD(splitBlock, blockSize- WORD_SIZE))=
splitBlock->sizeAndTags;
insertFreeBlock(splitBlock);
// set size of ptrFreeBlock to exclude size of newBlock
blockSize = reqSize;
} else { // if we didnt split, set the next block's preceding tag to 1
*((size_t*) POINTER_ADD(ptrFreeBlock, SIZE(ptrFreeBlock->sizeAndTags))) |=
TAG_PRECEDING_USED;
}
removeFreeBlock(ptrFreeBlock);
precedingBlockUseTag = ptrFreeBlock->sizeAndTags & TAG_PRECEDING_USED;
// if the preceding block is used as well, set lower two bits. Else, set only
// used bit.
if ( precedingBlockUseTag ) {
ptrFreeBlock->sizeAndTags = blockSize | (TAG_PRECEDING_USED + TAG_USED);
} else {
ptrFreeBlock->sizeAndTags = blockSize | TAG_USED;
}
// return pointer to block (beginning of payload)
// if null, return null. else return 8 after start of block (ie skip header,
// return ptr to payload region)
if ( ptrFreeBlock == NULL) { return NULL; }
else { return (void*) POINTER_ADD(ptrFreeBlock, WORD_SIZE); }
}
/* Free the block referenced by ptr. */
void mm_free (void *ptr) {
size_t payloadSize;
BlockInfo * blockInfo;
BlockInfo * followingBlock;
size_t bitMask;
// Implement mm_free. You can change or remove the declaraions
// above. They are included as minor hints.
// set BlockInfo pointer to include header
blockInfo = (BlockInfo*) POINTER_SUB(ptr, WORD_SIZE);
payloadSize = SIZE(blockInfo->sizeAndTags) - WORD_SIZE;
followingBlock = (BlockInfo*) POINTER_ADD(ptr, payloadSize + WORD_SIZE);
// set header (first tags, then size)
bitMask = ~0 << 1;
blockInfo->sizeAndTags &= bitMask; /* preserves all bits, except sets lowest
to 0 (unsetting used tag) */
// copy header into footer
*((size_t*) POINTER_ADD(blockInfo, payloadSize)) = blockInfo->sizeAndTags;
// set preceding use tag for following block
bitMask = (~0 << 2) | 1;
followingBlock->sizeAndTags &= bitMask; /* preserves all bits except 2nd
lowest bit */
// insert into free list and coalesce
insertFreeBlock(blockInfo);
coalesceFreeBlock(blockInfo);
}
// Implement a heap consistency checker as needed.
int mm_check() {
return 0;
}