Move thread_mpi to src/external/
[alexxy/gromacs.git] / src / gromacs / gmxlib / 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 #ifdef HAVE_CONFIG_H
38 #include <config.h>
39 #endif
40
41 /* This file is completely threadsafe - keep it that way! */
42
43 #include "gromacs/utility/gmxmpi.h"
44
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include "gmx_fatal.h"
49 #include "smalloc.h"
50 #include "main.h"
51 #ifdef WITH_DMALLOC
52 #include <dmalloc.h>
53 #endif
54
55 #ifdef DEBUG
56 #include "thread_mpi/threads.h"
57
58 static void log_action(int bMal, const char *what, const char *file, int line,
59                        int nelem, int size, void *ptr)
60 {
61     static int btot = 0;
62     char      *NN   = "NULL";
63     int        bytes;
64
65     bytes = size*nelem;
66     if (!bMal)
67     {
68         bytes = -bytes;
69     }
70
71     tMPI_Thread_mutex_lock(&gmx_logfile_mtx);
72
73     /* This total memory count is not correct, since with realloc
74      * it adds the whole size again, not just the increment.
75      */
76     /* This static variable is protected by the mutex too... */
77     btot += bytes;
78
79     bytes /= 1024;
80     if (debug && (bytes != 0))
81     {
82         fprintf(debug, "%s:%d kB (%7d kB) [%s, line %d, nelem %d, size %d]\n",
83                 what ? what : NN, bytes, btot/1024,
84                 file ? file : NN, line, nelem, size);
85     }
86     /* Print to stderr for things larger than 1 MB */
87     if (bytes >= 1024 || bytes <= -1024)
88     {
89         char *fname = NULL;
90         if (file)
91         {
92             fname = strrchr(file, DIR_SEPARATOR);
93             if (fname)
94             {
95                 fname++;
96             }
97             else
98             {
99                 fname = file;
100             }
101         }
102         printf("%s: %.1f MB [%s, line %d, nelem %d, size %d]\n",
103                what ? what  : NN, bytes/1024.0,
104                file ? fname : NN, line, nelem, size);
105     }
106     tMPI_Thread_mutex_unlock(&gmx_logfile_mtx);
107 }
108 #endif
109
110 void *save_malloc(const char *name, const char *file, int line, size_t size)
111 {
112     void *p;
113
114     p = NULL;
115     if (size == 0)
116     {
117         p = NULL;
118     }
119     else
120     {
121         if ((p = malloc(size)) == NULL)
122         {
123             gmx_fatal(errno, __FILE__, __LINE__,
124                       "Not enough memory. Failed to malloc %"GMX_PRId64 " bytes for %s\n"
125                       "(called from file %s, line %d)",
126                       (gmx_int64_t)size, name, file, line);
127         }
128         (void) memset(p, 0, size);
129     }
130 #ifdef DEBUG
131     log_action(1, name, file, line, 1, size, p);
132 #endif
133     return p;
134 }
135
136 void *save_calloc(const char *name, const char *file, int line,
137                   size_t nelem, size_t elsize)
138 {
139     void *p;
140
141     p = NULL;
142     if ((nelem == 0) || (elsize == 0))
143     {
144         p = NULL;
145     }
146     else
147     {
148 #ifdef PRINT_ALLOC_KB
149         int rank = 0;
150         if (nelem*elsize >= PRINT_ALLOC_KB*1024)
151         {
152 #ifdef GMX_MPI
153             MPI_Comm_rank(MPI_COMM_WORLD, &rank);
154 #endif
155             printf("Allocating %.1f MB for %s (called from file %s, line %d on %d)\n",
156                    nelem*elsize/1048576.0, name, file, line, rank);
157         }
158 #endif
159 #ifdef GMX_BROKEN_CALLOC
160         /* emulate calloc(3) with malloc/memset on machines with
161            a broken calloc, e.g. in -lgmalloc on cray xt3. */
162         if ((p = malloc((size_t)nelem*(size_t)elsize)) == NULL)
163         {
164             gmx_fatal(errno, __FILE__, __LINE__,
165                       "Not enough memory. Failed to calloc %"GMX_PRId64
166                       " elements of size %"GMX_PRId64
167                       " for %s\n(called from file %s, line %d)",
168                       (gmx_int64_t)nelem, (gmx_int64_t)elsize,
169                       name, file, line);
170         }
171         memset(p, 0, (size_t) (nelem * elsize));
172 #else
173         if ((p = calloc((size_t)nelem, (size_t)elsize)) == NULL)
174         {
175             gmx_fatal(errno, __FILE__, __LINE__,
176                       "Not enough memory. Failed to calloc %"GMX_PRId64
177                       " elements of size %"GMX_PRId64
178                       " for %s\n(called from file %s, line %d)",
179                       (gmx_int64_t)nelem, (gmx_int64_t)elsize, name, file, line);
180         }
181 #endif
182     }
183 #ifdef DEBUG
184     log_action(1, name, file, line, nelem, elsize, p);
185 #endif
186     return p;
187 }
188
189 void *save_realloc(const char *name, const char *file, int line, void *ptr,
190                    size_t nelem, size_t elsize)
191 {
192     void  *p;
193     size_t size = nelem*elsize;
194
195     p = NULL;
196     if (size == 0)
197     {
198         save_free(name, file, line, ptr);
199     }
200     else
201     {
202 #ifdef PRINT_ALLOC_KB
203         int rank = 0;
204         if (size >= PRINT_ALLOC_KB*1024)
205         {
206 #ifdef GMX_MPI
207             MPI_Comm_rank(MPI_COMM_WORLD, &rank);
208 #endif
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 size_t maxavail(void)
247 {
248     char  *ptr;
249     size_t low, high, size;
250
251     low  = 0;
252     high = 256e6;
253     while ((high-low) > 4)
254     {
255         size = (high+low)/2;
256         if ((ptr = (char *)malloc((size_t)size)) == NULL)
257         {
258             high = size;
259         }
260         else
261         {
262             free(ptr);
263             low = size;
264         }
265     }
266     return low;
267 }
268
269 size_t memavail(void)
270 {
271     char  *ptr;
272     size_t size;
273
274     size = maxavail();
275     if (size != 0)
276     {
277         if ((ptr = (char *)malloc((size_t)size)) != NULL)
278         {
279             size += memavail();
280             free(ptr);
281         }
282     }
283     return size;
284 }
285
286 /* If we don't have useful routines for allocating aligned memory,
287  * then we have to use the old-style GROMACS approach bitwise-ANDing
288  * pointers to ensure alignment. We store the pointer to the originally
289  * allocated region in the space before the returned pointer */
290
291 /* we create a positive define for the absence of an system-provided memalign */
292 #if (!defined HAVE_POSIX_MEMALIGN && !defined HAVE_MEMALIGN && \
293      !defined HAVE__ALIGNED_MALLOC)
294 #define GMX_OWN_MEMALIGN
295 #endif
296
297
298 /* Pointers allocated with this routine should only be freed
299  * with save_free_aligned, however this will only matter
300  * on systems that lack posix_memalign() and memalign() when
301  * freeing memory that needed to be adjusted to achieve
302  * the necessary alignment. */
303 void *save_malloc_aligned(const char *name, const char *file, int line,
304                           unsigned nelem, size_t elsize, size_t alignment)
305 {
306     void   **aligned  = NULL;
307     void    *malloced = NULL;
308     gmx_bool allocate_fail;
309
310     if (alignment == 0)
311     {
312         gmx_fatal(errno, __FILE__, __LINE__,
313                   "Cannot allocate aligned memory with alignment of zero!\n(called from file %s, line %d)", file, line);
314     }
315
316
317     if (nelem == 0 || elsize == 0)
318     {
319         aligned  = NULL;
320     }
321     else
322     {
323 #ifdef PRINT_ALLOC_KB
324         if (nelem*elsize >= PRINT_ALLOC_KB*1024)
325         {
326             printf("Allocating %.1f MB for %s\n",
327                    nelem*elsize/(PRINT_ALLOC_KB*1024.0), name);
328         }
329 #endif
330
331         allocate_fail = FALSE; /* stop compiler warnings */
332 #ifdef HAVE_POSIX_MEMALIGN
333         allocate_fail = (0 != posix_memalign(&malloced, alignment, nelem*elsize));
334 #elif defined HAVE_MEMALIGN
335         allocate_fail = ((malloced = memalign(alignment, nelem*elsize)) == NULL);
336 #elif defined HAVE__ALIGNED_MALLOC
337         allocate_fail = ((malloced = _aligned_malloc(nelem*elsize, alignment))
338                          == NULL);
339 #else
340         allocate_fail = ((malloced = malloc(nelem*elsize+alignment+
341                                             sizeof(void*))) == NULL);
342 #endif
343         if (allocate_fail)
344         {
345             gmx_fatal(errno, __FILE__, __LINE__,
346                       "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);
347         }
348         /* we start with the original pointer */
349         aligned = (void**)malloced;
350
351 #ifdef GMX_OWN_MEMALIGN
352         /* Make the aligned pointer, and save the underlying pointer that
353          * we're allowed to free(). */
354
355         /* we first make space to store that underlying pointer: */
356         aligned = aligned + 1;
357         /* then we apply a bit mask */
358         aligned = (void *) (((size_t) aligned + alignment - 1) &
359                             (~((size_t) (alignment-1))));
360         /* and we store the original pointer in the area just before the
361            pointer we're going to return */
362         aligned[-1] = malloced;
363 #endif
364     }
365     return (void*)aligned;
366 }
367
368 void *save_calloc_aligned(const char *name, const char *file, int line,
369                           unsigned nelem, size_t elsize, size_t alignment)
370 {
371     void *aligned = save_malloc_aligned(name, file, line, nelem, elsize, alignment);
372     if (aligned != NULL)
373     {
374         memset(aligned, 0, (size_t)(nelem * elsize));
375     }
376     return aligned;
377 }
378
379 /* This routine can NOT be called with any pointer */
380 void save_free_aligned(const char *name, const char *file, int line, void *ptr)
381 {
382     int   i, j;
383     void *free = ptr;
384
385     if (NULL != ptr)
386     {
387 #ifdef GMX_OWN_MEMALIGN
388         /* we get the pointer from just before the memaligned pointer */
389         free = ((void**)ptr)[-1];
390 #endif
391
392 #ifndef HAVE__ALIGNED_MALLOC
393         /* (Now) we're allowed to use a normal free() on this pointer. */
394         save_free(name, file, line, free);
395 #else
396         _aligned_free(free);
397 #endif
398     }
399 }