Logo AND Algorithmique Numérique Distribuée

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