2.5-18.1
[glibc.git] / malloc / arena.c
blob0dcb7cb9f85e482c5f09d90e60e455bf10b81c2a
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 2001,2002,2003,2004,2005,2006,2007
3 Free Software Foundation, Inc.
4 This file is part of the GNU C Library.
5 Contributed by Wolfram Gloger <wg@malloc.de>, 2001.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public License as
9 published by the Free Software Foundation; either version 2.1 of the
10 License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If not,
19 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 #include <stdbool.h>
24 /* Compile-time constants. */
26 #define HEAP_MIN_SIZE (32*1024)
27 #ifndef HEAP_MAX_SIZE
28 # ifdef DEFAULT_MMAP_THRESHOLD_MAX
29 # define HEAP_MAX_SIZE (2 * DEFAULT_MMAP_THRESHOLD_MAX)
30 # else
31 # define HEAP_MAX_SIZE (1024*1024) /* must be a power of two */
32 # endif
33 #endif
35 /* HEAP_MIN_SIZE and HEAP_MAX_SIZE limit the size of mmap()ed heaps
36 that are dynamically created for multi-threaded programs. The
37 maximum size must be a power of two, for fast determination of
38 which heap belongs to a chunk. It should be much larger than the
39 mmap threshold, so that requests with a size just below that
40 threshold can be fulfilled without creating too many heaps. */
43 #ifndef THREAD_STATS
44 #define THREAD_STATS 0
45 #endif
47 /* If THREAD_STATS is non-zero, some statistics on mutex locking are
48 computed. */
50 /***************************************************************************/
52 #define top(ar_ptr) ((ar_ptr)->top)
54 /* A heap is a single contiguous memory region holding (coalesceable)
55 malloc_chunks. It is allocated with mmap() and always starts at an
56 address aligned to HEAP_MAX_SIZE. Not used unless compiling with
57 USE_ARENAS. */
59 typedef struct _heap_info {
60 mstate ar_ptr; /* Arena for this heap. */
61 struct _heap_info *prev; /* Previous heap. */
62 size_t size; /* Current size in bytes. */
63 size_t mprotect_size; /* Size in bytes that has been mprotected
64 PROT_READ|PROT_WRITE. */
65 /* Make sure the following data is properly aligned, particularly
66 that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of
67 MALLOC_ALIGNMENT. */
68 char pad[-6 * SIZE_SZ & MALLOC_ALIGN_MASK];
69 } heap_info;
71 /* Get a compile-time error if the heap_info padding is not correct
72 to make alignment work as expected in sYSMALLOc. */
73 extern int sanity_check_heap_info_alignment[(sizeof (heap_info)
74 + 2 * SIZE_SZ) % MALLOC_ALIGNMENT
75 ? -1 : 1];
77 /* Thread specific data */
79 static tsd_key_t arena_key;
80 static mutex_t list_lock;
82 #if THREAD_STATS
83 static int stat_n_heaps;
84 #define THREAD_STAT(x) x
85 #else
86 #define THREAD_STAT(x) do ; while(0)
87 #endif
89 /* Mapped memory in non-main arenas (reliable only for NO_THREADS). */
90 static unsigned long arena_mem;
92 /* Already initialized? */
93 int __malloc_initialized = -1;
95 /**************************************************************************/
97 #if USE_ARENAS
99 /* arena_get() acquires an arena and locks the corresponding mutex.
100 First, try the one last locked successfully by this thread. (This
101 is the common case and handled with a macro for speed.) Then, loop
102 once over the circularly linked list of arenas. If no arena is
103 readily available, create a new one. In this latter case, `size'
104 is just a hint as to how much memory will be required immediately
105 in the new arena. */
107 #define arena_get(ptr, size) do { \
108 Void_t *vptr = NULL; \
109 ptr = (mstate)tsd_getspecific(arena_key, vptr); \
110 if(ptr && !mutex_trylock(&ptr->mutex)) { \
111 THREAD_STAT(++(ptr->stat_lock_direct)); \
112 } else \
113 ptr = arena_get2(ptr, (size)); \
114 } while(0)
116 /* find the heap and corresponding arena for a given ptr */
118 #define heap_for_ptr(ptr) \
119 ((heap_info *)((unsigned long)(ptr) & ~(HEAP_MAX_SIZE-1)))
120 #define arena_for_chunk(ptr) \
121 (chunk_non_main_arena(ptr) ? heap_for_ptr(ptr)->ar_ptr : &main_arena)
123 #else /* !USE_ARENAS */
125 /* There is only one arena, main_arena. */
127 #if THREAD_STATS
128 #define arena_get(ar_ptr, sz) do { \
129 ar_ptr = &main_arena; \
130 if(!mutex_trylock(&ar_ptr->mutex)) \
131 ++(ar_ptr->stat_lock_direct); \
132 else { \
133 (void)mutex_lock(&ar_ptr->mutex); \
134 ++(ar_ptr->stat_lock_wait); \
136 } while(0)
137 #else
138 #define arena_get(ar_ptr, sz) do { \
139 ar_ptr = &main_arena; \
140 (void)mutex_lock(&ar_ptr->mutex); \
141 } while(0)
142 #endif
143 #define arena_for_chunk(ptr) (&main_arena)
145 #endif /* USE_ARENAS */
147 /**************************************************************************/
149 #ifndef NO_THREADS
151 /* atfork support. */
153 static __malloc_ptr_t (*save_malloc_hook) (size_t __size,
154 __const __malloc_ptr_t);
155 # if !defined _LIBC || !defined USE_TLS || (defined SHARED && !USE___THREAD)
156 static __malloc_ptr_t (*save_memalign_hook) (size_t __align, size_t __size,
157 __const __malloc_ptr_t);
158 # endif
159 static void (*save_free_hook) (__malloc_ptr_t __ptr,
160 __const __malloc_ptr_t);
161 static Void_t* save_arena;
163 /* Magic value for the thread-specific arena pointer when
164 malloc_atfork() is in use. */
166 #define ATFORK_ARENA_PTR ((Void_t*)-1)
168 /* The following hooks are used while the `atfork' handling mechanism
169 is active. */
171 static Void_t*
172 malloc_atfork(size_t sz, const Void_t *caller)
174 Void_t *vptr = NULL;
175 Void_t *victim;
177 tsd_getspecific(arena_key, vptr);
178 if(vptr == ATFORK_ARENA_PTR) {
179 /* We are the only thread that may allocate at all. */
180 if(save_malloc_hook != malloc_check) {
181 return _int_malloc(&main_arena, sz);
182 } else {
183 if(top_check()<0)
184 return 0;
185 victim = _int_malloc(&main_arena, sz+1);
186 return mem2mem_check(victim, sz);
188 } else {
189 /* Suspend the thread until the `atfork' handlers have completed.
190 By that time, the hooks will have been reset as well, so that
191 mALLOc() can be used again. */
192 (void)mutex_lock(&list_lock);
193 (void)mutex_unlock(&list_lock);
194 return public_mALLOc(sz);
198 static void
199 free_atfork(Void_t* mem, const Void_t *caller)
201 Void_t *vptr = NULL;
202 mstate ar_ptr;
203 mchunkptr p; /* chunk corresponding to mem */
205 if (mem == 0) /* free(0) has no effect */
206 return;
208 p = mem2chunk(mem); /* do not bother to replicate free_check here */
210 #if HAVE_MMAP
211 if (chunk_is_mmapped(p)) /* release mmapped memory. */
213 munmap_chunk(p);
214 return;
216 #endif
218 ar_ptr = arena_for_chunk(p);
219 tsd_getspecific(arena_key, vptr);
220 if(vptr != ATFORK_ARENA_PTR)
221 (void)mutex_lock(&ar_ptr->mutex);
222 _int_free(ar_ptr, mem);
223 if(vptr != ATFORK_ARENA_PTR)
224 (void)mutex_unlock(&ar_ptr->mutex);
228 /* Counter for number of times the list is locked by the same thread. */
229 static unsigned int atfork_recursive_cntr;
231 /* The following two functions are registered via thread_atfork() to
232 make sure that the mutexes remain in a consistent state in the
233 fork()ed version of a thread. Also adapt the malloc and free hooks
234 temporarily, because the `atfork' handler mechanism may use
235 malloc/free internally (e.g. in LinuxThreads). */
237 static void
238 ptmalloc_lock_all (void)
240 mstate ar_ptr;
242 if(__malloc_initialized < 1)
243 return;
244 if (mutex_trylock(&list_lock))
246 Void_t *my_arena;
247 tsd_getspecific(arena_key, my_arena);
248 if (my_arena == ATFORK_ARENA_PTR)
249 /* This is the same thread which already locks the global list.
250 Just bump the counter. */
251 goto out;
253 /* This thread has to wait its turn. */
254 (void)mutex_lock(&list_lock);
256 for(ar_ptr = &main_arena;;) {
257 (void)mutex_lock(&ar_ptr->mutex);
258 ar_ptr = ar_ptr->next;
259 if(ar_ptr == &main_arena) break;
261 save_malloc_hook = __malloc_hook;
262 save_free_hook = __free_hook;
263 __malloc_hook = malloc_atfork;
264 __free_hook = free_atfork;
265 /* Only the current thread may perform malloc/free calls now. */
266 tsd_getspecific(arena_key, save_arena);
267 tsd_setspecific(arena_key, ATFORK_ARENA_PTR);
268 out:
269 ++atfork_recursive_cntr;
272 static void
273 ptmalloc_unlock_all (void)
275 mstate ar_ptr;
277 if(__malloc_initialized < 1)
278 return;
279 if (--atfork_recursive_cntr != 0)
280 return;
281 tsd_setspecific(arena_key, save_arena);
282 __malloc_hook = save_malloc_hook;
283 __free_hook = save_free_hook;
284 for(ar_ptr = &main_arena;;) {
285 (void)mutex_unlock(&ar_ptr->mutex);
286 ar_ptr = ar_ptr->next;
287 if(ar_ptr == &main_arena) break;
289 (void)mutex_unlock(&list_lock);
292 #ifdef __linux__
294 /* In NPTL, unlocking a mutex in the child process after a
295 fork() is currently unsafe, whereas re-initializing it is safe and
296 does not leak resources. Therefore, a special atfork handler is
297 installed for the child. */
299 static void
300 ptmalloc_unlock_all2 (void)
302 mstate ar_ptr;
304 if(__malloc_initialized < 1)
305 return;
306 #if defined _LIBC || defined MALLOC_HOOKS
307 tsd_setspecific(arena_key, save_arena);
308 __malloc_hook = save_malloc_hook;
309 __free_hook = save_free_hook;
310 #endif
311 for(ar_ptr = &main_arena;;) {
312 mutex_init(&ar_ptr->mutex);
313 ar_ptr = ar_ptr->next;
314 if(ar_ptr == &main_arena) break;
316 mutex_init(&list_lock);
317 atfork_recursive_cntr = 0;
320 #else
322 #define ptmalloc_unlock_all2 ptmalloc_unlock_all
324 #endif
326 #endif /* !defined NO_THREADS */
328 /* Initialization routine. */
329 #ifdef _LIBC
330 #include <string.h>
331 extern char **_environ;
333 static char *
334 internal_function
335 next_env_entry (char ***position)
337 char **current = *position;
338 char *result = NULL;
340 while (*current != NULL)
342 if (__builtin_expect ((*current)[0] == 'M', 0)
343 && (*current)[1] == 'A'
344 && (*current)[2] == 'L'
345 && (*current)[3] == 'L'
346 && (*current)[4] == 'O'
347 && (*current)[5] == 'C'
348 && (*current)[6] == '_')
350 result = &(*current)[7];
352 /* Save current position for next visit. */
353 *position = ++current;
355 break;
358 ++current;
361 return result;
363 #endif /* _LIBC */
365 /* Set up basic state so that _int_malloc et al can work. */
366 static void
367 ptmalloc_init_minimal (void)
369 #if DEFAULT_TOP_PAD != 0
370 mp_.top_pad = DEFAULT_TOP_PAD;
371 #endif
372 mp_.n_mmaps_max = DEFAULT_MMAP_MAX;
373 mp_.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
374 mp_.trim_threshold = DEFAULT_TRIM_THRESHOLD;
375 mp_.pagesize = malloc_getpagesize;
379 #ifdef _LIBC
380 # ifdef SHARED
381 static void *
382 __failing_morecore (ptrdiff_t d)
384 return (void *) MORECORE_FAILURE;
387 extern struct dl_open_hook *_dl_open_hook;
388 libc_hidden_proto (_dl_open_hook);
389 # endif
391 # if defined SHARED && defined USE_TLS && !USE___THREAD
392 /* This is called by __pthread_initialize_minimal when it needs to use
393 malloc to set up the TLS state. We cannot do the full work of
394 ptmalloc_init (below) until __pthread_initialize_minimal has finished,
395 so it has to switch to using the special startup-time hooks while doing
396 those allocations. */
397 void
398 __libc_malloc_pthread_startup (bool first_time)
400 if (first_time)
402 ptmalloc_init_minimal ();
403 save_malloc_hook = __malloc_hook;
404 save_memalign_hook = __memalign_hook;
405 save_free_hook = __free_hook;
406 __malloc_hook = malloc_starter;
407 __memalign_hook = memalign_starter;
408 __free_hook = free_starter;
410 else
412 __malloc_hook = save_malloc_hook;
413 __memalign_hook = save_memalign_hook;
414 __free_hook = save_free_hook;
417 # endif
418 #endif
420 static void
421 ptmalloc_init (void)
423 #if __STD_C
424 const char* s;
425 #else
426 char* s;
427 #endif
428 int secure = 0;
430 if(__malloc_initialized >= 0) return;
431 __malloc_initialized = 0;
433 #ifdef _LIBC
434 # if defined SHARED && defined USE_TLS && !USE___THREAD
435 /* ptmalloc_init_minimal may already have been called via
436 __libc_malloc_pthread_startup, above. */
437 if (mp_.pagesize == 0)
438 # endif
439 #endif
440 ptmalloc_init_minimal();
442 #ifndef NO_THREADS
443 # if defined _LIBC && defined USE_TLS
444 /* We know __pthread_initialize_minimal has already been called,
445 and that is enough. */
446 # define NO_STARTER
447 # endif
448 # ifndef NO_STARTER
449 /* With some threads implementations, creating thread-specific data
450 or initializing a mutex may call malloc() itself. Provide a
451 simple starter version (realloc() won't work). */
452 save_malloc_hook = __malloc_hook;
453 save_memalign_hook = __memalign_hook;
454 save_free_hook = __free_hook;
455 __malloc_hook = malloc_starter;
456 __memalign_hook = memalign_starter;
457 __free_hook = free_starter;
458 # ifdef _LIBC
459 /* Initialize the pthreads interface. */
460 if (__pthread_initialize != NULL)
461 __pthread_initialize();
462 # endif /* !defined _LIBC */
463 # endif /* !defined NO_STARTER */
464 #endif /* !defined NO_THREADS */
465 mutex_init(&main_arena.mutex);
466 main_arena.next = &main_arena;
468 #if defined _LIBC && defined SHARED
469 /* In case this libc copy is in a non-default namespace, never use brk.
470 Likewise if dlopened from statically linked program. */
471 Dl_info di;
472 struct link_map *l;
474 if (_dl_open_hook != NULL
475 || (_dl_addr (ptmalloc_init, &di, &l, NULL) != 0
476 && l->l_ns != LM_ID_BASE))
477 __morecore = __failing_morecore;
478 #endif
480 mutex_init(&list_lock);
481 tsd_key_create(&arena_key, NULL);
482 tsd_setspecific(arena_key, (Void_t *)&main_arena);
483 thread_atfork(ptmalloc_lock_all, ptmalloc_unlock_all, ptmalloc_unlock_all2);
484 #ifndef NO_THREADS
485 # ifndef NO_STARTER
486 __malloc_hook = save_malloc_hook;
487 __memalign_hook = save_memalign_hook;
488 __free_hook = save_free_hook;
489 # else
490 # undef NO_STARTER
491 # endif
492 #endif
493 #ifdef _LIBC
494 secure = __libc_enable_secure;
495 s = NULL;
496 if (__builtin_expect (_environ != NULL, 1))
498 char **runp = _environ;
499 char *envline;
501 while (__builtin_expect ((envline = next_env_entry (&runp)) != NULL,
504 size_t len = strcspn (envline, "=");
506 if (envline[len] != '=')
507 /* This is a "MALLOC_" variable at the end of the string
508 without a '=' character. Ignore it since otherwise we
509 will access invalid memory below. */
510 continue;
512 switch (len)
514 case 6:
515 if (memcmp (envline, "CHECK_", 6) == 0)
516 s = &envline[7];
517 break;
518 case 8:
519 if (! secure)
521 if (memcmp (envline, "TOP_PAD_", 8) == 0)
522 mALLOPt(M_TOP_PAD, atoi(&envline[9]));
523 else if (memcmp (envline, "PERTURB_", 8) == 0)
524 mALLOPt(M_PERTURB, atoi(&envline[9]));
526 break;
527 case 9:
528 if (! secure && memcmp (envline, "MMAP_MAX_", 9) == 0)
529 mALLOPt(M_MMAP_MAX, atoi(&envline[10]));
530 break;
531 case 15:
532 if (! secure)
534 if (memcmp (envline, "TRIM_THRESHOLD_", 15) == 0)
535 mALLOPt(M_TRIM_THRESHOLD, atoi(&envline[16]));
536 else if (memcmp (envline, "MMAP_THRESHOLD_", 15) == 0)
537 mALLOPt(M_MMAP_THRESHOLD, atoi(&envline[16]));
539 break;
540 default:
541 break;
545 #else
546 if (! secure)
548 if((s = getenv("MALLOC_TRIM_THRESHOLD_")))
549 mALLOPt(M_TRIM_THRESHOLD, atoi(s));
550 if((s = getenv("MALLOC_TOP_PAD_")))
551 mALLOPt(M_TOP_PAD, atoi(s));
552 if((s = getenv("MALLOC_PERTURB_")))
553 mALLOPt(M_PERTURB, atoi(s));
554 if((s = getenv("MALLOC_MMAP_THRESHOLD_")))
555 mALLOPt(M_MMAP_THRESHOLD, atoi(s));
556 if((s = getenv("MALLOC_MMAP_MAX_")))
557 mALLOPt(M_MMAP_MAX, atoi(s));
559 s = getenv("MALLOC_CHECK_");
560 #endif
561 if(s && s[0]) {
562 mALLOPt(M_CHECK_ACTION, (int)(s[0] - '0'));
563 if (check_action != 0)
564 __malloc_check_init();
566 if(__malloc_initialize_hook != NULL)
567 (*__malloc_initialize_hook)();
568 __malloc_initialized = 1;
571 /* There are platforms (e.g. Hurd) with a link-time hook mechanism. */
572 #ifdef thread_atfork_static
573 thread_atfork_static(ptmalloc_lock_all, ptmalloc_unlock_all, \
574 ptmalloc_unlock_all2)
575 #endif
579 /* Managing heaps and arenas (for concurrent threads) */
581 #if USE_ARENAS
583 #if MALLOC_DEBUG > 1
585 /* Print the complete contents of a single heap to stderr. */
587 static void
588 #if __STD_C
589 dump_heap(heap_info *heap)
590 #else
591 dump_heap(heap) heap_info *heap;
592 #endif
594 char *ptr;
595 mchunkptr p;
597 fprintf(stderr, "Heap %p, size %10lx:\n", heap, (long)heap->size);
598 ptr = (heap->ar_ptr != (mstate)(heap+1)) ?
599 (char*)(heap + 1) : (char*)(heap + 1) + sizeof(struct malloc_state);
600 p = (mchunkptr)(((unsigned long)ptr + MALLOC_ALIGN_MASK) &
601 ~MALLOC_ALIGN_MASK);
602 for(;;) {
603 fprintf(stderr, "chunk %p size %10lx", p, (long)p->size);
604 if(p == top(heap->ar_ptr)) {
605 fprintf(stderr, " (top)\n");
606 break;
607 } else if(p->size == (0|PREV_INUSE)) {
608 fprintf(stderr, " (fence)\n");
609 break;
611 fprintf(stderr, "\n");
612 p = next_chunk(p);
616 #endif /* MALLOC_DEBUG > 1 */
618 /* If consecutive mmap (0, HEAP_MAX_SIZE << 1, ...) calls return decreasing
619 addresses as opposed to increasing, new_heap would badly fragment the
620 address space. In that case remember the second HEAP_MAX_SIZE part
621 aligned to HEAP_MAX_SIZE from last mmap (0, HEAP_MAX_SIZE << 1, ...)
622 call (if it is already aligned) and try to reuse it next time. We need
623 no locking for it, as kernel ensures the atomicity for us - worst case
624 we'll call mmap (addr, HEAP_MAX_SIZE, ...) for some value of addr in
625 multiple threads, but only one will succeed. */
626 static char *aligned_heap_area;
628 /* Create a new heap. size is automatically rounded up to a multiple
629 of the page size. */
631 static heap_info *
632 internal_function
633 #if __STD_C
634 new_heap(size_t size, size_t top_pad)
635 #else
636 new_heap(size, top_pad) size_t size, top_pad;
637 #endif
639 size_t page_mask = malloc_getpagesize - 1;
640 char *p1, *p2;
641 unsigned long ul;
642 heap_info *h;
644 if(size+top_pad < HEAP_MIN_SIZE)
645 size = HEAP_MIN_SIZE;
646 else if(size+top_pad <= HEAP_MAX_SIZE)
647 size += top_pad;
648 else if(size > HEAP_MAX_SIZE)
649 return 0;
650 else
651 size = HEAP_MAX_SIZE;
652 size = (size + page_mask) & ~page_mask;
654 /* A memory region aligned to a multiple of HEAP_MAX_SIZE is needed.
655 No swap space needs to be reserved for the following large
656 mapping (on Linux, this is the case for all non-writable mappings
657 anyway). */
658 p2 = MAP_FAILED;
659 if(aligned_heap_area) {
660 p2 = (char *)MMAP(aligned_heap_area, HEAP_MAX_SIZE, PROT_NONE,
661 MAP_PRIVATE|MAP_NORESERVE);
662 aligned_heap_area = NULL;
663 if (p2 != MAP_FAILED && ((unsigned long)p2 & (HEAP_MAX_SIZE-1))) {
664 munmap(p2, HEAP_MAX_SIZE);
665 p2 = MAP_FAILED;
668 if(p2 == MAP_FAILED) {
669 p1 = (char *)MMAP(0, HEAP_MAX_SIZE<<1, PROT_NONE,
670 MAP_PRIVATE|MAP_NORESERVE);
671 if(p1 != MAP_FAILED) {
672 p2 = (char *)(((unsigned long)p1 + (HEAP_MAX_SIZE-1))
673 & ~(HEAP_MAX_SIZE-1));
674 ul = p2 - p1;
675 if (ul)
676 munmap(p1, ul);
677 else
678 aligned_heap_area = p2 + HEAP_MAX_SIZE;
679 munmap(p2 + HEAP_MAX_SIZE, HEAP_MAX_SIZE - ul);
680 } else {
681 /* Try to take the chance that an allocation of only HEAP_MAX_SIZE
682 is already aligned. */
683 p2 = (char *)MMAP(0, HEAP_MAX_SIZE, PROT_NONE, MAP_PRIVATE|MAP_NORESERVE);
684 if(p2 == MAP_FAILED)
685 return 0;
686 if((unsigned long)p2 & (HEAP_MAX_SIZE-1)) {
687 munmap(p2, HEAP_MAX_SIZE);
688 return 0;
692 if(mprotect(p2, size, PROT_READ|PROT_WRITE) != 0) {
693 munmap(p2, HEAP_MAX_SIZE);
694 return 0;
696 h = (heap_info *)p2;
697 h->size = size;
698 h->mprotect_size = size;
699 THREAD_STAT(stat_n_heaps++);
700 return h;
703 /* Grow or shrink a heap. size is automatically rounded up to a
704 multiple of the page size if it is positive. */
706 static int
707 #if __STD_C
708 grow_heap(heap_info *h, long diff)
709 #else
710 grow_heap(h, diff) heap_info *h; long diff;
711 #endif
713 size_t page_mask = malloc_getpagesize - 1;
714 long new_size;
716 if(diff >= 0) {
717 diff = (diff + page_mask) & ~page_mask;
718 new_size = (long)h->size + diff;
719 if((unsigned long) new_size > (unsigned long) HEAP_MAX_SIZE)
720 return -1;
721 if((unsigned long) new_size > h->mprotect_size) {
722 if (mprotect((char *)h + h->mprotect_size,
723 (unsigned long) new_size - h->mprotect_size,
724 PROT_READ|PROT_WRITE) != 0)
725 return -2;
726 h->mprotect_size = new_size;
728 } else {
729 new_size = (long)h->size + diff;
730 if(new_size < (long)sizeof(*h))
731 return -1;
732 /* Try to re-map the extra heap space freshly to save memory, and
733 make it inaccessible. */
734 #ifdef _LIBC
735 if (__builtin_expect (__libc_enable_secure, 0))
736 #else
737 if (1)
738 #endif
740 if((char *)MMAP((char *)h + new_size, -diff, PROT_NONE,
741 MAP_PRIVATE|MAP_FIXED) == (char *) MAP_FAILED)
742 return -2;
743 h->mprotect_size = new_size;
745 #ifdef _LIBC
746 else
747 madvise ((char *)h + new_size, -diff, MADV_DONTNEED);
748 #endif
749 /*fprintf(stderr, "shrink %p %08lx\n", h, new_size);*/
751 h->size = new_size;
752 return 0;
755 /* Delete a heap. */
757 #define delete_heap(heap) \
758 do { \
759 if ((char *)(heap) + HEAP_MAX_SIZE == aligned_heap_area) \
760 aligned_heap_area = NULL; \
761 munmap((char*)(heap), HEAP_MAX_SIZE); \
762 } while (0)
764 static int
765 internal_function
766 #if __STD_C
767 heap_trim(heap_info *heap, size_t pad)
768 #else
769 heap_trim(heap, pad) heap_info *heap; size_t pad;
770 #endif
772 mstate ar_ptr = heap->ar_ptr;
773 unsigned long pagesz = mp_.pagesize;
774 mchunkptr top_chunk = top(ar_ptr), p, bck, fwd;
775 heap_info *prev_heap;
776 long new_size, top_size, extra;
778 /* Can this heap go away completely? */
779 while(top_chunk == chunk_at_offset(heap, sizeof(*heap))) {
780 prev_heap = heap->prev;
781 p = chunk_at_offset(prev_heap, prev_heap->size - (MINSIZE-2*SIZE_SZ));
782 assert(p->size == (0|PREV_INUSE)); /* must be fencepost */
783 p = prev_chunk(p);
784 new_size = chunksize(p) + (MINSIZE-2*SIZE_SZ);
785 assert(new_size>0 && new_size<(long)(2*MINSIZE));
786 if(!prev_inuse(p))
787 new_size += p->prev_size;
788 assert(new_size>0 && new_size<HEAP_MAX_SIZE);
789 if(new_size + (HEAP_MAX_SIZE - prev_heap->size) < pad + MINSIZE + pagesz)
790 break;
791 ar_ptr->system_mem -= heap->size;
792 arena_mem -= heap->size;
793 delete_heap(heap);
794 heap = prev_heap;
795 if(!prev_inuse(p)) { /* consolidate backward */
796 p = prev_chunk(p);
797 unlink(p, bck, fwd);
799 assert(((unsigned long)((char*)p + new_size) & (pagesz-1)) == 0);
800 assert( ((char*)p + new_size) == ((char*)heap + heap->size) );
801 top(ar_ptr) = top_chunk = p;
802 set_head(top_chunk, new_size | PREV_INUSE);
803 /*check_chunk(ar_ptr, top_chunk);*/
805 top_size = chunksize(top_chunk);
806 extra = ((top_size - pad - MINSIZE + (pagesz-1))/pagesz - 1) * pagesz;
807 if(extra < (long)pagesz)
808 return 0;
809 /* Try to shrink. */
810 if(grow_heap(heap, -extra) != 0)
811 return 0;
812 ar_ptr->system_mem -= extra;
813 arena_mem -= extra;
815 /* Success. Adjust top accordingly. */
816 set_head(top_chunk, (top_size - extra) | PREV_INUSE);
817 /*check_chunk(ar_ptr, top_chunk);*/
818 return 1;
821 /* Create a new arena with initial size "size". */
823 static mstate
824 _int_new_arena(size_t size)
826 mstate a;
827 heap_info *h;
828 char *ptr;
829 unsigned long misalign;
831 h = new_heap(size + (sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT),
832 mp_.top_pad);
833 if(!h) {
834 /* Maybe size is too large to fit in a single heap. So, just try
835 to create a minimally-sized arena and let _int_malloc() attempt
836 to deal with the large request via mmap_chunk(). */
837 h = new_heap(sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT, mp_.top_pad);
838 if(!h)
839 return 0;
841 a = h->ar_ptr = (mstate)(h+1);
842 malloc_init_state(a);
843 /*a->next = NULL;*/
844 a->system_mem = a->max_system_mem = h->size;
845 arena_mem += h->size;
846 #ifdef NO_THREADS
847 if((unsigned long)(mp_.mmapped_mem + arena_mem + main_arena.system_mem) >
848 mp_.max_total_mem)
849 mp_.max_total_mem = mp_.mmapped_mem + arena_mem + main_arena.system_mem;
850 #endif
852 /* Set up the top chunk, with proper alignment. */
853 ptr = (char *)(a + 1);
854 misalign = (unsigned long)chunk2mem(ptr) & MALLOC_ALIGN_MASK;
855 if (misalign > 0)
856 ptr += MALLOC_ALIGNMENT - misalign;
857 top(a) = (mchunkptr)ptr;
858 set_head(top(a), (((char*)h + h->size) - ptr) | PREV_INUSE);
860 return a;
863 static mstate
864 internal_function
865 #if __STD_C
866 arena_get2(mstate a_tsd, size_t size)
867 #else
868 arena_get2(a_tsd, size) mstate a_tsd; size_t size;
869 #endif
871 mstate a;
873 if(!a_tsd)
874 a = a_tsd = &main_arena;
875 else {
876 a = a_tsd->next;
877 if(!a) {
878 /* This can only happen while initializing the new arena. */
879 (void)mutex_lock(&main_arena.mutex);
880 THREAD_STAT(++(main_arena.stat_lock_wait));
881 return &main_arena;
885 /* Check the global, circularly linked list for available arenas. */
886 bool retried = false;
887 repeat:
888 do {
889 if(!mutex_trylock(&a->mutex)) {
890 if (retried)
891 (void)mutex_unlock(&list_lock);
892 THREAD_STAT(++(a->stat_lock_loop));
893 tsd_setspecific(arena_key, (Void_t *)a);
894 return a;
896 a = a->next;
897 } while(a != a_tsd);
899 /* If not even the list_lock can be obtained, try again. This can
900 happen during `atfork', or for example on systems where thread
901 creation makes it temporarily impossible to obtain _any_
902 locks. */
903 if(!retried && mutex_trylock(&list_lock)) {
904 /* We will block to not run in a busy loop. */
905 (void)mutex_lock(&list_lock);
907 /* Since we blocked there might be an arena available now. */
908 retried = true;
909 a = a_tsd;
910 goto repeat;
913 /* Nothing immediately available, so generate a new arena. */
914 a = _int_new_arena(size);
915 if(a)
917 tsd_setspecific(arena_key, (Void_t *)a);
918 mutex_init(&a->mutex);
919 mutex_lock(&a->mutex); /* remember result */
921 /* Add the new arena to the global list. */
922 a->next = main_arena.next;
923 atomic_write_barrier ();
924 main_arena.next = a;
926 THREAD_STAT(++(a->stat_lock_loop));
928 (void)mutex_unlock(&list_lock);
930 return a;
933 #endif /* USE_ARENAS */
936 * Local variables:
937 * c-basic-offset: 2
938 * End: