Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'v3_9_x'
[simgrid.git] / src / xbt / mmalloc / mm_module.c
1 /* Initialization for access to a mmap'd malloc managed region.
2    Copyright 1992, 2000 Free Software Foundation, Inc.
3
4    Contributed by Fred Fish at Cygnus Support.   fnf@cygnus.com
5
6    This file is part of the GNU C Library.
7
8    The GNU C Library is free software; you can redistribute it and/or
9    modify it under the terms of the GNU Library General Public License as
10    published by the Free Software Foundation; either version 2 of the
11    License, or (at your option) any later version.
12
13    The GNU C Library is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16    Library General Public License for more details.
17
18    You should have received a copy of the GNU Library General Public
19    License along with the GNU C Library; see the file COPYING.LIB.  If
20    not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21    Boston, MA 02111-1307, USA.  */
22
23 #include <sys/types.h>
24 #include <fcntl.h>              /* After sys/types.h, at least for dpx/2.  */
25 #include <sys/stat.h>
26 #include <string.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>             /* Prototypes for lseek */
29 #endif
30 #include "mmprivate.h"
31 #include "xbt/ex.h"
32 #include "xbt_modinter.h" /* declarations of mmalloc_preinit and friends that live here */
33
34 #ifndef SEEK_SET
35 #define SEEK_SET 0
36 #endif
37
38 /* Initialize access to a mmalloc managed region.
39
40    If FD is a valid file descriptor for an open file then data for the
41    mmalloc managed region is mapped to that file, otherwise an anonymous
42    map is used if supported by the underlying OS. In case of running in
43    an OS without support of anonymous mappings then "/dev/zero" is used 
44    and in both cases the data will not exist in any filesystem object.
45
46    If the open file corresponding to FD is from a previous use of
47    mmalloc and passes some basic sanity checks to ensure that it is
48    compatible with the current mmalloc package, then its data is
49    mapped in and is immediately accessible at the same addresses in
50    the current process as the process that created the file (ignoring
51    the BASEADDR parameter).
52
53    For non valid FDs or empty files ones the mapping is established 
54    starting at the specified address BASEADDR in the process address 
55    space.
56
57    The provided BASEADDR should be choosed carefully in order to avoid
58    bumping into existing mapped regions or future mapped regions.
59
60    On success, returns a "malloc descriptor" which is used in subsequent
61    calls to other mmalloc package functions.  It is explicitly "void *"
62    so that users of the package don't have to worry about the actual
63    implementation details.
64
65    On failure returns NULL. */
66
67 xbt_mheap_t xbt_mheap_new(int fd, void *baseaddr)
68 {
69   struct mdesc mtemp;
70   xbt_mheap_t mdp;
71   void *mbase;
72   struct stat sbuf;
73
74   /* First check to see if FD is a valid file descriptor, and if so, see
75      if the file has any current contents (size > 0).  If it does, then
76      attempt to reuse the file.  If we can't reuse the file, either
77      because it isn't a valid mmalloc produced file, was produced by an
78      obsolete version, or any other reason, then we fail to attach to
79      this file. */
80
81   if (fd >= 0) {
82     if (fstat(fd, &sbuf) < 0)
83       return (NULL);
84
85     else if (sbuf.st_size > 0) {
86       /* We were given an valid file descriptor on an open file, so try to remap
87          it into the current process at the same address to which it was previously
88          mapped. It naturally have to pass some sanity checks for that.
89
90          Note that we have to update the file descriptor number in the malloc-
91          descriptor read from the file to match the current valid one, before
92          trying to map the file in, and again after a successful mapping and
93          after we've switched over to using the mapped in malloc descriptor
94          rather than the temporary one on the stack.
95
96          Once we've switched over to using the mapped in malloc descriptor, we
97          have to update the pointer to the morecore function, since it almost
98          certainly will be at a different address if the process reusing the
99          mapped region is from a different executable.
100
101          Also note that if the heap being remapped previously used the mmcheckf()
102          routines, we need to update the hooks since their target functions
103          will have certainly moved if the executable has changed in any way.
104          We do this by calling mmcheckf() internally.
105
106          Returns a pointer to the malloc descriptor if successful, or NULL if
107          unsuccessful for some reason. */
108
109       struct mdesc newmd;
110       struct mdesc *mdptr = NULL, *mdptemp = NULL;
111
112       if (lseek(fd, 0L, SEEK_SET) != 0)
113         return NULL;
114       if (read(fd, (char *) &newmd, sizeof(newmd)) != sizeof(newmd))
115         return NULL;
116       if (newmd.headersize != sizeof(newmd))
117         return NULL;
118       if (strcmp(newmd.magic, MMALLOC_MAGIC) != 0)
119         return NULL;
120       if (newmd.version > MMALLOC_VERSION)
121         return NULL;
122
123       newmd.fd = fd;
124       if (__mmalloc_remap_core(&newmd) == newmd.base) {
125         mdptr = (struct mdesc *) newmd.base;
126         mdptr->fd = fd;
127         if(!mdptr->refcount){
128           sem_init(&mdptr->sem, 0, 1);
129           mdptr->refcount++;
130         }
131       }
132
133       /* Add the new heap to the linked list of heaps attached by mmalloc */
134       mdptemp = __mmalloc_default_mdp;
135       while(mdptemp->next_mdesc)
136         mdptemp = mdptemp->next_mdesc;
137
138       LOCK(mdptemp);
139       mdptemp->next_mdesc = mdptr;
140       UNLOCK(mdptemp);
141
142       return mdptr;
143     }
144   }
145
146   /* NULL is not a valid baseaddr as we cannot map anything there.
147      C'mon, user. Think! */
148   if (baseaddr == NULL)
149     return (NULL);
150
151   /* We start off with the malloc descriptor allocated on the stack, until
152      we build it up enough to call _mmalloc_mmap_morecore() to allocate the
153      first page of the region and copy it there.  Ensure that it is zero'd and
154      then initialize the fields that we know values for. */
155
156   mdp = &mtemp;
157   memset((char *) mdp, 0, sizeof(mtemp));
158   strncpy(mdp->magic, MMALLOC_MAGIC, MMALLOC_MAGIC_SIZE);
159   mdp->headersize = sizeof(mtemp);
160   mdp->version = MMALLOC_VERSION;
161   mdp->fd = fd;
162   mdp->base = mdp->breakval = mdp->top = baseaddr;
163   mdp->next_mdesc = NULL;
164   mdp->refcount = 1;
165   
166   /* If we have not been passed a valid open file descriptor for the file
167      to map to, then we go for an anonymous map */
168
169   if (mdp->fd < 0){
170     mdp->flags |= MMALLOC_ANONYMOUS;
171   }
172   sem_init(&mdp->sem, 0, 1);
173   
174   /* If we have not been passed a valid open file descriptor for the file
175      to map to, then open /dev/zero and use that to map to. */
176
177   /* Now try to map in the first page, copy the malloc descriptor structure
178      there, and arrange to return a pointer to this new copy.  If the mapping
179      fails, then close the file descriptor if it was opened by us, and arrange
180      to return a NULL. */
181
182   if ((mbase = mmorecore(mdp, sizeof(mtemp))) != NULL) {
183     memcpy(mbase, mdp, sizeof(mtemp));
184   } else {
185     fprintf(stderr, "morecore failed to get some more memory!\n");
186     abort();
187   }
188
189   /* Add the new heap to the linked list of heaps attached by mmalloc */  
190   if(__mmalloc_default_mdp){
191     mdp = __mmalloc_default_mdp;
192     while(mdp->next_mdesc)
193       mdp = mdp->next_mdesc;
194
195     LOCK(mdp);
196     mdp->next_mdesc = (struct mdesc *)mbase;
197     UNLOCK(mdp);
198   }
199
200   return mbase;
201 }
202
203
204
205 /** Terminate access to a mmalloc managed region, but do not free its content.
206  *
207  * This is for example useful for the base region where ldl stores its data
208  *   because it leaves the place after us.
209  */
210 void xbt_mheap_destroy_no_free(xbt_mheap_t md)
211 {
212   struct mdesc *mdp = md;
213
214   if(--mdp->refcount == 0){
215     LOCK(mdp) ;
216     sem_destroy(&mdp->sem);
217   }
218 }
219
220 /** Terminate access to a mmalloc managed region by unmapping all memory pages
221     associated with the region, and closing the file descriptor if it is one
222     that we opened.
223
224     Returns NULL on success.
225
226     Returns the malloc descriptor on failure, which can subsequently be used
227     for further action, such as obtaining more information about the nature of
228     the failure.
229
230     Note that the malloc descriptor that we are using is currently located in
231     region we are about to unmap, so we first make a local copy of it on the
232     stack and use the copy. */
233
234 void *xbt_mheap_destroy(xbt_mheap_t mdp)
235 {
236   struct mdesc mtemp, *mdptemp;
237
238   if (mdp != NULL) {
239     /* Remove the heap from the linked list of heaps attached by mmalloc */
240     mdptemp = __mmalloc_default_mdp;
241     while(mdptemp->next_mdesc != mdp )
242       mdptemp = mdptemp->next_mdesc;
243
244     mdptemp->next_mdesc = mdp->next_mdesc;
245
246     xbt_mheap_destroy_no_free(mdp);
247     mtemp = *mdp;
248
249     /* Now unmap all the pages associated with this region by asking for a
250        negative increment equal to the current size of the region. */
251
252     if (mmorecore(&mtemp, (char *)mtemp.base - (char *)mtemp.breakval) == NULL) {
253       /* Deallocating failed.  Update the original malloc descriptor
254          with any changes */
255       *mdp = mtemp;
256     } else {
257       if (mtemp.flags & MMALLOC_DEVZERO) {
258         close(mtemp.fd);
259       }
260       mdp = NULL;
261     }
262   }
263
264   return (mdp);
265 }
266
267 /* Safety gap from the heap's break address.
268  * Try to increase this first if you experience strange errors under
269  * valgrind. */
270 #define HEAP_OFFSET   (128UL<<20)
271
272 xbt_mheap_t mmalloc_get_default_md(void)
273 {
274   xbt_assert(__mmalloc_default_mdp);
275   return __mmalloc_default_mdp;
276 }
277
278 static void mmalloc_fork_prepare(void)
279 {
280   xbt_mheap_t mdp = NULL;
281   if ((mdp =__mmalloc_default_mdp)){
282     while(mdp){
283       LOCK(mdp);
284       if(mdp->fd >= 0){
285         mdp->refcount++;
286       }
287       mdp = mdp->next_mdesc;
288     }
289   }
290 }
291
292 static void mmalloc_fork_parent(void)
293 {
294   xbt_mheap_t mdp = NULL;
295   if ((mdp =__mmalloc_default_mdp)){
296     while(mdp){
297       if(mdp->fd < 0)
298         UNLOCK(mdp);
299       mdp = mdp->next_mdesc;
300     }
301   }
302 }
303
304 static void mmalloc_fork_child(void)
305 {
306   struct mdesc* mdp = NULL;
307   if ((mdp =__mmalloc_default_mdp)){
308     while(mdp){
309       UNLOCK(mdp);
310       mdp = mdp->next_mdesc;
311     }
312   }
313 }
314
315 /* Initialize the default malloc descriptor. */
316 void *mmalloc_preinit(void)
317 {
318   int res;
319   if (__mmalloc_default_mdp == NULL) {
320     unsigned long mask = ~((unsigned long)getpagesize() - 1);
321     void *addr = (void*)(((unsigned long)sbrk(0) + HEAP_OFFSET) & mask);
322     __mmalloc_default_mdp = xbt_mheap_new(-1, addr);
323     /* Fixme? only the default mdp in protected against forks */
324     // This is mandated to protect the mmalloced areas through forks. Think of tesh.
325     // Nah, removing the mutex isn't a good idea either for tesh
326     res = xbt_os_thread_atfork(mmalloc_fork_prepare,  
327                                mmalloc_fork_parent, mmalloc_fork_child);
328     if (res != 0)
329       THROWF(system_error,0,"xbt_os_thread_atfork() failed: return value %d",res);
330   }
331   xbt_assert(__mmalloc_default_mdp != NULL);
332
333 #if defined(HAVE_GNU_LD) && defined(MMALLOC_WANT_OVERRIDE_LEGACY)
334   mm_gnuld_legacy_init();
335 #endif
336
337   return __mmalloc_default_mdp;
338 }
339
340 void mmalloc_postexit(void)
341 {
342   /* Do not detach the default mdp or ldl won't be able to free the memory it allocated since we're in memory */
343   //  mmalloc_detach(__mmalloc_default_mdp);
344   xbt_mheap_destroy_no_free(__mmalloc_default_mdp);
345 }
346
347 size_t mmalloc_get_bytes_used(xbt_mheap_t heap){
348   int i = 0, j = 0;
349   int bytes = 0;
350   
351   while(i<=((struct mdesc *)heap)->heaplimit){
352     if(((struct mdesc *)heap)->heapinfo[i].type == 0){
353       if(((struct mdesc *)heap)->heapinfo[i].busy_block.busy_size > 0)
354         bytes += ((struct mdesc *)heap)->heapinfo[i].busy_block.busy_size;
355      
356     }else if(((struct mdesc *)heap)->heapinfo[i].type > 0){
357       for(j=0; j < (size_t) (BLOCKSIZE >> ((struct mdesc *)heap)->heapinfo[i].type); j++){
358         if(((struct mdesc *)heap)->heapinfo[i].busy_frag.frag_size[j] > 0)
359           bytes += ((struct mdesc *)heap)->heapinfo[i].busy_frag.frag_size[j];
360       }
361     }
362     i++; 
363   }
364
365   return bytes;
366 }
367