Debian Codegraph @

hmmer/easel/esl_alloc.c

raw symbols SCIP
1 /* Portable aligned memory allocation.
2 *
3 * See esl_alloc.md for notes.
4 *
5 * Contents:
6 * 1. Portable(-ish) fallback implementation of aligned allocation.
7 * 2. esl_alloc_aligned(), esl_alloc_free() API calls
8 * 3. Benchmark driver
9 * 4. Unit tests
10 * 5. Test driver
11 */
12 #include <esl_config.h>
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <stdint.h>
17
18 #include "easel.h"
19
20 /*****************************************************************
21 * 1. Portable(-ish) fallback implementation of aligned allocation
22 *****************************************************************/
23 #if defined(eslALLOC_TESTDRIVE) || defined (eslALLOC_BENCHMARK) || \
24 (! defined(HAVE_POSIX_MEMALIGN) && ! defined(HAVE_ALIGNED_ALLOC) && ! defined(HAVE__MM_MALLOC))
25 /* Only compile this section if we need it, or for the unit test driver. */
26
27 /* alloc_aligned_fallback()
28 *
29 * Allocate for <size> bytes, and return a pointer to that allocation
30 * that is aligned on a <alignment>-byte boundary. <alignment> must be
31 * at least 1, no more than 256, and a power of two. (So valid values
32 * are 1, 2, 4, 8, 16, 32, 64, 128, 256.) This pointer must be free'd
33 * by alloc_aligned_free_fallback().
34 *
35 * <size> is >= 0. 0 is ok here; because <alignment> is >= 1, we never
36 * malloc() for 0 size.
37 */
38 static void *
39 alloc_aligned_fallback(size_t size, size_t alignment)
40 {
41 void *pp;
42 uint8_t *p;
43 int r;
44
45 ESL_DASSERT1(( size >= 0 ));
46 ESL_DASSERT1(( alignment > 0 && alignment <= 256 )); // alignment V is limited to max of 256-byte boundaries
47 ESL_DASSERT1(( (alignment & (alignment-1)) == 0 )); // bit trickery for: alignment V is a power of 2
48
49 if ( (pp = malloc(size + alignment)) == NULL) return NULL; // worst case: we need a full extra V bytes
50 p = (uint8_t *) (((uintptr_t) pp + alignment) & (~(alignment-1))); // p is now aligned, and p-pp >= 1, so we have room for r
51 r = (int) ((uintptr_t) p - (uintptr_t) pp); // total shift, 1..V (int; won't fit in uint8)
52 p[-1] = (uint8_t) (r-1); // tuck r-1 into the byte before *p
53
54
55 #if 0
56 printf("allocating...\n");
57 printf("original malloc'ed ptr = %p\n", pp);
58 printf("aligned ptr = %p\n", p);
59 printf("offset = %d\n", r);
60 #endif
61
62 return (void *) p;
63 }
64
65
66 static void
67 alloc_aligned_free_fallback(void *p)
68 {
69 void *pp;
70 unsigned int r;
71
72 r = (unsigned int) (((uint8_t *) p)[-1]) + 1; // get r-1 back from byte before *p. Add 1, but as an int, not uint8
73 pp = (void *) ((uintptr_t) p - r); // move p back by r bytes to reconstruct what malloc's pp was
74 free(pp); // and we can free the reconstructed pointer.
75
76 #if 0
77 printf("freeing...\n");
78 printf("offset = %d\n", r);
79 printf("aligned ptr = %p\n", p);
80 printf("original malloc'ed ptr = %p\n", pp);
81 #endif
82 }
83 #endif // only compile the fallback code in if we don't have a system alternative, or in unit testing
84 /*-------------- end, fallback implementation -------------------*/
85
86
87
88 /*****************************************************************
89 * 2. esl_alloc_aligned() and esl_alloc_free() API calls
90 *****************************************************************/
91
92 /* Function: esl_alloc_aligned()
93 * Synopsis: Allocate aligned memory.
94 * Incept: SRE, Thu Feb 9 17:12:53 2017 [Lo Fidelity Allstars]
95 *
96 * Purpose: Allocate <size> bytes of memory, and return a pointer to
97 * it, with the pointer aligned on a <alignment>-byte
98 * boundary. <size> is > 0. <alignment> must be a power of
99 * two, >= sizeof(void *), and <= 256. The pointer must be
100 * freed by esl_alloc_free().
101 *
102 * Args: size : size to allocate, in bytes
103 * alignment : memory aligned on this byte boundary
104 *
105 * Returns: pointer to the aligned memory
106 *
107 * Throws: <NULL> on allocation failure.
108 *
109 * Note: It's better to return <void *> so the caller can cast the
110 * pointer to the desired type. If instead you pass
111 * <*ret_p> as an argument, so you can return an integer
112 * status in Easel style, the caller has to fiddle with it,
113 * casting it to void **, to make the compiler happy.
114 *
115 * We require <size> > 0 because malloc() and
116 * posix_memalign() are allowed to return NULL for
117 * zero-length allocations, and Easel sees that as an
118 * allocation failure.
119 *
120 * We require <alignment> >= sizeof(void *) because
121 * posix_memalign() does. The POSIX spec actually states
122 * that <alignment> must be a **multiple** of sizeof(void
123 * *), but don't get confused. Because <alignment> is a
124 * power of two, that's the same thing.
125 */
126 void *
127 esl_alloc_aligned(size_t size, size_t alignment)
128 {
129 void *p;
130
131 ESL_DASSERT1(( size > 0 )); // avoid 0 mallocs
132 ESL_DASSERT1(( alignment > sizeof(void *) && alignment <= 256 )); // alignment V is limited to max of 256-byte boundaries
133 ESL_DASSERT1(( (alignment & (alignment-1)) == 0 )); // bit trickery for: alignment V is a power of 2
134
135 #ifdef HAVE_POSIX_MEMALIGN
136 if (posix_memalign(&p, alignment, size) != 0) return NULL;
137 #elif HAVE_ALIGNED_ALLOC
138 p = aligned_alloc(alignment, size);
139 #elif HAVE__MM_MALLOC
140 p = _mm_malloc(size, alignment);
141 #else
142 p = alloc_aligned_fallback(size, alignment);
143 #endif
144
145 if (p == NULL)
146 esl_exception(eslEMEM, FALSE, __FILE__, __LINE__, "aligned alloc of size %d failed", size);
147
148 return p;
149 }
150
151 /* Function: esl_alloc_free()
152 * Synopsis: Free aligned memory from esl_alloc_aligned()
153 * Incept: SRE, Thu Feb 9 17:21:41 2017 [Andrew Bird]
154 */
155 void
156 esl_alloc_free(void *p)
157 {
158 if (p) {
159 #ifdef HAVE_POSIX_MEMALIGN
160 free(p);
161 #elif HAVE_ALIGNED_ALLOC
162 free(p);
163 #elif HAVE__MM_MALLOC
164 _mm_free(p);
165 #else
166 alloc_aligned_free_fallback(p);
167 #endif
168 }
169 }
170 /*----------------------- end, API ------------------------------*/
171
172
173 /*****************************************************************
174 * 3. Benchmark driver
175 *****************************************************************/
176 #ifdef eslALLOC_BENCHMARK
177
178 #include "easel.h"
179 #include "esl_alloc.h"
180 #include "esl_getopts.h"
181 #include "esl_random.h"
182
183 static ESL_OPTIONS options[] = {
184 /* name type default env range toggles reqs incomp help docgroup*/
185 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
186 { "-1", eslARG_NONE,"default",NULL, NULL, "-1,-2,-3,-4", NULL, NULL, "1: malloc (unaligned), realloc (unaligned)", 0 },
187 { "-2", eslARG_NONE, FALSE, NULL, NULL, "-1,-2,-3,-4", NULL, NULL, "2: malloc (unaligned), free/fresh alloc", 0 },
188 { "-3", eslARG_NONE, FALSE, NULL, NULL, "-1,-2,-3,-4", NULL, NULL, "3: our aligned malloc, free/fresh alloc", 0 },
189 { "-4", eslARG_NONE, FALSE, NULL, NULL, "-1,-2,-3,-4", NULL, NULL, "4: posix_memalign, free/fresh alloc", 0 },
190 { "-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
191 { "-N", eslARG_INT, "10000", NULL, NULL, NULL, NULL, NULL, "number of iterations", 0 },
192 { "-L", eslARG_INT, "100", NULL, NULL, NULL, NULL, NULL, "number of rows", 0 },
193 { "-M", eslARG_INT, "500000", NULL, NULL, NULL, NULL, NULL, "maximum alloc per row (bytes)", 0 },
194 { "-V", eslARG_INT, "64", NULL, NULL, NULL, NULL, NULL, "memory alignment (bytes)", 0 },
195 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
196 };
197 static char usage[] = "[-options]";
198 static char banner[] = "benchmark driver for esl_alloc";
199
200 int
201 main(int argc, char **argv)
202 {
203 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
204 ESL_RANDOMNESS *rng = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
205 int N = esl_opt_GetInteger(go, "-N");
206 int L = esl_opt_GetInteger(go, "-L");
207 int M = esl_opt_GetInteger(go, "-M");
208 int V = esl_opt_GetInteger(go, "-V");
209 int do_realloc = esl_opt_GetBoolean(go, "-1");
210 int do_fresh_malloc = esl_opt_GetBoolean(go, "-2");
211 int do_esl_alloc = esl_opt_GetBoolean(go, "-3");
212 int do_posix_memalign = esl_opt_GetBoolean(go, "-4");
213 char **p;
214 int size;
215 int i,j;
216
217 #ifndef HAVE_POSIX_MEMALIGN
218 if (do_posix_memalign) esl_fatal("can't benchmark posix_memalign(): not available on this system");
219 #endif
220
221 p = malloc(sizeof(char *) * L);
222 for (i = 0; i < L; i++)
223 {
224 size = 1 + esl_rnd_Roll(rng,M);
225 if (do_realloc) p[i] = malloc(size);
226 else if (do_fresh_malloc) p[i] = malloc(size);
227 else if (do_esl_alloc) p[i] = alloc_aligned_fallback(size, V);
228 #ifdef HAVE_POSIX_MEMALIGN
229 else if (do_posix_memalign) {
230 if (posix_memalign((void **) &(p[i]), V, size) != 0) esl_fatal("posix_memalign() failed");
231 }
232 #endif
233 }
234
235 for (j = 0; j < N; j++)
236 {
237 for (i = 0; i < L; i++)
238 {
239 size = 1 + esl_rnd_Roll(rng,M);
240 if (do_realloc) { p[i] = realloc(p[i], size); }
241 else if (do_fresh_malloc) { free(p[i]); p[i] = malloc(size); }
242 else if (do_esl_alloc) { alloc_aligned_free_fallback(p[i]); p[i] = alloc_aligned_fallback(size, V); }
243 #ifdef HAVE_POSIX_MEMALIGN
244 else if (do_posix_memalign) {
245 free(p[i]);
246 if (posix_memalign((void **) &(p[i]), V, size) != 0) esl_fatal("posix_memalign failed");
247 }
248 #endif
249 }
250 }
251
252 for (i = 0; i < L; i++)
253 if (do_esl_alloc) alloc_aligned_free_fallback(p[i]);
254 else free(p[i]);
255 free(p);
256 esl_randomness_Destroy(rng);
257 esl_getopts_Destroy(go);
258 return 0;
259 }
260 #endif // eslALLOC_BENCHMARK
261 /*----------------- end, benchmark ------------------------------*/
262
263
264
265 /*****************************************************************
266 * 4. Unit tests
267 *****************************************************************/
268 #ifdef eslALLOC_TESTDRIVE
269 #include <limits.h>
270 #include "esl_random.h"
271
272
273 static void
274 utest_fallback(ESL_RANDOMNESS *rng)
275 {
276 int N = 100; // do N allocations in the utest
277 int **p; // store all the allocated pointers, forcing alloc to give us different ones
278 int L; // randomly chosen allocation size, 1..1000
279 int V; // randomly chosen alignment, sizeof(void*)..2^8 bytes
280 int i,j;
281
282 ESL_DASSERT1(( sizeof(void *) < 256 )); // if not, code below will infinite loop
283
284 if ((p = malloc(sizeof(int *) * N)) == NULL) esl_fatal("malloc failed");
285 for (i = 0; i < N; i++)
286 {
287 L = esl_rnd_Roll(rng, 1000) + 1;
288 do { V = 1 << (4 + esl_rnd_Roll(rng, 5)); } while (V < sizeof(void *)); // 2^r for r=4..8: 16,32...256
289 p[i] = alloc_aligned_fallback(sizeof(int) * L, V);
290
291 /* try to instigate a valgrind-catchable write failure */
292 for (j = 0; j < L; j++)
293 p[i][j] = 1;
294 }
295
296 for (i = 0; i < N; i++)
297 alloc_aligned_free_fallback(p[i]);
298
299 free(p);
300 }
301
302
303 /* same test strategy & code as above, but now for the API calls */
304 static void
305 utest_api(ESL_RANDOMNESS *rng)
306 {
307 int N = 100;
308 int **p;
309 int L;
310 int V;
311 int i,j;
312
313 ESL_DASSERT1(( sizeof(void *) < 256 )); // if not, code below will infinite loop
314
315 if ((p = malloc(sizeof(int *) * N)) == NULL) esl_fatal("malloc failed");
316 for (i = 0; i < N; i++)
317 {
318 L = esl_rnd_Roll(rng, 1000) + 1;
319 do { V = 1 << (4 + esl_rnd_Roll(rng, 5)); } while (V < sizeof(void *));
320 p[i] = esl_alloc_aligned(sizeof(int) * L, V);
321
322 for (j = 0; j < L; j++) p[i][j] = 1;
323 }
324
325 for (i = 0; i < N; i++)
326 esl_alloc_free(p[i]);
327 free(p);
328 }
329
330 /* there must be a better way to do this. */
331 static int
332 determine_system_alignment(void)
333 {
334 int N = 100;
335 char **p;
336 int i;
337 uintptr_t x;
338 int V, Vmin;
339
340 if ((p = malloc(sizeof(char *) * N)) == NULL) esl_fatal("malloc failed");
341 for (i = 0; i < N; i++)
342 p[i] = malloc(sizeof(char) * 1000);
343
344 Vmin = INT_MAX;
345 for (i = 0; i < N; i++)
346 {
347 x = (uintptr_t) p[i];
348 V = 0;
349 while ( !(x & 0x1) ) { x >>= 1; V++; }
350 Vmin = ESL_MIN(V, Vmin);
351 }
352
353 for (i = 0; i < N; i++)
354 free(p[i]);
355 free(p);
356
357 return 1<<Vmin;
358 }
359 #endif // eslALLOC_TESTDRIVE
360 /*--------------------- unit tests ------------------------------*/
361
362
363
364
365 /*****************************************************************
366 * 5. Test driver
367 *****************************************************************/
368 #ifdef eslALLOC_TESTDRIVE
369
370 #include "easel.h"
371 #include "esl_getopts.h"
372 #include "esl_random.h"
373
374 static ESL_OPTIONS options[] = {
375 /* name type default env range toggles reqs incomp help docgroup*/
376 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
377 { "-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
378 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
379 };
380 static char usage[] = "[-options]";
381 static char banner[] = "test driver for esl_alloc";
382
383 int
384 main(int argc, char **argv)
385 {
386 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
387 ESL_RANDOMNESS *rng = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
388
389 fprintf(stderr, "## %s\n", argv[0]);
390 fprintf(stderr, "# rng seed: %" PRIu32 "\n", esl_randomness_GetSeed(rng));
391 fprintf(stderr, "# sizeof(void*): %d\n", (int) sizeof(void *));
392 fprintf(stderr, "# malloc() aligns on: %d bytes\n", determine_system_alignment());
393
394 #ifdef HAVE_POSIX_MEMALIGN
395 fprintf(stderr, "# esl_alloc is using: posix_memalign()\n");
396 #elif HAVE_ALIGNED_ALLOC
397 fprintf(stderr, "# esl_alloc is using: aligned_alloc()\n");
398 #elif HAVE__MM_MALLOC
399 fprintf(stderr, "# esl_alloc is using: _mm_malloc()\n");
400 #else
401 fprintf(stderr, "# esl_alloc is using: alloc_aligned_fallback()\n");
402 #endif
403
404 utest_fallback(rng);
405 utest_api(rng);
406
407 fprintf(stderr, "# status = ok\n");
408 esl_randomness_Destroy(rng);
409 esl_getopts_Destroy(go);
410 return eslOK;
411 }
412 #endif // eslALLOC_TESTDRIVE