Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
c91b4a06cbb6a431a90de95e8007f8fca129ef6c
[simgrid.git] / src / xbt / mmalloc / mmalloc.c
1 /* Memory allocator `malloc'. */
2
3 /* Copyright (c) 2010-2014. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 /* Copyright 1990, 1991, 1992 Free Software Foundation
10
11    Written May 1989 by Mike Haertel.
12    Heavily modified Mar 1992 by Fred Fish for mmap'd version. */
13
14 #include <string.h>             /* Prototypes for memcpy, memmove, memset, etc */
15 #include <stdio.h>
16 #include "mmprivate.h"
17
18 /* Prototypes for local functions */
19
20 static void initialize(xbt_mheap_t mdp);
21 static void *register_morecore(xbt_mheap_t mdp, size_t size);
22 static void *align(xbt_mheap_t mdp, size_t size);
23
24 /* Allocation aligned on block boundary.
25  *
26  * It never returns NULL, but dies verbosely on error.
27  */
28 static void *align(struct mdesc *mdp, size_t size)
29 {
30   void *result;
31   unsigned long int adj;
32
33   result = mmorecore(mdp, size);
34
35   /* if this reservation does not fill up the last block of our resa,
36    * complete the reservation by also asking for the full latest block.
37    *
38    * Also, the returned block is aligned to the end of block (but I've
39    * no fucking idea of why, actually -- http://abstrusegoose.com/432 --
40    * but not doing so seems to lead to issues).
41    */
42   adj = RESIDUAL(result, BLOCKSIZE);
43   if (adj != 0) {
44     adj = BLOCKSIZE - adj;
45     mmorecore(mdp, adj);
46     result = (char *) result + adj;
47   }
48   return (result);
49 }
50
51 /* Finish the initialization of the mheap. If we want to inline it
52  * properly, we need to make the align function publicly visible, too  */
53 static void initialize(xbt_mheap_t mdp)
54 {
55   int i;
56   malloc_info mi; /* to compute the offset of the swag hook */
57
58   mdp->heapsize = HEAP / BLOCKSIZE;
59   mdp->heapinfo = (malloc_info *)
60     align(mdp, mdp->heapsize * sizeof(malloc_info));
61
62   memset((void *) mdp->heapinfo, 0, mdp->heapsize * sizeof(malloc_info));
63   mdp->heapinfo[0].type=-1;
64   mdp->heapinfo[0].free_block.size = 0;
65   mdp->heapinfo[0].free_block.next = mdp->heapinfo[0].free_block.prev = 0;
66   mdp->heapindex = 0;
67   mdp->heapbase = (void *) mdp->heapinfo;
68   mdp->flags |= MMALLOC_INITIALIZED;
69
70   for (i=0;i<BLOCKLOG;i++) {
71       xbt_swag_init(&(mdp->fraghead[i]),
72                     xbt_swag_offset(mi, freehook));
73   }
74 }
75
76 #define update_hook(a,offset) do { if (a) { a = ((char*)a +(offset));} }while(0)
77
78 /* Get neatly aligned memory from the low level layers, and register it
79  * into the heap info table as necessary. */
80 static void *register_morecore(struct mdesc *mdp, size_t size)
81 {
82   int i;
83   void *result;
84   malloc_info *newinfo, *oldinfo;
85   size_t newsize;
86
87   result = align(mdp, size); // Never returns NULL
88
89   /* Check if we need to grow the info table (in a multiplicative manner)  */
90   if ((size_t) BLOCK((char *) result + size) > mdp->heapsize) {
91     int it;
92
93     newsize = mdp->heapsize;
94     while ((size_t) BLOCK((char *) result + size) > newsize)
95       newsize *= 2;
96
97     /* Copy old info into new location */
98     oldinfo = mdp->heapinfo;
99     newinfo = (malloc_info *) align(mdp, newsize * sizeof(malloc_info));
100     memcpy(newinfo, oldinfo, mdp->heapsize * sizeof(malloc_info));
101
102     /* Initialise the new blockinfo : */
103     memset((char*) newinfo + mdp->heapsize * sizeof(malloc_info), 0,
104       (newsize - mdp->heapsize)* sizeof(malloc_info));
105
106     /* Update the swag of busy blocks containing free fragments by applying the offset to all swag_hooks. Yeah. My hand is right in the fan and I still type */
107     size_t offset=((char*)newinfo)-((char*)oldinfo);
108
109     for (i=1/*first element of heapinfo describes the mdesc area*/;
110          i<mdp->heaplimit;
111          i++) {
112       update_hook(newinfo[i].freehook.next,offset);
113       update_hook(newinfo[i].freehook.prev,offset);
114     }
115     // also update the starting points of the swag
116     for (i=0;i<BLOCKLOG;i++) {
117       update_hook(mdp->fraghead[i].head,offset);
118       update_hook(mdp->fraghead[i].tail,offset);
119     }
120     mdp->heapinfo = newinfo;
121
122     /* mark the space previously occupied by the block info as free by first marking it
123      * as occupied in the regular way, and then freing it */
124     for (it=0; it<BLOCKIFY(mdp->heapsize * sizeof(malloc_info)); it++){
125       newinfo[BLOCK(oldinfo)+it].type = 0;
126       newinfo[BLOCK(oldinfo)+it].busy_block.ignore = 0;
127     }
128
129     newinfo[BLOCK(oldinfo)].busy_block.size = BLOCKIFY(mdp->heapsize * sizeof(malloc_info));
130     newinfo[BLOCK(oldinfo)].busy_block.busy_size = size;
131     mfree(mdp, (void *) oldinfo);
132     mdp->heapsize = newsize;
133   }
134
135   mdp->heaplimit = BLOCK((char *) result + size);
136   return (result);
137 }
138 #undef update_hook
139
140 /* Allocate memory from the heap.  */
141 void *mmalloc(xbt_mheap_t mdp, size_t size) {
142   void *res= mmalloc_no_memset(mdp,size);
143   if (mdp->options & XBT_MHEAP_OPTION_MEMSET) {
144     memset(res,0,size);
145   }
146   return res;
147 }
148 /* Spliting mmalloc this way is mandated by a trick in mrealloc, that gives
149    back the memory of big blocks to the system before reallocating them: we don't
150    want to loose the beginning of the area when this happens */
151 void *mmalloc_no_memset(xbt_mheap_t mdp, size_t size)
152 {
153   void *result;
154   size_t block, blocks, lastblocks, start;
155   register size_t i;
156   register size_t log;
157   int it;
158
159   size_t requested_size = size; // The amount of memory requested by user, for real
160
161   /* Work even if the user was stupid enough to ask a ridicullously small block (even 0-length),
162    *    ie return a valid block that can be realloced and freed.
163    * glibc malloc does not use this trick but return a constant pointer, but we need to enlist the free fragments later on.
164    */
165   if (size < SMALLEST_POSSIBLE_MALLOC)
166     size = SMALLEST_POSSIBLE_MALLOC;
167
168   //  printf("(%s) Mallocing %d bytes on %p (default: %p)...",xbt_thread_self_name(),size,mdp,__mmalloc_default_mdp);fflush(stdout);
169
170   if (!(mdp->flags & MMALLOC_INITIALIZED))
171     initialize(mdp);
172
173   mmalloc_paranoia(mdp);
174
175   /* Determine the allocation policy based on the request size.  */
176   if (size <= BLOCKSIZE / 2) {
177     /* Small allocation to receive a fragment of a block.
178        Determine the logarithm to base two of the fragment size. */
179     log = 1;
180     --size;
181     while ((size /= 2) != 0) {
182       ++log;
183     }
184
185     /* Look in the fragment lists for a free fragment of the desired size. */
186     if (xbt_swag_size(&mdp->fraghead[log])>0) {
187       /* There are free fragments of this size; Get one of them and prepare to return it.
188          Update the block's nfree and if no other free fragment, get out of the swag. */
189
190       /* search a fragment that I could return as a result */
191       malloc_info *candidate_info = xbt_swag_getFirst(&mdp->fraghead[log]);
192       size_t candidate_block = (candidate_info - &(mdp->heapinfo[0]));
193       size_t candidate_frag;
194       for (candidate_frag=0;candidate_frag<(size_t) (BLOCKSIZE >> log);candidate_frag++)
195         if (candidate_info->busy_frag.frag_size[candidate_frag] == -1)
196           break;
197       xbt_assert(candidate_frag < (size_t) (BLOCKSIZE >> log),
198           "Block %zu was registered as containing free fragments of type %zu, but I can't find any",candidate_block,log);
199
200       result = (void*) (((char*)ADDRESS(candidate_block)) + (candidate_frag << log));
201
202       /* Remove this fragment from the list of free guys */
203       candidate_info->busy_frag.nfree--;
204       if (candidate_info->busy_frag.nfree == 0) {
205         xbt_swag_remove(candidate_info,&mdp->fraghead[log]);
206       }
207
208       /* Update our metadata about this fragment */
209       candidate_info->busy_frag.frag_size[candidate_frag] = requested_size;
210       candidate_info->busy_frag.ignore[candidate_frag] = 0;
211       //xbt_backtrace_no_malloc(candidate_info->busy_frag.bt[candidate_frag],XBT_BACKTRACE_SIZE);
212       //xbt_libunwind_backtrace(candidate_info->busy_frag.bt[candidate_frag],XBT_BACKTRACE_SIZE);
213
214       /* Update the statistics.  */
215       mdp -> heapstats.chunks_used++;
216       mdp -> heapstats.bytes_used += 1 << log;
217       mdp -> heapstats.chunks_free--;
218       mdp -> heapstats.bytes_free -= 1 << log;
219
220     } else {
221       /* No free fragments of the desired size, so get a new block
222          and break it into fragments, returning the first.  */
223
224       result = mmalloc(mdp, BLOCKSIZE); // does not return NULL
225       block = BLOCK(result);
226
227       mdp->heapinfo[block].type = log;
228       /* Link all fragments but the first as free, and add the block to the swag of blocks containing free frags  */
229       for (i = 1; i < (size_t) (BLOCKSIZE >> log); ++i) {
230         mdp->heapinfo[block].busy_frag.frag_size[i] = -1;
231         mdp->heapinfo[block].busy_frag.ignore[i] = 0;
232       }
233       mdp->heapinfo[block].busy_frag.nfree = i - 1;
234       mdp->heapinfo[block].freehook.prev = NULL;
235       mdp->heapinfo[block].freehook.next = NULL;
236
237       xbt_swag_insert(&mdp->heapinfo[block], &(mdp->fraghead[log]));
238
239       /* mark the fragment returned as busy */
240       mdp->heapinfo[block].busy_frag.frag_size[0] = requested_size;
241       mdp->heapinfo[block].busy_frag.ignore[0] = 0;
242       //xbt_backtrace_no_malloc(mdp->heapinfo[block].busy_frag.bt[0],XBT_BACKTRACE_SIZE);
243       //xbt_libunwind_backtrace(mdp->heapinfo[block].busy_frag.bt[0],XBT_BACKTRACE_SIZE);
244       
245       /* update stats */
246       mdp -> heapstats.chunks_free += (BLOCKSIZE >> log) - 1;
247       mdp -> heapstats.bytes_free += BLOCKSIZE - (1 << log);
248       mdp -> heapstats.bytes_used -= BLOCKSIZE - (1 << log);
249     }
250   } else {
251     /* Large allocation to receive one or more blocks.
252        Search the free list in a circle starting at the last place visited.
253        If we loop completely around without finding a large enough
254        space we will have to get more memory from the system.  */
255     blocks = BLOCKIFY(size);
256     start = block = MALLOC_SEARCH_START;
257     while (mdp->heapinfo[block].free_block.size < blocks) {
258       if (mdp->heapinfo[block].type >=0) { // Don't trust xbt_die and friends in malloc-level library, you fool!
259         fprintf(stderr,"Internal error: found a free block not marked as such (block=%lu type=%lu). Please report this bug.\n",(unsigned long)block,(unsigned long)mdp->heapinfo[block].type);
260         abort();
261       }
262
263       block = mdp->heapinfo[block].free_block.next;
264       if (block == start) {
265         /* Need to get more from the system.  Check to see if
266            the new core will be contiguous with the final free
267            block; if so we don't need to get as much.  */
268         block = mdp->heapinfo[0].free_block.prev;
269         lastblocks = mdp->heapinfo[block].free_block.size;
270         if (mdp->heaplimit != 0 &&
271             block + lastblocks == mdp->heaplimit &&
272             mmorecore(mdp, 0) == ADDRESS(block + lastblocks) &&
273             (register_morecore(mdp, (blocks - lastblocks) * BLOCKSIZE)) != NULL) {
274           /* Which block we are extending (the `final free
275              block' referred to above) might have changed, if
276              it got combined with a freed info table.  */
277           block = mdp->heapinfo[0].free_block.prev;
278
279           mdp->heapinfo[block].free_block.size += (blocks - lastblocks);
280           continue;
281         }
282         result = register_morecore(mdp, blocks * BLOCKSIZE);
283
284         block = BLOCK(result);
285         for (it=0;it<blocks;it++){
286           mdp->heapinfo[block+it].type = 0;
287           mdp->heapinfo[block+it].busy_block.busy_size = 0;
288           mdp->heapinfo[block+it].busy_block.ignore = 0;
289         }
290         mdp->heapinfo[block].busy_block.size = blocks;
291         mdp->heapinfo[block].busy_block.busy_size = requested_size;
292         //mdp->heapinfo[block].busy_block.bt_size=xbt_backtrace_no_malloc(mdp->heapinfo[block].busy_block.bt,XBT_BACKTRACE_SIZE);
293         //mdp->heapinfo[block].busy_block.bt_size = xbt_libunwind_backtrace(mdp->heapinfo[block].busy_block.bt,XBT_BACKTRACE_SIZE);
294         mdp -> heapstats.chunks_used++;
295         mdp -> heapstats.bytes_used += blocks * BLOCKSIZE;
296
297         return result;
298       }
299       /* Need large block(s), but found some in the existing heap */
300     }
301
302     /* At this point we have found a suitable free list entry.
303        Figure out how to remove what we need from the list. */
304     result = ADDRESS(block);
305     if (mdp->heapinfo[block].free_block.size > blocks) {
306       /* The block we found has a bit left over,
307          so relink the tail end back into the free list. */
308       mdp->heapinfo[block + blocks].free_block.size
309         = mdp->heapinfo[block].free_block.size - blocks;
310       mdp->heapinfo[block + blocks].free_block.next
311         = mdp->heapinfo[block].free_block.next;
312       mdp->heapinfo[block + blocks].free_block.prev
313         = mdp->heapinfo[block].free_block.prev;
314       mdp->heapinfo[mdp->heapinfo[block].free_block.prev].free_block.next
315         = mdp->heapinfo[mdp->heapinfo[block].free_block.next].free_block.prev
316         = mdp->heapindex = block + blocks;
317     } else {
318       /* The block exactly matches our requirements,
319          so just remove it from the list. */
320       mdp->heapinfo[mdp->heapinfo[block].free_block.next].free_block.prev
321         = mdp->heapinfo[block].free_block.prev;
322       mdp->heapinfo[mdp->heapinfo[block].free_block.prev].free_block.next
323         = mdp->heapindex = mdp->heapinfo[block].free_block.next;
324     }
325
326     for (it=0;it<blocks;it++){
327       mdp->heapinfo[block+it].type = 0;
328       mdp->heapinfo[block+it].busy_block.busy_size = 0;
329       mdp->heapinfo[block+it].busy_block.ignore = 0;
330     }
331     mdp->heapinfo[block].busy_block.size = blocks;
332     mdp->heapinfo[block].busy_block.busy_size = requested_size; 
333     //mdp->heapinfo[block].busy_block.bt_size = xbt_backtrace_no_malloc(mdp->heapinfo[block].busy_block.bt,XBT_BACKTRACE_SIZE);
334     //mdp->heapinfo[block].busy_block.bt_size = xbt_libunwind_backtrace(mdp->heapinfo[block].busy_block.bt,XBT_BACKTRACE_SIZE);
335     
336     mdp -> heapstats.chunks_used++;
337     mdp -> heapstats.bytes_used += blocks * BLOCKSIZE;
338     mdp -> heapstats.bytes_free -= blocks * BLOCKSIZE;
339
340   }
341   //printf("(%s) Done mallocing. Result is %p\n",xbt_thread_self_name(),result);fflush(stdout);
342
343   return (result);
344 }