Merge release-5-0 into master
[alexxy/gromacs.git] / src / gromacs / utility / smalloc.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #include "gmxpre.h"
38
39 #include "gromacs/utility/smalloc.h"
40
41 #include "config.h"
42
43 #include <errno.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47
48 #ifdef WITH_DMALLOC
49 #include <dmalloc.h>
50 #endif
51
52 #include "thread_mpi/threads.h"
53
54 #include "gromacs/utility/fatalerror.h"
55 #ifdef PRINT_ALLOC_KB
56 #include "gromacs/utility/basenetwork.h"
57 #include "gromacs/utility/gmxmpi.h"
58 #endif
59
60 static gmx_bool            g_bOverAllocDD     = FALSE;
61 static tMPI_Thread_mutex_t g_over_alloc_mutex = TMPI_THREAD_MUTEX_INITIALIZER;
62
63 #ifdef DEBUG
64 static void log_action(int bMal, const char *what, const char *file, int line,
65                        int nelem, int size, void *ptr)
66 {
67     static int btot = 0;
68     char      *NN   = "NULL";
69     int        bytes;
70
71     bytes = size*nelem;
72     if (!bMal)
73     {
74         bytes = -bytes;
75     }
76
77     tMPI_Thread_mutex_lock(&gmx_logfile_mtx);
78
79     /* This total memory count is not correct, since with realloc
80      * it adds the whole size again, not just the increment.
81      */
82     /* This static variable is protected by the mutex too... */
83     btot += bytes;
84
85     bytes /= 1024;
86     if (debug && (bytes != 0))
87     {
88         fprintf(debug, "%s:%d kB (%7d kB) [%s, line %d, nelem %d, size %d]\n",
89                 what ? what : NN, bytes, btot/1024,
90                 file ? file : NN, line, nelem, size);
91     }
92     /* Print to stderr for things larger than 1 MB */
93     if (bytes >= 1024 || bytes <= -1024)
94     {
95         char *fname = NULL;
96         if (file)
97         {
98             fname = strrchr(file, DIR_SEPARATOR);
99             if (fname)
100             {
101                 fname++;
102             }
103             else
104             {
105                 fname = file;
106             }
107         }
108         printf("%s: %.1f MB [%s, line %d, nelem %d, size %d]\n",
109                what ? what  : NN, bytes/1024.0,
110                file ? fname : NN, line, nelem, size);
111     }
112     tMPI_Thread_mutex_unlock(&gmx_logfile_mtx);
113 }
114 #endif
115
116 void *save_malloc(const char *name, const char *file, int line, size_t size)
117 {
118     void *p;
119
120     p = NULL;
121     if (size == 0)
122     {
123         p = NULL;
124     }
125     else
126     {
127         if ((p = malloc(size)) == NULL)
128         {
129             gmx_fatal(errno, __FILE__, __LINE__,
130                       "Not enough memory. Failed to malloc %"GMX_PRId64 " bytes for %s\n"
131                       "(called from file %s, line %d)",
132                       (gmx_int64_t)size, name, file, line);
133         }
134         (void) memset(p, 0, size);
135     }
136 #ifdef DEBUG
137     log_action(1, name, file, line, 1, size, p);
138 #endif
139     return p;
140 }
141
142 void *save_calloc(const char *name, const char *file, int line,
143                   size_t nelem, size_t elsize)
144 {
145     void *p;
146
147     p = NULL;
148     if ((nelem == 0) || (elsize == 0))
149     {
150         p = NULL;
151     }
152     else
153     {
154 #ifdef PRINT_ALLOC_KB
155         if (nelem*elsize >= PRINT_ALLOC_KB*1024)
156         {
157             int rank = gmx_node_rank();
158             printf("Allocating %.1f MB for %s (called from file %s, line %d on %d)\n",
159                    nelem*elsize/1048576.0, name, file, line, rank);
160         }
161 #endif
162 #ifdef GMX_BROKEN_CALLOC
163         /* emulate calloc(3) with malloc/memset on machines with
164            a broken calloc, e.g. in -lgmalloc on cray xt3. */
165         if ((p = malloc((size_t)nelem*(size_t)elsize)) == NULL)
166         {
167             gmx_fatal(errno, __FILE__, __LINE__,
168                       "Not enough memory. Failed to calloc %"GMX_PRId64
169                       " elements of size %"GMX_PRId64
170                       " for %s\n(called from file %s, line %d)",
171                       (gmx_int64_t)nelem, (gmx_int64_t)elsize,
172                       name, file, line);
173         }
174         memset(p, 0, (size_t) (nelem * elsize));
175 #else
176         if ((p = calloc((size_t)nelem, (size_t)elsize)) == NULL)
177         {
178             gmx_fatal(errno, __FILE__, __LINE__,
179                       "Not enough memory. Failed to calloc %"GMX_PRId64
180                       " elements of size %"GMX_PRId64
181                       " for %s\n(called from file %s, line %d)",
182                       (gmx_int64_t)nelem, (gmx_int64_t)elsize, name, file, line);
183         }
184 #endif
185     }
186 #ifdef DEBUG
187     log_action(1, name, file, line, nelem, elsize, p);
188 #endif
189     return p;
190 }
191
192 void *save_realloc(const char *name, const char *file, int line, void *ptr,
193                    size_t nelem, size_t elsize)
194 {
195     void  *p;
196     size_t size = nelem*elsize;
197
198     p = NULL;
199     if (size == 0)
200     {
201         save_free(name, file, line, ptr);
202     }
203     else
204     {
205 #ifdef PRINT_ALLOC_KB
206         if (size >= PRINT_ALLOC_KB*1024)
207         {
208             int rank = gmx_node_rank();
209             printf("Reallocating %.1f MB for %s (called from file %s, line %d on %d)\n",
210                    size/1048576.0, name, file, line, rank);
211         }
212 #endif
213         if (ptr == NULL)
214         {
215             p = malloc((size_t)size);
216         }
217         else
218         {
219             p = realloc(ptr, (size_t)size);
220         }
221         if (p == NULL)
222         {
223             gmx_fatal(errno, __FILE__, __LINE__,
224                       "Not enough memory. Failed to realloc %"GMX_PRId64 " bytes for %s, %s=%x\n"
225                       "(called from file %s, line %d)",
226                       (gmx_int64_t)size, name, name, ptr, file, line);
227         }
228 #ifdef DEBUG
229         log_action(1, name, file, line, 1, size, p);
230 #endif
231     }
232     return p;
233 }
234
235 void save_free(const char gmx_unused *name, const char gmx_unused *file, int gmx_unused line, void *ptr)
236 {
237 #ifdef DEBUG
238     log_action(0, name, file, line, 0, 0, ptr);
239 #endif
240     if (ptr != NULL)
241     {
242         free(ptr);
243     }
244 }
245
246 /* If we don't have useful routines for allocating aligned memory,
247  * then we have to use the old-style GROMACS approach bitwise-ANDing
248  * pointers to ensure alignment. We store the pointer to the originally
249  * allocated region in the space before the returned pointer */
250
251 /* we create a positive define for the absence of an system-provided memalign */
252 #if (!defined HAVE_POSIX_MEMALIGN && !defined HAVE_MEMALIGN && \
253      !defined HAVE__ALIGNED_MALLOC)
254 #define GMX_OWN_MEMALIGN
255 #endif
256
257
258 /* Pointers allocated with this routine should only be freed
259  * with save_free_aligned, however this will only matter
260  * on systems that lack posix_memalign() and memalign() when
261  * freeing memory that needed to be adjusted to achieve
262  * the necessary alignment. */
263 void *save_malloc_aligned(const char *name, const char *file, int line,
264                           size_t nelem, size_t elsize, size_t alignment)
265 {
266     void   **aligned  = NULL;
267     void    *malloced = NULL;
268     gmx_bool allocate_fail;
269
270     if (alignment == 0)
271     {
272         gmx_fatal(errno, __FILE__, __LINE__,
273                   "Cannot allocate aligned memory with alignment of zero!\n(called from file %s, line %d)", file, line);
274     }
275
276
277     if (nelem == 0 || elsize == 0)
278     {
279         aligned  = NULL;
280     }
281     else
282     {
283 #ifdef PRINT_ALLOC_KB
284         if (nelem*elsize >= PRINT_ALLOC_KB*1024)
285         {
286             int rank = gmx_node_rank();
287             printf("Allocating %.1f MB for %s (called from file %s, line %d on %d)\n",
288                    nelem*elsize/1048576.0, name, file, line, rank);
289         }
290 #endif
291
292 #ifdef HAVE_POSIX_MEMALIGN
293         allocate_fail = (0 != posix_memalign(&malloced, alignment, nelem*elsize));
294 #elif defined HAVE_MEMALIGN
295         allocate_fail = ((malloced = memalign(alignment, nelem*elsize)) == NULL);
296 #elif defined HAVE__ALIGNED_MALLOC
297         allocate_fail = ((malloced = _aligned_malloc(nelem*elsize, alignment))
298                          == NULL);
299 #else
300         allocate_fail = ((malloced = malloc(nelem*elsize+alignment+
301                                             sizeof(void*))) == NULL);
302 #endif
303         if (allocate_fail)
304         {
305             gmx_fatal(errno, __FILE__, __LINE__,
306                       "Not enough memory. Failed to allocate %u aligned elements of size %u for %s\n(called from file %s, line %d)", nelem, elsize, name, file, line);
307         }
308         /* we start with the original pointer */
309         aligned = (void**)malloced;
310
311 #ifdef GMX_OWN_MEMALIGN
312         /* Make the aligned pointer, and save the underlying pointer that
313          * we're allowed to free(). */
314
315         /* we first make space to store that underlying pointer: */
316         aligned = aligned + 1;
317         /* then we apply a bit mask */
318         aligned = (void *) (((size_t) aligned + alignment - 1) &
319                             (~((size_t) (alignment-1))));
320         /* and we store the original pointer in the area just before the
321            pointer we're going to return */
322         aligned[-1] = malloced;
323 #endif
324     }
325     return (void*)aligned;
326 }
327
328 void *save_calloc_aligned(const char *name, const char *file, int line,
329                           size_t nelem, size_t elsize, size_t alignment)
330 {
331     void *aligned = save_malloc_aligned(name, file, line, nelem, elsize, alignment);
332     if (aligned != NULL)
333     {
334         memset(aligned, 0, (size_t)(nelem * elsize));
335     }
336     return aligned;
337 }
338
339 /* This routine can NOT be called with any pointer */
340 void save_free_aligned(const char *name, const char *file, int line, void *ptr)
341 {
342     int   i, j;
343     void *free = ptr;
344
345     if (NULL != ptr)
346     {
347 #ifdef GMX_OWN_MEMALIGN
348         /* we get the pointer from just before the memaligned pointer */
349         free = ((void**)ptr)[-1];
350 #endif
351
352 #ifndef HAVE__ALIGNED_MALLOC
353         /* (Now) we're allowed to use a normal free() on this pointer. */
354         save_free(name, file, line, free);
355 #else
356         _aligned_free(free);
357 #endif
358     }
359 }
360
361 void set_over_alloc_dd(gmx_bool set)
362 {
363     tMPI_Thread_mutex_lock(&g_over_alloc_mutex);
364     /* we just make sure that we don't set this at the same time.
365        We don't worry too much about reading this rarely-set variable */
366     g_bOverAllocDD = set;
367     tMPI_Thread_mutex_unlock(&g_over_alloc_mutex);
368 }
369
370 int over_alloc_dd(int n)
371 {
372     if (g_bOverAllocDD)
373     {
374         return OVER_ALLOC_FAC*n + 100;
375     }
376     else
377     {
378         return n;
379     }
380 }