]> git.ipfire.org Git - thirdparty/glibc.git/blame - malloc/arena.c
malloc: Manual part of conversion to __libc_lock
[thirdparty/glibc.git] / malloc / arena.c
CommitLineData
fa8d436c 1/* Malloc implementation for multiple threads without lock contention.
f7a9f785 2 Copyright (C) 2001-2016 Free Software Foundation, Inc.
fa8d436c
UD
3 This file is part of the GNU C Library.
4 Contributed by Wolfram Gloger <wg@malloc.de>, 2001.
5
6 The GNU C Library is free software; you can redistribute it and/or
cc7375ce
RM
7 modify it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
fa8d436c
UD
9 License, or (at your option) any later version.
10
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
cc7375ce 14 Lesser General Public License for more details.
fa8d436c 15
cc7375ce 16 You should have received a copy of the GNU Lesser General Public
59ba27a6
PE
17 License along with the GNU C Library; see the file COPYING.LIB. If
18 not, see <http://www.gnu.org/licenses/>. */
fa8d436c 19
a28b6b0a
RM
20#include <stdbool.h>
21
fa8d436c
UD
22/* Compile-time constants. */
23
6c8dbf00 24#define HEAP_MIN_SIZE (32 * 1024)
fa8d436c 25#ifndef HEAP_MAX_SIZE
e404fb16 26# ifdef DEFAULT_MMAP_THRESHOLD_MAX
bd2c2341 27# define HEAP_MAX_SIZE (2 * DEFAULT_MMAP_THRESHOLD_MAX)
e404fb16 28# else
6c8dbf00 29# define HEAP_MAX_SIZE (1024 * 1024) /* must be a power of two */
e404fb16 30# endif
fa8d436c
UD
31#endif
32
33/* HEAP_MIN_SIZE and HEAP_MAX_SIZE limit the size of mmap()ed heaps
34 that are dynamically created for multi-threaded programs. The
35 maximum size must be a power of two, for fast determination of
36 which heap belongs to a chunk. It should be much larger than the
37 mmap threshold, so that requests with a size just below that
38 threshold can be fulfilled without creating too many heaps. */
39
fa8d436c
UD
40/***************************************************************************/
41
42#define top(ar_ptr) ((ar_ptr)->top)
43
44/* A heap is a single contiguous memory region holding (coalesceable)
45 malloc_chunks. It is allocated with mmap() and always starts at an
22a89187 46 address aligned to HEAP_MAX_SIZE. */
fa8d436c 47
6c8dbf00
OB
48typedef struct _heap_info
49{
fa8d436c
UD
50 mstate ar_ptr; /* Arena for this heap. */
51 struct _heap_info *prev; /* Previous heap. */
52 size_t size; /* Current size in bytes. */
6c8dbf00
OB
53 size_t mprotect_size; /* Size in bytes that has been mprotected
54 PROT_READ|PROT_WRITE. */
7d013a64
RM
55 /* Make sure the following data is properly aligned, particularly
56 that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of
c7fd3362
JJ
57 MALLOC_ALIGNMENT. */
58 char pad[-6 * SIZE_SZ & MALLOC_ALIGN_MASK];
fa8d436c
UD
59} heap_info;
60
7d013a64
RM
61/* Get a compile-time error if the heap_info padding is not correct
62 to make alignment work as expected in sYSMALLOc. */
63extern int sanity_check_heap_info_alignment[(sizeof (heap_info)
6c8dbf00
OB
64 + 2 * SIZE_SZ) % MALLOC_ALIGNMENT
65 ? -1 : 1];
7d013a64 66
6782806d
FW
67/* Thread specific data. */
68
69static __thread mstate thread_arena attribute_tls_model_ie;
70
90c400bd
FW
71/* Arena free list. free_list_lock synchronizes access to the
72 free_list variable below, and the next_free and attached_threads
73 members of struct malloc_state objects. No other locks must be
74 acquired after free_list_lock has been acquired. */
fa8d436c 75
cbb47fa1 76__libc_lock_define_initialized (static, free_list_lock);
02d46fc4 77static size_t narenas = 1;
425ce2ed 78static mstate free_list;
fa8d436c 79
90c400bd
FW
80/* list_lock prevents concurrent writes to the next member of struct
81 malloc_state objects.
82
83 Read access to the next member is supposed to synchronize with the
84 atomic_write_barrier and the write to the next member in
85 _int_new_arena. This suffers from data races; see the FIXME
86 comments in _int_new_arena and reused_arena.
87
7962541a
FW
88 list_lock also prevents concurrent forks. At the time list_lock is
89 acquired, no arena lock must have been acquired, but it is
90 permitted to acquire arena locks subsequently, while list_lock is
91 acquired. */
cbb47fa1 92__libc_lock_define_initialized (static, list_lock);
90c400bd 93
2a652f5a
RM
94/* Already initialized? */
95int __malloc_initialized = -1;
96
fa8d436c
UD
97/**************************************************************************/
98
fa8d436c
UD
99
100/* arena_get() acquires an arena and locks the corresponding mutex.
101 First, try the one last locked successfully by this thread. (This
102 is the common case and handled with a macro for speed.) Then, loop
103 once over the circularly linked list of arenas. If no arena is
104 readily available, create a new one. In this latter case, `size'
105 is just a hint as to how much memory will be required immediately
106 in the new arena. */
107
108#define arena_get(ptr, size) do { \
6782806d 109 ptr = thread_arena; \
6c8dbf00
OB
110 arena_lock (ptr, size); \
111 } while (0)
425ce2ed 112
6c8dbf00 113#define arena_lock(ptr, size) do { \
fff94fa2 114 if (ptr && !arena_is_corrupt (ptr)) \
cbb47fa1 115 __libc_lock_lock (ptr->mutex); \
6c8dbf00 116 else \
92a9b22d 117 ptr = arena_get2 ((size), NULL); \
6c8dbf00 118 } while (0)
fa8d436c
UD
119
120/* find the heap and corresponding arena for a given ptr */
121
122#define heap_for_ptr(ptr) \
6c8dbf00 123 ((heap_info *) ((unsigned long) (ptr) & ~(HEAP_MAX_SIZE - 1)))
fa8d436c 124#define arena_for_chunk(ptr) \
6c8dbf00 125 (chunk_non_main_arena (ptr) ? heap_for_ptr (ptr)->ar_ptr : &main_arena)
fa8d436c 126
fa8d436c
UD
127
128/**************************************************************************/
129
fa8d436c
UD
130/* atfork support. */
131
29d79486
FW
132/* The following three functions are called around fork from a
133 multi-threaded process. We do not use the general fork handler
134 mechanism to make sure that our handlers are the last ones being
135 called, so that other fork handlers can use the malloc
136 subsystem. */
fa8d436c 137
29d79486 138void
186fe877 139internal_function
29d79486 140__malloc_fork_lock_parent (void)
fa8d436c 141{
6c8dbf00 142 if (__malloc_initialized < 1)
2a652f5a 143 return;
6c8dbf00 144
90c400bd 145 /* We do not acquire free_list_lock here because we completely
29d79486 146 reconstruct free_list in __malloc_fork_unlock_child. */
90c400bd 147
4bf5f222 148 __libc_lock_lock (list_lock);
7dac9f3d 149
8a727af9 150 for (mstate ar_ptr = &main_arena;; )
6c8dbf00 151 {
4bf5f222 152 __libc_lock_lock (ar_ptr->mutex);
6c8dbf00
OB
153 ar_ptr = ar_ptr->next;
154 if (ar_ptr == &main_arena)
155 break;
7dac9f3d 156 }
fa8d436c
UD
157}
158
29d79486 159void
186fe877 160internal_function
29d79486 161__malloc_fork_unlock_parent (void)
fa8d436c 162{
6c8dbf00 163 if (__malloc_initialized < 1)
2a652f5a 164 return;
6c8dbf00 165
8a727af9 166 for (mstate ar_ptr = &main_arena;; )
6c8dbf00 167 {
4bf5f222 168 __libc_lock_unlock (ar_ptr->mutex);
6c8dbf00
OB
169 ar_ptr = ar_ptr->next;
170 if (ar_ptr == &main_arena)
171 break;
172 }
4bf5f222 173 __libc_lock_unlock (list_lock);
fa8d436c
UD
174}
175
29d79486 176void
186fe877 177internal_function
29d79486 178__malloc_fork_unlock_child (void)
fa8d436c 179{
6c8dbf00 180 if (__malloc_initialized < 1)
2a652f5a 181 return;
6c8dbf00 182
8a727af9 183 /* Push all arenas to the free list, except thread_arena, which is
a62719ba 184 attached to the current thread. */
4bf5f222 185 __libc_lock_init (free_list_lock);
8a727af9
FW
186 if (thread_arena != NULL)
187 thread_arena->attached_threads = 1;
425ce2ed 188 free_list = NULL;
8a727af9 189 for (mstate ar_ptr = &main_arena;; )
6c8dbf00 190 {
4bf5f222 191 __libc_lock_init (ar_ptr->mutex);
8a727af9 192 if (ar_ptr != thread_arena)
6c8dbf00 193 {
a62719ba
FW
194 /* This arena is no longer attached to any thread. */
195 ar_ptr->attached_threads = 0;
6c8dbf00
OB
196 ar_ptr->next_free = free_list;
197 free_list = ar_ptr;
198 }
199 ar_ptr = ar_ptr->next;
200 if (ar_ptr == &main_arena)
201 break;
425ce2ed 202 }
90c400bd 203
4bf5f222 204 __libc_lock_init (list_lock);
fa8d436c
UD
205}
206
fa8d436c 207/* Initialization routine. */
fa8d436c
UD
208#include <string.h>
209extern char **_environ;
210
211static char *
212internal_function
213next_env_entry (char ***position)
214{
215 char **current = *position;
216 char *result = NULL;
217
218 while (*current != NULL)
219 {
220 if (__builtin_expect ((*current)[0] == 'M', 0)
6c8dbf00
OB
221 && (*current)[1] == 'A'
222 && (*current)[2] == 'L'
223 && (*current)[3] == 'L'
224 && (*current)[4] == 'O'
225 && (*current)[5] == 'C'
226 && (*current)[6] == '_')
227 {
228 result = &(*current)[7];
fa8d436c 229
6c8dbf00
OB
230 /* Save current position for next visit. */
231 *position = ++current;
fa8d436c 232
6c8dbf00
OB
233 break;
234 }
fa8d436c
UD
235
236 ++current;
237 }
238
239 return result;
240}
fa8d436c 241
c0f62c56 242
22a89187 243#ifdef SHARED
c0f62c56
UD
244static void *
245__failing_morecore (ptrdiff_t d)
246{
247 return (void *) MORECORE_FAILURE;
248}
5f21997b
UD
249
250extern struct dl_open_hook *_dl_open_hook;
251libc_hidden_proto (_dl_open_hook);
fde89ad0
RM
252#endif
253
fa8d436c 254static void
06d6611a 255ptmalloc_init (void)
fa8d436c 256{
6c8dbf00
OB
257 if (__malloc_initialized >= 0)
258 return;
259
fa8d436c
UD
260 __malloc_initialized = 0;
261
22a89187 262#ifdef SHARED
5f21997b
UD
263 /* In case this libc copy is in a non-default namespace, never use brk.
264 Likewise if dlopened from statically linked program. */
c0f62c56
UD
265 Dl_info di;
266 struct link_map *l;
5f21997b
UD
267
268 if (_dl_open_hook != NULL
269 || (_dl_addr (ptmalloc_init, &di, &l, NULL) != 0
6c8dbf00 270 && l->l_ns != LM_ID_BASE))
c0f62c56
UD
271 __morecore = __failing_morecore;
272#endif
273
6782806d 274 thread_arena = &main_arena;
02d46fc4 275 const char *s = NULL;
a1ffb40e 276 if (__glibc_likely (_environ != NULL))
08e49216
RM
277 {
278 char **runp = _environ;
279 char *envline;
280
281 while (__builtin_expect ((envline = next_env_entry (&runp)) != NULL,
6c8dbf00
OB
282 0))
283 {
284 size_t len = strcspn (envline, "=");
285
286 if (envline[len] != '=')
287 /* This is a "MALLOC_" variable at the end of the string
288 without a '=' character. Ignore it since otherwise we
289 will access invalid memory below. */
290 continue;
291
292 switch (len)
293 {
294 case 6:
295 if (memcmp (envline, "CHECK_", 6) == 0)
296 s = &envline[7];
297 break;
298 case 8:
299 if (!__builtin_expect (__libc_enable_secure, 0))
300 {
301 if (memcmp (envline, "TOP_PAD_", 8) == 0)
302 __libc_mallopt (M_TOP_PAD, atoi (&envline[9]));
303 else if (memcmp (envline, "PERTURB_", 8) == 0)
304 __libc_mallopt (M_PERTURB, atoi (&envline[9]));
305 }
306 break;
307 case 9:
308 if (!__builtin_expect (__libc_enable_secure, 0))
309 {
310 if (memcmp (envline, "MMAP_MAX_", 9) == 0)
311 __libc_mallopt (M_MMAP_MAX, atoi (&envline[10]));
312 else if (memcmp (envline, "ARENA_MAX", 9) == 0)
313 __libc_mallopt (M_ARENA_MAX, atoi (&envline[10]));
314 }
315 break;
316 case 10:
317 if (!__builtin_expect (__libc_enable_secure, 0))
318 {
319 if (memcmp (envline, "ARENA_TEST", 10) == 0)
320 __libc_mallopt (M_ARENA_TEST, atoi (&envline[11]));
321 }
322 break;
323 case 15:
324 if (!__builtin_expect (__libc_enable_secure, 0))
325 {
326 if (memcmp (envline, "TRIM_THRESHOLD_", 15) == 0)
327 __libc_mallopt (M_TRIM_THRESHOLD, atoi (&envline[16]));
328 else if (memcmp (envline, "MMAP_THRESHOLD_", 15) == 0)
329 __libc_mallopt (M_MMAP_THRESHOLD, atoi (&envline[16]));
330 }
331 break;
332 default:
333 break;
334 }
335 }
336 }
337 if (s && s[0])
338 {
339 __libc_mallopt (M_CHECK_ACTION, (int) (s[0] - '0'));
340 if (check_action != 0)
341 __malloc_check_init ();
08e49216 342 }
2ba3cfa1 343#if HAVE_MALLOC_INIT_HOOK
92e1ab0e 344 void (*hook) (void) = atomic_forced_read (__malloc_initialize_hook);
df77455c
UD
345 if (hook != NULL)
346 (*hook)();
2ba3cfa1 347#endif
fa8d436c
UD
348 __malloc_initialized = 1;
349}
350
fa8d436c
UD
351/* Managing heaps and arenas (for concurrent threads) */
352
fa8d436c
UD
353#if MALLOC_DEBUG > 1
354
355/* Print the complete contents of a single heap to stderr. */
356
357static void
6c8dbf00 358dump_heap (heap_info *heap)
fa8d436c
UD
359{
360 char *ptr;
361 mchunkptr p;
362
6c8dbf00
OB
363 fprintf (stderr, "Heap %p, size %10lx:\n", heap, (long) heap->size);
364 ptr = (heap->ar_ptr != (mstate) (heap + 1)) ?
365 (char *) (heap + 1) : (char *) (heap + 1) + sizeof (struct malloc_state);
366 p = (mchunkptr) (((unsigned long) ptr + MALLOC_ALIGN_MASK) &
367 ~MALLOC_ALIGN_MASK);
368 for (;; )
369 {
370 fprintf (stderr, "chunk %p size %10lx", p, (long) p->size);
371 if (p == top (heap->ar_ptr))
372 {
373 fprintf (stderr, " (top)\n");
374 break;
375 }
376 else if (p->size == (0 | PREV_INUSE))
377 {
378 fprintf (stderr, " (fence)\n");
379 break;
380 }
381 fprintf (stderr, "\n");
382 p = next_chunk (p);
fa8d436c 383 }
fa8d436c 384}
fa8d436c
UD
385#endif /* MALLOC_DEBUG > 1 */
386
26d550d3
UD
387/* If consecutive mmap (0, HEAP_MAX_SIZE << 1, ...) calls return decreasing
388 addresses as opposed to increasing, new_heap would badly fragment the
389 address space. In that case remember the second HEAP_MAX_SIZE part
390 aligned to HEAP_MAX_SIZE from last mmap (0, HEAP_MAX_SIZE << 1, ...)
391 call (if it is already aligned) and try to reuse it next time. We need
392 no locking for it, as kernel ensures the atomicity for us - worst case
393 we'll call mmap (addr, HEAP_MAX_SIZE, ...) for some value of addr in
394 multiple threads, but only one will succeed. */
395static char *aligned_heap_area;
396
fa8d436c
UD
397/* Create a new heap. size is automatically rounded up to a multiple
398 of the page size. */
399
400static heap_info *
401internal_function
6c8dbf00 402new_heap (size_t size, size_t top_pad)
fa8d436c 403{
8a35c3fe 404 size_t pagesize = GLRO (dl_pagesize);
fa8d436c
UD
405 char *p1, *p2;
406 unsigned long ul;
407 heap_info *h;
408
6c8dbf00 409 if (size + top_pad < HEAP_MIN_SIZE)
fa8d436c 410 size = HEAP_MIN_SIZE;
6c8dbf00 411 else if (size + top_pad <= HEAP_MAX_SIZE)
fa8d436c 412 size += top_pad;
6c8dbf00 413 else if (size > HEAP_MAX_SIZE)
fa8d436c
UD
414 return 0;
415 else
416 size = HEAP_MAX_SIZE;
8a35c3fe 417 size = ALIGN_UP (size, pagesize);
fa8d436c
UD
418
419 /* A memory region aligned to a multiple of HEAP_MAX_SIZE is needed.
420 No swap space needs to be reserved for the following large
421 mapping (on Linux, this is the case for all non-writable mappings
422 anyway). */
26d550d3 423 p2 = MAP_FAILED;
6c8dbf00
OB
424 if (aligned_heap_area)
425 {
426 p2 = (char *) MMAP (aligned_heap_area, HEAP_MAX_SIZE, PROT_NONE,
427 MAP_NORESERVE);
428 aligned_heap_area = NULL;
429 if (p2 != MAP_FAILED && ((unsigned long) p2 & (HEAP_MAX_SIZE - 1)))
430 {
431 __munmap (p2, HEAP_MAX_SIZE);
432 p2 = MAP_FAILED;
433 }
26d550d3 434 }
6c8dbf00
OB
435 if (p2 == MAP_FAILED)
436 {
437 p1 = (char *) MMAP (0, HEAP_MAX_SIZE << 1, PROT_NONE, MAP_NORESERVE);
438 if (p1 != MAP_FAILED)
439 {
440 p2 = (char *) (((unsigned long) p1 + (HEAP_MAX_SIZE - 1))
441 & ~(HEAP_MAX_SIZE - 1));
442 ul = p2 - p1;
443 if (ul)
444 __munmap (p1, ul);
445 else
446 aligned_heap_area = p2 + HEAP_MAX_SIZE;
447 __munmap (p2 + HEAP_MAX_SIZE, HEAP_MAX_SIZE - ul);
448 }
26d550d3 449 else
6c8dbf00
OB
450 {
451 /* Try to take the chance that an allocation of only HEAP_MAX_SIZE
452 is already aligned. */
453 p2 = (char *) MMAP (0, HEAP_MAX_SIZE, PROT_NONE, MAP_NORESERVE);
454 if (p2 == MAP_FAILED)
455 return 0;
456
457 if ((unsigned long) p2 & (HEAP_MAX_SIZE - 1))
458 {
459 __munmap (p2, HEAP_MAX_SIZE);
460 return 0;
461 }
462 }
fa8d436c 463 }
6c8dbf00
OB
464 if (__mprotect (p2, size, PROT_READ | PROT_WRITE) != 0)
465 {
466 __munmap (p2, HEAP_MAX_SIZE);
467 return 0;
468 }
469 h = (heap_info *) p2;
fa8d436c 470 h->size = size;
c7fd3362 471 h->mprotect_size = size;
322dea08 472 LIBC_PROBE (memory_heap_new, 2, h, h->size);
fa8d436c
UD
473 return h;
474}
475
cbf5760e
UD
476/* Grow a heap. size is automatically rounded up to a
477 multiple of the page size. */
fa8d436c
UD
478
479static int
6c8dbf00 480grow_heap (heap_info *h, long diff)
fa8d436c 481{
8a35c3fe 482 size_t pagesize = GLRO (dl_pagesize);
fa8d436c
UD
483 long new_size;
484
8a35c3fe 485 diff = ALIGN_UP (diff, pagesize);
6c8dbf00
OB
486 new_size = (long) h->size + diff;
487 if ((unsigned long) new_size > (unsigned long) HEAP_MAX_SIZE)
cbf5760e 488 return -1;
6c8dbf00
OB
489
490 if ((unsigned long) new_size > h->mprotect_size)
491 {
492 if (__mprotect ((char *) h + h->mprotect_size,
493 (unsigned long) new_size - h->mprotect_size,
494 PROT_READ | PROT_WRITE) != 0)
495 return -2;
496
497 h->mprotect_size = new_size;
498 }
cbf5760e
UD
499
500 h->size = new_size;
322dea08 501 LIBC_PROBE (memory_heap_more, 2, h, h->size);
cbf5760e
UD
502 return 0;
503}
504
505/* Shrink a heap. */
506
507static int
6c8dbf00 508shrink_heap (heap_info *h, long diff)
cbf5760e
UD
509{
510 long new_size;
511
6c8dbf00
OB
512 new_size = (long) h->size - diff;
513 if (new_size < (long) sizeof (*h))
cbf5760e 514 return -1;
6c8dbf00 515
9fab36eb
SP
516 /* Try to re-map the extra heap space freshly to save memory, and make it
517 inaccessible. See malloc-sysdep.h to know when this is true. */
a1ffb40e 518 if (__glibc_unlikely (check_may_shrink_heap ()))
cbf5760e 519 {
6c8dbf00
OB
520 if ((char *) MMAP ((char *) h + new_size, diff, PROT_NONE,
521 MAP_FIXED) == (char *) MAP_FAILED)
522 return -2;
523
cbf5760e
UD
524 h->mprotect_size = new_size;
525 }
cbf5760e 526 else
6c8dbf00 527 __madvise ((char *) h + new_size, diff, MADV_DONTNEED);
cbf5760e
UD
528 /*fprintf(stderr, "shrink %p %08lx\n", h, new_size);*/
529
fa8d436c 530 h->size = new_size;
322dea08 531 LIBC_PROBE (memory_heap_less, 2, h, h->size);
fa8d436c
UD
532 return 0;
533}
534
535/* Delete a heap. */
536
26d550d3 537#define delete_heap(heap) \
6c8dbf00
OB
538 do { \
539 if ((char *) (heap) + HEAP_MAX_SIZE == aligned_heap_area) \
540 aligned_heap_area = NULL; \
541 __munmap ((char *) (heap), HEAP_MAX_SIZE); \
542 } while (0)
fa8d436c
UD
543
544static int
545internal_function
6c8dbf00 546heap_trim (heap_info *heap, size_t pad)
fa8d436c
UD
547{
548 mstate ar_ptr = heap->ar_ptr;
6c8dbf00
OB
549 unsigned long pagesz = GLRO (dl_pagesize);
550 mchunkptr top_chunk = top (ar_ptr), p, bck, fwd;
fa8d436c 551 heap_info *prev_heap;
c26efef9 552 long new_size, top_size, top_area, extra, prev_size, misalign;
fa8d436c
UD
553
554 /* Can this heap go away completely? */
6c8dbf00
OB
555 while (top_chunk == chunk_at_offset (heap, sizeof (*heap)))
556 {
557 prev_heap = heap->prev;
558 prev_size = prev_heap->size - (MINSIZE - 2 * SIZE_SZ);
559 p = chunk_at_offset (prev_heap, prev_size);
560 /* fencepost must be properly aligned. */
561 misalign = ((long) p) & MALLOC_ALIGN_MASK;
562 p = chunk_at_offset (prev_heap, prev_size - misalign);
563 assert (p->size == (0 | PREV_INUSE)); /* must be fencepost */
564 p = prev_chunk (p);
565 new_size = chunksize (p) + (MINSIZE - 2 * SIZE_SZ) + misalign;
566 assert (new_size > 0 && new_size < (long) (2 * MINSIZE));
567 if (!prev_inuse (p))
568 new_size += p->prev_size;
569 assert (new_size > 0 && new_size < HEAP_MAX_SIZE);
570 if (new_size + (HEAP_MAX_SIZE - prev_heap->size) < pad + MINSIZE + pagesz)
571 break;
572 ar_ptr->system_mem -= heap->size;
6c8dbf00
OB
573 LIBC_PROBE (memory_heap_free, 2, heap, heap->size);
574 delete_heap (heap);
575 heap = prev_heap;
576 if (!prev_inuse (p)) /* consolidate backward */
577 {
578 p = prev_chunk (p);
fff94fa2 579 unlink (ar_ptr, p, bck, fwd);
6c8dbf00
OB
580 }
581 assert (((unsigned long) ((char *) p + new_size) & (pagesz - 1)) == 0);
582 assert (((char *) p + new_size) == ((char *) heap + heap->size));
583 top (ar_ptr) = top_chunk = p;
584 set_head (top_chunk, new_size | PREV_INUSE);
585 /*check_chunk(ar_ptr, top_chunk);*/
fa8d436c 586 }
c26efef9
MG
587
588 /* Uses similar logic for per-thread arenas as the main arena with systrim
e4bc326d
CD
589 and _int_free by preserving the top pad and rounding down to the nearest
590 page. */
6c8dbf00 591 top_size = chunksize (top_chunk);
e4bc326d
CD
592 if ((unsigned long)(top_size) <
593 (unsigned long)(mp_.trim_threshold))
594 return 0;
595
c26efef9 596 top_area = top_size - MINSIZE - 1;
f8ef472c 597 if (top_area < 0 || (size_t) top_area <= pad)
c26efef9
MG
598 return 0;
599
e4bc326d 600 /* Release in pagesize units and round down to the nearest page. */
c26efef9 601 extra = ALIGN_DOWN(top_area - pad, pagesz);
e4bc326d 602 if (extra == 0)
fa8d436c 603 return 0;
6c8dbf00 604
fa8d436c 605 /* Try to shrink. */
6c8dbf00 606 if (shrink_heap (heap, extra) != 0)
fa8d436c 607 return 0;
6c8dbf00 608
fa8d436c 609 ar_ptr->system_mem -= extra;
fa8d436c
UD
610
611 /* Success. Adjust top accordingly. */
6c8dbf00 612 set_head (top_chunk, (top_size - extra) | PREV_INUSE);
fa8d436c
UD
613 /*check_chunk(ar_ptr, top_chunk);*/
614 return 1;
615}
616
04ec80e4
UD
617/* Create a new arena with initial size "size". */
618
a62719ba 619/* If REPLACED_ARENA is not NULL, detach it from this thread. Must be
90c400bd 620 called while free_list_lock is held. */
a62719ba
FW
621static void
622detach_arena (mstate replaced_arena)
623{
624 if (replaced_arena != NULL)
625 {
626 assert (replaced_arena->attached_threads > 0);
627 /* The current implementation only detaches from main_arena in
628 case of allocation failure. This means that it is likely not
629 beneficial to put the arena on free_list even if the
630 reference count reaches zero. */
631 --replaced_arena->attached_threads;
632 }
633}
634
04ec80e4 635static mstate
6c8dbf00 636_int_new_arena (size_t size)
04ec80e4
UD
637{
638 mstate a;
639 heap_info *h;
640 char *ptr;
641 unsigned long misalign;
642
6c8dbf00
OB
643 h = new_heap (size + (sizeof (*h) + sizeof (*a) + MALLOC_ALIGNMENT),
644 mp_.top_pad);
645 if (!h)
646 {
647 /* Maybe size is too large to fit in a single heap. So, just try
648 to create a minimally-sized arena and let _int_malloc() attempt
649 to deal with the large request via mmap_chunk(). */
650 h = new_heap (sizeof (*h) + sizeof (*a) + MALLOC_ALIGNMENT, mp_.top_pad);
651 if (!h)
652 return 0;
653 }
654 a = h->ar_ptr = (mstate) (h + 1);
655 malloc_init_state (a);
a62719ba 656 a->attached_threads = 1;
04ec80e4
UD
657 /*a->next = NULL;*/
658 a->system_mem = a->max_system_mem = h->size;
04ec80e4
UD
659
660 /* Set up the top chunk, with proper alignment. */
6c8dbf00
OB
661 ptr = (char *) (a + 1);
662 misalign = (unsigned long) chunk2mem (ptr) & MALLOC_ALIGN_MASK;
04ec80e4
UD
663 if (misalign > 0)
664 ptr += MALLOC_ALIGNMENT - misalign;
6c8dbf00
OB
665 top (a) = (mchunkptr) ptr;
666 set_head (top (a), (((char *) h + h->size) - ptr) | PREV_INUSE);
04ec80e4 667
3ea5be54 668 LIBC_PROBE (memory_arena_new, 2, a, size);
a62719ba 669 mstate replaced_arena = thread_arena;
6782806d 670 thread_arena = a;
4bf5f222 671 __libc_lock_init (a->mutex);
425ce2ed 672
4bf5f222 673 __libc_lock_lock (list_lock);
425ce2ed
UD
674
675 /* Add the new arena to the global list. */
676 a->next = main_arena.next;
90c400bd
FW
677 /* FIXME: The barrier is an attempt to synchronize with read access
678 in reused_arena, which does not acquire list_lock while
679 traversing the list. */
425ce2ed
UD
680 atomic_write_barrier ();
681 main_arena.next = a;
682
4bf5f222 683 __libc_lock_unlock (list_lock);
425ce2ed 684
4bf5f222 685 __libc_lock_lock (free_list_lock);
90c400bd 686 detach_arena (replaced_arena);
4bf5f222 687 __libc_lock_unlock (free_list_lock);
90c400bd
FW
688
689 /* Lock this arena. NB: Another thread may have been attached to
690 this arena because the arena is now accessible from the
691 main_arena.next list and could have been picked by reused_arena.
692 This can only happen for the last arena created (before the arena
693 limit is reached). At this point, some arena has to be attached
694 to two threads. We could acquire the arena lock before list_lock
695 to make it less likely that reused_arena picks this new arena,
29d79486
FW
696 but this could result in a deadlock with
697 __malloc_fork_lock_parent. */
90c400bd 698
4bf5f222 699 __libc_lock_lock (a->mutex);
90c400bd 700
04ec80e4
UD
701 return a;
702}
703
425ce2ed 704
f88aab5d 705/* Remove an arena from free_list. */
425ce2ed
UD
706static mstate
707get_free_list (void)
708{
a62719ba 709 mstate replaced_arena = thread_arena;
425ce2ed
UD
710 mstate result = free_list;
711 if (result != NULL)
712 {
4bf5f222 713 __libc_lock_lock (free_list_lock);
425ce2ed
UD
714 result = free_list;
715 if (result != NULL)
a62719ba
FW
716 {
717 free_list = result->next_free;
718
3da825ce 719 /* The arena will be attached to this thread. */
f88aab5d
FW
720 assert (result->attached_threads == 0);
721 result->attached_threads = 1;
a62719ba
FW
722
723 detach_arena (replaced_arena);
724 }
4bf5f222 725 __libc_lock_unlock (free_list_lock);
425ce2ed
UD
726
727 if (result != NULL)
6c8dbf00
OB
728 {
729 LIBC_PROBE (memory_arena_reuse_free_list, 1, result);
4bf5f222 730 __libc_lock_lock (result->mutex);
6782806d 731 thread_arena = result;
6c8dbf00 732 }
425ce2ed
UD
733 }
734
735 return result;
736}
737
f88aab5d
FW
738/* Remove the arena from the free list (if it is present).
739 free_list_lock must have been acquired by the caller. */
740static void
741remove_from_free_list (mstate arena)
742{
743 mstate *previous = &free_list;
744 for (mstate p = free_list; p != NULL; p = p->next_free)
745 {
746 assert (p->attached_threads == 0);
747 if (p == arena)
748 {
749 /* Remove the requested arena from the list. */
750 *previous = p->next_free;
751 break;
752 }
753 else
754 previous = &p->next_free;
755 }
756}
757
77480c6b 758/* Lock and return an arena that can be reused for memory allocation.
bf51f568
JL
759 Avoid AVOID_ARENA as we have already failed to allocate memory in
760 it and it is currently locked. */
425ce2ed 761static mstate
bf51f568 762reused_arena (mstate avoid_arena)
425ce2ed 763{
425ce2ed 764 mstate result;
90c400bd 765 /* FIXME: Access to next_to_use suffers from data races. */
425ce2ed
UD
766 static mstate next_to_use;
767 if (next_to_use == NULL)
768 next_to_use = &main_arena;
769
3da825ce
FW
770 /* Iterate over all arenas (including those linked from
771 free_list). */
425ce2ed
UD
772 result = next_to_use;
773 do
774 {
4bf5f222 775 if (!arena_is_corrupt (result) && !__libc_lock_trylock (result->mutex))
6c8dbf00 776 goto out;
425ce2ed 777
90c400bd 778 /* FIXME: This is a data race, see _int_new_arena. */
425ce2ed
UD
779 result = result->next;
780 }
781 while (result != next_to_use);
782
bf51f568
JL
783 /* Avoid AVOID_ARENA as we have already failed to allocate memory
784 in that arena and it is currently locked. */
785 if (result == avoid_arena)
786 result = result->next;
787
fff94fa2
SP
788 /* Make sure that the arena we get is not corrupted. */
789 mstate begin = result;
790 while (arena_is_corrupt (result) || result == avoid_arena)
791 {
792 result = result->next;
793 if (result == begin)
a3b47337
FW
794 /* We looped around the arena list. We could not find any
795 arena that was either not corrupted or not the one we
796 wanted to avoid. */
797 return NULL;
fff94fa2
SP
798 }
799
fff94fa2 800 /* No arena available without contention. Wait for the next in line. */
6999d38c 801 LIBC_PROBE (memory_arena_reuse_wait, 3, &result->mutex, result, avoid_arena);
4bf5f222 802 __libc_lock_lock (result->mutex);
425ce2ed 803
6c8dbf00 804out:
f88aab5d 805 /* Attach the arena to the current thread. */
a62719ba 806 {
90c400bd 807 /* Update the arena thread attachment counters. */
a62719ba 808 mstate replaced_arena = thread_arena;
4bf5f222 809 __libc_lock_lock (free_list_lock);
a62719ba 810 detach_arena (replaced_arena);
f88aab5d
FW
811
812 /* We may have picked up an arena on the free list. We need to
813 preserve the invariant that no arena on the free list has a
814 positive attached_threads counter (otherwise,
815 arena_thread_freeres cannot use the counter to determine if the
816 arena needs to be put on the free list). We unconditionally
817 remove the selected arena from the free list. The caller of
818 reused_arena checked the free list and observed it to be empty,
819 so the list is very short. */
820 remove_from_free_list (result);
821
a62719ba 822 ++result->attached_threads;
f88aab5d 823
4bf5f222 824 __libc_lock_unlock (free_list_lock);
a62719ba
FW
825 }
826
6999d38c 827 LIBC_PROBE (memory_arena_reuse, 2, result, avoid_arena);
6782806d 828 thread_arena = result;
425ce2ed
UD
829 next_to_use = result->next;
830
831 return result;
832}
425ce2ed 833
fa8d436c
UD
834static mstate
835internal_function
92a9b22d 836arena_get2 (size_t size, mstate avoid_arena)
fa8d436c
UD
837{
838 mstate a;
fa8d436c 839
77cdc054
AS
840 static size_t narenas_limit;
841
842 a = get_free_list ();
843 if (a == NULL)
844 {
845 /* Nothing immediately available, so generate a new arena. */
846 if (narenas_limit == 0)
6c8dbf00
OB
847 {
848 if (mp_.arena_max != 0)
849 narenas_limit = mp_.arena_max;
850 else if (narenas > mp_.arena_test)
851 {
852 int n = __get_nprocs ();
853
854 if (n >= 1)
855 narenas_limit = NARENAS_FROM_NCORES (n);
856 else
857 /* We have no information about the system. Assume two
858 cores. */
859 narenas_limit = NARENAS_FROM_NCORES (2);
860 }
861 }
77cdc054
AS
862 repeat:;
863 size_t n = narenas;
41b81892 864 /* NB: the following depends on the fact that (size_t)0 - 1 is a
6c8dbf00
OB
865 very large number and that the underflow is OK. If arena_max
866 is set the value of arena_test is irrelevant. If arena_test
867 is set but narenas is not yet larger or equal to arena_test
868 narenas_limit is 0. There is no possibility for narenas to
869 be too big for the test to always fail since there is not
870 enough address space to create that many arenas. */
a1ffb40e 871 if (__glibc_unlikely (n <= narenas_limit - 1))
6c8dbf00
OB
872 {
873 if (catomic_compare_and_exchange_bool_acq (&narenas, n + 1, n))
874 goto repeat;
875 a = _int_new_arena (size);
a1ffb40e 876 if (__glibc_unlikely (a == NULL))
6c8dbf00
OB
877 catomic_decrement (&narenas);
878 }
a5fb313c 879 else
6c8dbf00 880 a = reused_arena (avoid_arena);
77cdc054 881 }
fa8d436c
UD
882 return a;
883}
884
c78ab094
SP
885/* If we don't have the main arena, then maybe the failure is due to running
886 out of mmapped areas, so we can try allocating on the main arena.
887 Otherwise, it is likely that sbrk() has failed and there is still a chance
888 to mmap(), so try one of the other arenas. */
889static mstate
890arena_get_retry (mstate ar_ptr, size_t bytes)
891{
655673f3 892 LIBC_PROBE (memory_arena_retry, 2, bytes, ar_ptr);
6c8dbf00
OB
893 if (ar_ptr != &main_arena)
894 {
4bf5f222 895 __libc_lock_unlock (ar_ptr->mutex);
c3b9ef8d
SP
896 /* Don't touch the main arena if it is corrupt. */
897 if (arena_is_corrupt (&main_arena))
898 return NULL;
899
6c8dbf00 900 ar_ptr = &main_arena;
4bf5f222 901 __libc_lock_lock (ar_ptr->mutex);
6c8dbf00
OB
902 }
903 else
904 {
4bf5f222 905 __libc_lock_unlock (ar_ptr->mutex);
92a9b22d 906 ar_ptr = arena_get2 (bytes, ar_ptr);
6c8dbf00 907 }
c78ab094
SP
908
909 return ar_ptr;
910}
911
425ce2ed
UD
912static void __attribute__ ((section ("__libc_thread_freeres_fn")))
913arena_thread_freeres (void)
914{
6782806d
FW
915 mstate a = thread_arena;
916 thread_arena = NULL;
425ce2ed
UD
917
918 if (a != NULL)
919 {
4bf5f222 920 __libc_lock_lock (free_list_lock);
a62719ba
FW
921 /* If this was the last attached thread for this arena, put the
922 arena on the free list. */
923 assert (a->attached_threads > 0);
924 if (--a->attached_threads == 0)
925 {
926 a->next_free = free_list;
927 free_list = a;
928 }
4bf5f222 929 __libc_lock_unlock (free_list_lock);
425ce2ed
UD
930 }
931}
932text_set_element (__libc_thread_subfreeres, arena_thread_freeres);
425ce2ed 933
fa8d436c
UD
934/*
935 * Local variables:
936 * c-basic-offset: 2
937 * End:
938 */