Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
57fa34ea57be68b4727f0d7d4dbcea5e81e7569c
[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 int 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 static void *align(struct mdesc *mdp, size_t size)
25 {
26   void *result;
27   unsigned long int adj;
28
29   result = mmorecore(mdp, size);
30
31   /* if this reservation does not fill up the last block of our resa,
32    * complete the reservation by also asking for the full lastest block.
33    *
34    * Also, the returned block is aligned to the end of block (but I've
35    * no fucking idea of why, actually -- http://abstrusegoose.com/432 --
36    * but not doing so seems to lead to issues).
37    */
38   adj = RESIDUAL(result, BLOCKSIZE);
39   if (adj != 0) {
40     adj = BLOCKSIZE - adj;
41     mmorecore(mdp, adj);
42     result = (char *) result + adj;
43   }
44   return (result);
45 }
46
47 /* Finish the initialization of the mheap. If we want to inline it
48  * properly, we need to make the align function publicly visible, too  */
49 static int initialize(xbt_mheap_t mdp)
50 {
51   mdp->heapsize = HEAP / BLOCKSIZE;
52   mdp->heapinfo = (malloc_info *)
53       align(mdp, mdp->heapsize * sizeof(malloc_info));
54   if (mdp->heapinfo == NULL) {
55     return (0);
56   }
57   memset((void *) mdp->heapinfo, 0, mdp->heapsize * sizeof(malloc_info));
58   mdp->heapinfo[0].type=-1;
59   mdp->heapinfo[0].free_block.size = 0;
60   mdp->heapinfo[0].free_block.next = mdp->heapinfo[0].free_block.prev = 0;
61   mdp->heapindex = 0;
62   mdp->heapbase = (void *) mdp->heapinfo;
63   mdp->flags |= MMALLOC_INITIALIZED;
64   return (1);
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);
76   if (result == NULL) {
77     return (NULL);
78   }
79
80   /* Check if we need to grow the info table (in a multiplicative manner)  */
81   if ((size_t) BLOCK((char *) result + size) > mdp->heapsize) {
82         int it;
83
84     newsize = mdp->heapsize;
85     while ((size_t) BLOCK((char *) result + size) > newsize)
86       newsize *= 2;
87
88     /* Copy old info into new location */
89     oldinfo = mdp->heapinfo;
90     newinfo = (malloc_info *) align(mdp, newsize * sizeof(malloc_info));
91     memset(newinfo, 0, newsize * sizeof(malloc_info));
92     memcpy(newinfo, oldinfo, mdp->heapsize * sizeof(malloc_info));
93     mdp->heapinfo = newinfo;
94
95     /* mark the space previously occupied by the block info as free by first marking it
96      * as occupied in the regular way, and then freing it */
97     for (it=0; it<BLOCKIFY(mdp->heapsize * sizeof(malloc_info)); it++)
98         newinfo[BLOCK(oldinfo)+it].type = 0;
99
100     newinfo[BLOCK(oldinfo)].busy_block.size = BLOCKIFY(mdp->heapsize * sizeof(malloc_info));
101     newinfo[BLOCK(oldinfo)].busy_block.busy_size = size;
102     mfree(mdp, (void *) oldinfo);
103     mdp->heapsize = newsize;
104   }
105
106   mdp->heaplimit = BLOCK((char *) result + size);
107   return (result);
108 }
109
110 /* Allocate memory from the heap.  */
111
112 void *mmalloc(xbt_mheap_t mdp, size_t size)
113 {
114   void *result;
115   size_t block, blocks, lastblocks, start;
116   register size_t i;
117   struct list *next;
118   register size_t log;
119   int it;
120
121   /* Work even if the user was stupid enough to ask a 0-byte block, ie return a valid block that can be realloced or freed
122    * glibc malloc does not use this trick but return a constant pointer, but my hack is quicker to implement ;)
123    */
124   if (size == 0)
125     size = 1;
126
127 //  printf("(%s) Mallocing %d bytes on %p (default: %p)...",xbt_thread_self_name(),size,mdp,__mmalloc_default_mdp);fflush(stdout);
128
129   if (!(mdp->flags & MMALLOC_INITIALIZED)) {
130     if (!initialize(mdp)) {
131       return (NULL);
132     }
133   }
134
135   if (size < sizeof(struct list)) {
136     size = sizeof(struct list);
137   }
138
139   /* Determine the allocation policy based on the request size.  */
140   if (size <= BLOCKSIZE / 2) {
141     /* Small allocation to receive a fragment of a block.
142        Determine the logarithm to base two of the fragment size. */
143     log = 1;
144     --size;
145     while ((size /= 2) != 0) {
146       ++log;
147     }
148
149     /* Look in the fragment lists for a
150        free fragment of the desired size. */
151     next = mdp->fraghead[log].next;
152     if (next != NULL) {
153       /* There are free fragments of this size.
154          Pop a fragment out of the fragment list and return it.
155          Update the block's nfree and first counters. */
156       result = (void *) next;
157       next->prev->next = next->next;
158       if (next->next != NULL) {
159         next->next->prev = next->prev;
160       }
161       block = BLOCK(result);
162       if (--mdp->heapinfo[block].busy_frag.nfree != 0) {
163         mdp->heapinfo[block].busy_frag.first =
164             RESIDUAL(next->next, BLOCKSIZE) >> log;
165       }
166
167     } else {
168       /* No free fragments of the desired size, so get a new block
169          and break it into fragments, returning the first.  */
170       //printf("(%s) No free fragment...",xbt_thread_self_name());
171       result = mmalloc(mdp, BLOCKSIZE);
172       //printf("(%s) Fragment: %p...",xbt_thread_self_name(),result);
173       if (result == NULL) {
174         return (NULL);
175       }
176
177       /* Link all fragments but the first into the free list.  */
178       for (i = 1; i < (size_t) (BLOCKSIZE >> log); ++i) {
179         next = (struct list *) ((char *) result + (i << log));
180         next->next = mdp->fraghead[log].next;
181         next->prev = &mdp->fraghead[log];
182         next->prev->next = next;
183         if (next->next != NULL) {
184           next->next->prev = next;
185         }
186       }
187
188       /* Initialize the nfree and first counters for this block.  */
189       block = BLOCK(result);
190       mdp->heapinfo[block].type = log;
191       mdp->heapinfo[block].busy_frag.nfree = i - 1;
192       mdp->heapinfo[block].busy_frag.first = i - 1;
193     }
194   } else {
195     /* Large allocation to receive one or more blocks.
196        Search the free list in a circle starting at the last place visited.
197        If we loop completely around without finding a large enough
198        space we will have to get more memory from the system.  */
199     blocks = BLOCKIFY(size);
200     start = block = MALLOC_SEARCH_START;
201     while (mdp->heapinfo[block].free_block.size < blocks) {
202         if (mdp->heapinfo[block].type >=0) {
203                 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);
204                 abort();
205         }
206
207       block = mdp->heapinfo[block].free_block.next;
208       if (block == start) {
209         /* Need to get more from the system.  Check to see if
210            the new core will be contiguous with the final free
211            block; if so we don't need to get as much.  */
212         block = mdp->heapinfo[0].free_block.prev;
213         lastblocks = mdp->heapinfo[block].free_block.size;
214         if (mdp->heaplimit != 0 &&
215             block + lastblocks == mdp->heaplimit &&
216             mmorecore(mdp, 0) == ADDRESS(block + lastblocks) &&
217             (register_morecore(mdp, (blocks - lastblocks) * BLOCKSIZE)) != NULL) {
218           /* Which block we are extending (the `final free
219              block' referred to above) might have changed, if
220              it got combined with a freed info table.  */
221           block = mdp->heapinfo[0].free_block.prev;
222
223           mdp->heapinfo[block].free_block.size += (blocks - lastblocks);
224           continue;
225         }
226         result = register_morecore(mdp, blocks * BLOCKSIZE);
227         if (result == NULL) {
228           return (NULL);
229         }
230         block = BLOCK(result);
231         for (it=0;it<blocks;it++)
232                 mdp->heapinfo[block+it].type = 0;
233         mdp->heapinfo[block].busy_block.size = blocks;
234         mdp->heapinfo[block].busy_block.busy_size = size;
235         return (result);
236       }
237     }
238
239     /* At this point we have found a suitable free list entry.
240        Figure out how to remove what we need from the list. */
241     result = ADDRESS(block);
242     if (mdp->heapinfo[block].free_block.size > blocks) {
243       /* The block we found has a bit left over,
244          so relink the tail end back into the free list. */
245       mdp->heapinfo[block + blocks].free_block.size
246           = mdp->heapinfo[block].free_block.size - blocks;
247       mdp->heapinfo[block + blocks].free_block.next
248           = mdp->heapinfo[block].free_block.next;
249       mdp->heapinfo[block + blocks].free_block.prev
250           = mdp->heapinfo[block].free_block.prev;
251       mdp->heapinfo[mdp->heapinfo[block].free_block.prev].free_block.next
252           = mdp->heapinfo[mdp->heapinfo[block].free_block.next].free_block.prev
253           = mdp->heapindex = block + blocks;
254     } else {
255       /* The block exactly matches our requirements,
256          so just remove it from the list. */
257       mdp->heapinfo[mdp->heapinfo[block].free_block.next].free_block.prev
258           = mdp->heapinfo[block].free_block.prev;
259       mdp->heapinfo[mdp->heapinfo[block].free_block.prev].free_block.next
260           = mdp->heapindex = mdp->heapinfo[block].free_block.next;
261     }
262
263     for (it=0;it<blocks;it++)
264         mdp->heapinfo[block+it].type = 0;
265     mdp->heapinfo[block].busy_block.size = blocks;
266     mdp->heapinfo[block].busy_block.busy_size = size;
267   }
268   //printf("(%s) Done mallocing. Result is %p\n",xbt_thread_self_name(),result);fflush(stdout);
269   return (result);
270 }