Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
model-checker : new heap comparison algorithm
[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 lastest 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   mdp->heapsize = HEAP / BLOCKSIZE;
55   mdp->heapinfo = (malloc_info *)
56     align(mdp, mdp->heapsize * sizeof(malloc_info));
57
58   memset((void *) mdp->heapinfo, 0, mdp->heapsize * sizeof(malloc_info));
59   mdp->heapinfo[0].type=-1;
60   mdp->heapinfo[0].free_block.size = 0;
61   mdp->heapinfo[0].free_block.next = mdp->heapinfo[0].free_block.prev = 0;
62   mdp->heapindex = 0;
63   mdp->heapbase = (void *) mdp->heapinfo;
64   mdp->flags |= MMALLOC_INITIALIZED;
65 }
66
67 /* Get neatly aligned memory from the low level layers, and register it
68  * into the heap info table as necessary. */
69 static void *register_morecore(struct mdesc *mdp, size_t size)
70 {
71   void *result;
72   malloc_info *newinfo, *oldinfo;
73   size_t newsize;
74
75   result = align(mdp, size); // Never returns NULL
76
77   /* Check if we need to grow the info table (in a multiplicative manner)  */
78   if ((size_t) BLOCK((char *) result + size) > mdp->heapsize) {
79     int it;
80
81     newsize = mdp->heapsize;
82     while ((size_t) BLOCK((char *) result + size) > newsize)
83       newsize *= 2;
84
85     /* Copy old info into new location */
86     oldinfo = mdp->heapinfo;
87     newinfo = (malloc_info *) align(mdp, newsize * sizeof(malloc_info));
88     memset(newinfo, 0, newsize * sizeof(malloc_info));
89     memcpy(newinfo, oldinfo, mdp->heapsize * sizeof(malloc_info));
90     mdp->heapinfo = newinfo;
91
92     /* mark the space previously occupied by the block info as free by first marking it
93      * as occupied in the regular way, and then freing it */
94     for (it=0; it<BLOCKIFY(mdp->heapsize * sizeof(malloc_info)); it++)
95       newinfo[BLOCK(oldinfo)+it].type = 0;
96
97     newinfo[BLOCK(oldinfo)].busy_block.size = BLOCKIFY(mdp->heapsize * sizeof(malloc_info));
98     newinfo[BLOCK(oldinfo)].busy_block.busy_size = size;
99     newinfo[BLOCK(oldinfo)].busy_block.bt_size = 0;// FIXME setup the backtrace
100     mfree(mdp, (void *) oldinfo);
101     mdp->heapsize = newsize;
102   }
103
104   mdp->heaplimit = BLOCK((char *) result + size);
105   return (result);
106 }
107
108 /* Allocate memory from the heap.  */
109
110 void *mmalloc(xbt_mheap_t mdp, size_t size)
111 {
112   void *result;
113   size_t block, blocks, lastblocks, start;
114   register size_t i;
115   struct list *next;
116   register size_t log;
117   int it;
118
119   size_t requested_size = size; // The amount of memory requested by user, for real
120
121   /* Work even if the user was stupid enough to ask a ridicullously small block (even 0-length),
122    *    ie return a valid block that can be realloced and freed.
123    * glibc malloc does not use this trick but return a constant pointer, but we need to enlist the free fragments later on.
124    */
125   if (size < SMALLEST_POSSIBLE_MALLOC)
126     size = SMALLEST_POSSIBLE_MALLOC;
127
128   //  printf("(%s) Mallocing %d bytes on %p (default: %p)...",xbt_thread_self_name(),size,mdp,__mmalloc_default_mdp);fflush(stdout);
129
130   if (!(mdp->flags & MMALLOC_INITIALIZED))
131     initialize(mdp);
132
133   /* Determine the allocation policy based on the request size.  */
134   if (size <= BLOCKSIZE / 2) {
135     /* Small allocation to receive a fragment of a block.
136        Determine the logarithm to base two of the fragment size. */
137     log = 1;
138     --size;
139     while ((size /= 2) != 0) {
140       ++log;
141     }
142
143     /* Look in the fragment lists for a
144        free fragment of the desired size. */
145     next = mdp->fraghead[log].next;
146     if (next != NULL) {
147       /* There are free fragments of this size.
148          Pop a fragment out of the fragment list and return it.
149          Update the block's nfree and first counters. */
150       int frag_nb;
151       result = (void *) next;
152       block = BLOCK(result);
153
154       frag_nb = RESIDUAL(result, BLOCKSIZE) >> log;
155       mdp->heapinfo[block].busy_frag.frag_size[frag_nb] = requested_size;
156       mdp->heapinfo[block].busy_frag.equal_to[frag_nb] = -1;
157       xbt_backtrace_no_malloc(mdp->heapinfo[block].busy_frag.bt[frag_nb],XBT_BACKTRACE_SIZE);
158
159       next->prev->next = next->next;
160       if (next->next != NULL) {
161         next->next->prev = next->prev;
162       }
163       if (--mdp->heapinfo[block].busy_frag.nfree != 0) {
164         mdp->heapinfo[block].busy_frag.first =
165           RESIDUAL(next->next, BLOCKSIZE) >> log;
166       }
167
168       /* Update the statistics.  */
169       mdp -> heapstats.chunks_used++;
170       mdp -> heapstats.bytes_used += 1 << log;
171       mdp -> heapstats.chunks_free--;
172       mdp -> heapstats.bytes_free -= 1 << log;
173
174       memset(result, 0, requested_size);
175       
176     } else {
177       /* No free fragments of the desired size, so get a new block
178          and break it into fragments, returning the first.  */
179       //printf("(%s) No free fragment...",xbt_thread_self_name());
180
181       result = mmalloc(mdp, BLOCKSIZE); // does not return NULL
182       memset(result, 0, requested_size);
183
184       /* Link all fragments but the first into the free list, and mark their requested size to 0.  */
185       block = BLOCK(result);
186       for (i = 1; i < (size_t) (BLOCKSIZE >> log); ++i) {
187         mdp->heapinfo[block].busy_frag.frag_size[i] = 0;
188         mdp->heapinfo[block].busy_frag.equal_to[i] = -1;
189         next = (struct list *) ((char *) result + (i << log));
190         next->next = mdp->fraghead[log].next;
191         next->prev = &mdp->fraghead[log];
192         next->prev->next = next;
193         if (next->next != NULL) {
194           next->next->prev = next;
195         }
196       }
197       mdp->heapinfo[block].busy_frag.frag_size[0] = requested_size;
198       mdp->heapinfo[block].busy_frag.equal_to[0] = -1;
199       xbt_backtrace_no_malloc(mdp->heapinfo[block].busy_frag.bt[0],XBT_BACKTRACE_SIZE);
200       
201       /* Initialize the nfree and first counters for this block.  */
202       mdp->heapinfo[block].type = log;
203       mdp->heapinfo[block].busy_frag.nfree = i - 1;
204       mdp->heapinfo[block].busy_frag.first = i - 1;
205
206       mdp -> heapstats.chunks_free += (BLOCKSIZE >> log) - 1;
207       mdp -> heapstats.bytes_free += BLOCKSIZE - (1 << log);
208       mdp -> heapstats.bytes_used -= BLOCKSIZE - (1 << log);
209     }
210   } else {
211     /* Large allocation to receive one or more blocks.
212        Search the free list in a circle starting at the last place visited.
213        If we loop completely around without finding a large enough
214        space we will have to get more memory from the system.  */
215     blocks = BLOCKIFY(size);
216     start = block = MALLOC_SEARCH_START;
217     while (mdp->heapinfo[block].free_block.size < blocks) {
218       if (mdp->heapinfo[block].type >=0) { // Don't trust xbt_die and friends in malloc-level library, you fool!
219         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);
220         abort();
221       }
222
223       block = mdp->heapinfo[block].free_block.next;
224       if (block == start) {
225         /* Need to get more from the system.  Check to see if
226            the new core will be contiguous with the final free
227            block; if so we don't need to get as much.  */
228         block = mdp->heapinfo[0].free_block.prev;
229         lastblocks = mdp->heapinfo[block].free_block.size;
230         if (mdp->heaplimit != 0 &&
231             block + lastblocks == mdp->heaplimit &&
232             mmorecore(mdp, 0) == ADDRESS(block + lastblocks) &&
233             (register_morecore(mdp, (blocks - lastblocks) * BLOCKSIZE)) != NULL) {
234           /* Which block we are extending (the `final free
235              block' referred to above) might have changed, if
236              it got combined with a freed info table.  */
237           block = mdp->heapinfo[0].free_block.prev;
238
239           mdp->heapinfo[block].free_block.size += (blocks - lastblocks);
240           continue;
241         }
242         result = register_morecore(mdp, blocks * BLOCKSIZE);
243         memset(result, 0, requested_size);
244
245         block = BLOCK(result);
246         for (it=0;it<blocks;it++){
247           mdp->heapinfo[block+it].type = 0;
248           mdp->heapinfo[block+it].busy_block.equal_to = -1;
249         }
250         mdp->heapinfo[block].busy_block.size = blocks;
251         mdp->heapinfo[block].busy_block.busy_size = requested_size;
252         mdp->heapinfo[block].busy_block.bt_size=xbt_backtrace_no_malloc(mdp->heapinfo[block].busy_block.bt,XBT_BACKTRACE_SIZE);
253         mdp -> heapstats.chunks_used++;
254         mdp -> heapstats.bytes_used += blocks * BLOCKSIZE;
255         return result;
256       }
257       /* Need large block(s), but found some in the existing heap */
258     }
259
260     /* At this point we have found a suitable free list entry.
261        Figure out how to remove what we need from the list. */
262     result = ADDRESS(block);
263     if (mdp->heapinfo[block].free_block.size > blocks) {
264       /* The block we found has a bit left over,
265          so relink the tail end back into the free list. */
266       mdp->heapinfo[block + blocks].free_block.size
267         = mdp->heapinfo[block].free_block.size - blocks;
268       mdp->heapinfo[block + blocks].free_block.next
269         = mdp->heapinfo[block].free_block.next;
270       mdp->heapinfo[block + blocks].free_block.prev
271         = mdp->heapinfo[block].free_block.prev;
272       mdp->heapinfo[mdp->heapinfo[block].free_block.prev].free_block.next
273         = mdp->heapinfo[mdp->heapinfo[block].free_block.next].free_block.prev
274         = mdp->heapindex = block + blocks;
275     } else {
276       /* The block exactly matches our requirements,
277          so just remove it from the list. */
278       mdp->heapinfo[mdp->heapinfo[block].free_block.next].free_block.prev
279         = mdp->heapinfo[block].free_block.prev;
280       mdp->heapinfo[mdp->heapinfo[block].free_block.prev].free_block.next
281         = mdp->heapindex = mdp->heapinfo[block].free_block.next;
282     }
283
284     for (it=0;it<blocks;it++){
285       mdp->heapinfo[block+it].type = 0;
286       mdp->heapinfo[block+it].busy_block.equal_to = -1;
287     }
288     mdp->heapinfo[block].busy_block.size = blocks;
289     mdp->heapinfo[block].busy_block.busy_size = requested_size;
290     //mdp->heapinfo[block].busy_block.bt_size = 0;
291     mdp->heapinfo[block].busy_block.bt_size = xbt_backtrace_no_malloc(mdp->heapinfo[block].busy_block.bt,XBT_BACKTRACE_SIZE);
292
293     mdp -> heapstats.chunks_used++;
294     mdp -> heapstats.bytes_used += blocks * BLOCKSIZE;
295     mdp -> heapstats.bytes_free -= blocks * BLOCKSIZE;
296   }
297   //printf("(%s) Done mallocing. Result is %p\n",xbt_thread_self_name(),result);fflush(stdout);
298   return (result);
299 }