Logo AND Algorithmique Numérique Distribuée

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