1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 2001,2002,2003,2004,2005,2006 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Wolfram Gloger <wg@malloc.de>, 2001.
6 The GNU C Library is free software; you can redistribute it and/or
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
9 License, or (at your option) any later version.
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
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If not,
18 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
23 /* Compile-time constants. */
25 #define HEAP_MIN_SIZE (32*1024)
27 #define HEAP_MAX_SIZE (1024*1024) /* must be a power of two */
30 /* HEAP_MIN_SIZE and HEAP_MAX_SIZE limit the size of mmap()ed heaps
31 that are dynamically created for multi-threaded programs. The
32 maximum size must be a power of two, for fast determination of
33 which heap belongs to a chunk. It should be much larger than the
34 mmap threshold, so that requests with a size just below that
35 threshold can be fulfilled without creating too many heaps. */
39 #define THREAD_STATS 0
42 /* If THREAD_STATS is non-zero, some statistics on mutex locking are
45 /***************************************************************************/
47 #define top(ar_ptr) ((ar_ptr)->top)
49 /* A heap is a single contiguous memory region holding (coalesceable)
50 malloc_chunks. It is allocated with mmap() and always starts at an
51 address aligned to HEAP_MAX_SIZE. Not used unless compiling with
54 typedef struct _heap_info
{
55 mstate ar_ptr
; /* Arena for this heap. */
56 struct _heap_info
*prev
; /* Previous heap. */
57 size_t size
; /* Current size in bytes. */
58 /* Make sure the following data is properly aligned, particularly
59 that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of
61 char pad
[-5 * SIZE_SZ
& MALLOC_ALIGN_MASK
];
64 /* Get a compile-time error if the heap_info padding is not correct
65 to make alignment work as expected in sYSMALLOc. */
66 extern int sanity_check_heap_info_alignment
[(sizeof (heap_info
)
67 + 2 * SIZE_SZ
) % MALLOC_ALIGNMENT
70 /* Thread specific data */
72 static tsd_key_t arena_key
;
73 static mutex_t list_lock
;
76 static int stat_n_heaps
;
77 #define THREAD_STAT(x) x
79 #define THREAD_STAT(x) do ; while(0)
82 /* Mapped memory in non-main arenas (reliable only for NO_THREADS). */
83 static unsigned long arena_mem
;
85 /* Already initialized? */
86 int __malloc_initialized
= -1;
88 /**************************************************************************/
92 /* arena_get() acquires an arena and locks the corresponding mutex.
93 First, try the one last locked successfully by this thread. (This
94 is the common case and handled with a macro for speed.) Then, loop
95 once over the circularly linked list of arenas. If no arena is
96 readily available, create a new one. In this latter case, `size'
97 is just a hint as to how much memory will be required immediately
100 #define arena_get(ptr, size) do { \
101 Void_t *vptr = NULL; \
102 ptr = (mstate)tsd_getspecific(arena_key, vptr); \
103 if(ptr && !mutex_trylock(&ptr->mutex)) { \
104 THREAD_STAT(++(ptr->stat_lock_direct)); \
106 ptr = arena_get2(ptr, (size)); \
109 /* find the heap and corresponding arena for a given ptr */
111 #define heap_for_ptr(ptr) \
112 ((heap_info *)((unsigned long)(ptr) & ~(HEAP_MAX_SIZE-1)))
113 #define arena_for_chunk(ptr) \
114 (chunk_non_main_arena(ptr) ? heap_for_ptr(ptr)->ar_ptr : &main_arena)
116 #else /* !USE_ARENAS */
118 /* There is only one arena, main_arena. */
121 #define arena_get(ar_ptr, sz) do { \
122 ar_ptr = &main_arena; \
123 if(!mutex_trylock(&ar_ptr->mutex)) \
124 ++(ar_ptr->stat_lock_direct); \
126 (void)mutex_lock(&ar_ptr->mutex); \
127 ++(ar_ptr->stat_lock_wait); \
131 #define arena_get(ar_ptr, sz) do { \
132 ar_ptr = &main_arena; \
133 (void)mutex_lock(&ar_ptr->mutex); \
136 #define arena_for_chunk(ptr) (&main_arena)
138 #endif /* USE_ARENAS */
140 /**************************************************************************/
144 /* atfork support. */
146 static __malloc_ptr_t (*save_malloc_hook
) (size_t __size
,
147 __const __malloc_ptr_t
);
148 # if !defined _LIBC || !defined USE_TLS || (defined SHARED && !USE___THREAD)
149 static __malloc_ptr_t (*save_memalign_hook
) (size_t __align
, size_t __size
,
150 __const __malloc_ptr_t
);
152 static void (*save_free_hook
) (__malloc_ptr_t __ptr
,
153 __const __malloc_ptr_t
);
154 static Void_t
* save_arena
;
156 /* Magic value for the thread-specific arena pointer when
157 malloc_atfork() is in use. */
159 #define ATFORK_ARENA_PTR ((Void_t*)-1)
161 /* The following hooks are used while the `atfork' handling mechanism
165 malloc_atfork(size_t sz
, const Void_t
*caller
)
170 tsd_getspecific(arena_key
, vptr
);
171 if(vptr
== ATFORK_ARENA_PTR
) {
172 /* We are the only thread that may allocate at all. */
173 if(save_malloc_hook
!= malloc_check
) {
174 return _int_malloc(&main_arena
, sz
);
178 victim
= _int_malloc(&main_arena
, sz
+1);
179 return mem2mem_check(victim
, sz
);
182 /* Suspend the thread until the `atfork' handlers have completed.
183 By that time, the hooks will have been reset as well, so that
184 mALLOc() can be used again. */
185 (void)mutex_lock(&list_lock
);
186 (void)mutex_unlock(&list_lock
);
187 return public_mALLOc(sz
);
192 free_atfork(Void_t
* mem
, const Void_t
*caller
)
196 mchunkptr p
; /* chunk corresponding to mem */
198 if (mem
== 0) /* free(0) has no effect */
201 p
= mem2chunk(mem
); /* do not bother to replicate free_check here */
204 if (chunk_is_mmapped(p
)) /* release mmapped memory. */
211 ar_ptr
= arena_for_chunk(p
);
212 tsd_getspecific(arena_key
, vptr
);
213 if(vptr
!= ATFORK_ARENA_PTR
)
214 (void)mutex_lock(&ar_ptr
->mutex
);
215 _int_free(ar_ptr
, mem
);
216 if(vptr
!= ATFORK_ARENA_PTR
)
217 (void)mutex_unlock(&ar_ptr
->mutex
);
221 /* Counter for number of times the list is locked by the same thread. */
222 static unsigned int atfork_recursive_cntr
;
224 /* The following two functions are registered via thread_atfork() to
225 make sure that the mutexes remain in a consistent state in the
226 fork()ed version of a thread. Also adapt the malloc and free hooks
227 temporarily, because the `atfork' handler mechanism may use
228 malloc/free internally (e.g. in LinuxThreads). */
231 ptmalloc_lock_all (void)
235 if(__malloc_initialized
< 1)
237 if (mutex_trylock(&list_lock
))
240 tsd_getspecific(arena_key
, my_arena
);
241 if (my_arena
== ATFORK_ARENA_PTR
)
242 /* This is the same thread which already locks the global list.
243 Just bump the counter. */
246 /* This thread has to wait its turn. */
247 (void)mutex_lock(&list_lock
);
249 for(ar_ptr
= &main_arena
;;) {
250 (void)mutex_lock(&ar_ptr
->mutex
);
251 ar_ptr
= ar_ptr
->next
;
252 if(ar_ptr
== &main_arena
) break;
254 save_malloc_hook
= __malloc_hook
;
255 save_free_hook
= __free_hook
;
256 __malloc_hook
= malloc_atfork
;
257 __free_hook
= free_atfork
;
258 /* Only the current thread may perform malloc/free calls now. */
259 tsd_getspecific(arena_key
, save_arena
);
260 tsd_setspecific(arena_key
, ATFORK_ARENA_PTR
);
262 ++atfork_recursive_cntr
;
266 ptmalloc_unlock_all (void)
270 if(__malloc_initialized
< 1)
272 if (--atfork_recursive_cntr
!= 0)
274 tsd_setspecific(arena_key
, save_arena
);
275 __malloc_hook
= save_malloc_hook
;
276 __free_hook
= save_free_hook
;
277 for(ar_ptr
= &main_arena
;;) {
278 (void)mutex_unlock(&ar_ptr
->mutex
);
279 ar_ptr
= ar_ptr
->next
;
280 if(ar_ptr
== &main_arena
) break;
282 (void)mutex_unlock(&list_lock
);
287 /* In NPTL, unlocking a mutex in the child process after a
288 fork() is currently unsafe, whereas re-initializing it is safe and
289 does not leak resources. Therefore, a special atfork handler is
290 installed for the child. */
293 ptmalloc_unlock_all2 (void)
297 if(__malloc_initialized
< 1)
299 #if defined _LIBC || defined MALLOC_HOOKS
300 tsd_setspecific(arena_key
, save_arena
);
301 __malloc_hook
= save_malloc_hook
;
302 __free_hook
= save_free_hook
;
304 for(ar_ptr
= &main_arena
;;) {
305 mutex_init(&ar_ptr
->mutex
);
306 ar_ptr
= ar_ptr
->next
;
307 if(ar_ptr
== &main_arena
) break;
309 mutex_init(&list_lock
);
310 atfork_recursive_cntr
= 0;
315 #define ptmalloc_unlock_all2 ptmalloc_unlock_all
319 #endif /* !defined NO_THREADS */
321 /* Initialization routine. */
324 extern char **_environ
;
328 next_env_entry (char ***position
)
330 char **current
= *position
;
333 while (*current
!= NULL
)
335 if (__builtin_expect ((*current
)[0] == 'M', 0)
336 && (*current
)[1] == 'A'
337 && (*current
)[2] == 'L'
338 && (*current
)[3] == 'L'
339 && (*current
)[4] == 'O'
340 && (*current
)[5] == 'C'
341 && (*current
)[6] == '_')
343 result
= &(*current
)[7];
345 /* Save current position for next visit. */
346 *position
= ++current
;
358 /* Set up basic state so that _int_malloc et al can work. */
360 ptmalloc_init_minimal (void)
362 #if DEFAULT_TOP_PAD != 0
363 mp_
.top_pad
= DEFAULT_TOP_PAD
;
365 mp_
.n_mmaps_max
= DEFAULT_MMAP_MAX
;
366 mp_
.mmap_threshold
= DEFAULT_MMAP_THRESHOLD
;
367 mp_
.trim_threshold
= DEFAULT_TRIM_THRESHOLD
;
368 mp_
.pagesize
= malloc_getpagesize
;
375 __failing_morecore (ptrdiff_t d
)
377 return (void *) MORECORE_FAILURE
;
380 extern struct dl_open_hook
*_dl_open_hook
;
381 libc_hidden_proto (_dl_open_hook
);
384 # if defined SHARED && defined USE_TLS && !USE___THREAD
385 /* This is called by __pthread_initialize_minimal when it needs to use
386 malloc to set up the TLS state. We cannot do the full work of
387 ptmalloc_init (below) until __pthread_initialize_minimal has finished,
388 so it has to switch to using the special startup-time hooks while doing
389 those allocations. */
391 __libc_malloc_pthread_startup (bool first_time
)
395 ptmalloc_init_minimal ();
396 save_malloc_hook
= __malloc_hook
;
397 save_memalign_hook
= __memalign_hook
;
398 save_free_hook
= __free_hook
;
399 __malloc_hook
= malloc_starter
;
400 __memalign_hook
= memalign_starter
;
401 __free_hook
= free_starter
;
405 __malloc_hook
= save_malloc_hook
;
406 __memalign_hook
= save_memalign_hook
;
407 __free_hook
= save_free_hook
;
423 if(__malloc_initialized
>= 0) return;
424 __malloc_initialized
= 0;
427 # if defined SHARED && defined USE_TLS && !USE___THREAD
428 /* ptmalloc_init_minimal may already have been called via
429 __libc_malloc_pthread_startup, above. */
430 if (mp_
.pagesize
== 0)
433 ptmalloc_init_minimal();
436 # if defined _LIBC && defined USE_TLS
437 /* We know __pthread_initialize_minimal has already been called,
438 and that is enough. */
442 /* With some threads implementations, creating thread-specific data
443 or initializing a mutex may call malloc() itself. Provide a
444 simple starter version (realloc() won't work). */
445 save_malloc_hook
= __malloc_hook
;
446 save_memalign_hook
= __memalign_hook
;
447 save_free_hook
= __free_hook
;
448 __malloc_hook
= malloc_starter
;
449 __memalign_hook
= memalign_starter
;
450 __free_hook
= free_starter
;
452 /* Initialize the pthreads interface. */
453 if (__pthread_initialize
!= NULL
)
454 __pthread_initialize();
455 # endif /* !defined _LIBC */
456 # endif /* !defined NO_STARTER */
457 #endif /* !defined NO_THREADS */
458 mutex_init(&main_arena
.mutex
);
459 main_arena
.next
= &main_arena
;
461 #if defined _LIBC && defined SHARED
462 /* In case this libc copy is in a non-default namespace, never use brk.
463 Likewise if dlopened from statically linked program. */
467 if (_dl_open_hook
!= NULL
468 || (_dl_addr (ptmalloc_init
, &di
, &l
, NULL
) != 0
469 && l
->l_ns
!= LM_ID_BASE
))
470 __morecore
= __failing_morecore
;
473 mutex_init(&list_lock
);
474 tsd_key_create(&arena_key
, NULL
);
475 tsd_setspecific(arena_key
, (Void_t
*)&main_arena
);
476 thread_atfork(ptmalloc_lock_all
, ptmalloc_unlock_all
, ptmalloc_unlock_all2
);
479 __malloc_hook
= save_malloc_hook
;
480 __memalign_hook
= save_memalign_hook
;
481 __free_hook
= save_free_hook
;
487 secure
= __libc_enable_secure
;
489 if (__builtin_expect (_environ
!= NULL
, 1))
491 char **runp
= _environ
;
494 while (__builtin_expect ((envline
= next_env_entry (&runp
)) != NULL
,
497 size_t len
= strcspn (envline
, "=");
499 if (envline
[len
] != '=')
500 /* This is a "MALLOC_" variable at the end of the string
501 without a '=' character. Ignore it since otherwise we
502 will access invalid memory below. */
508 if (memcmp (envline
, "CHECK_", 6) == 0)
514 if (memcmp (envline
, "TOP_PAD_", 8) == 0)
515 mALLOPt(M_TOP_PAD
, atoi(&envline
[9]));
516 else if (memcmp (envline
, "PERTURB_", 8) == 0)
517 mALLOPt(M_PERTURB
, atoi(&envline
[9]));
521 if (! secure
&& memcmp (envline
, "MMAP_MAX_", 9) == 0)
522 mALLOPt(M_MMAP_MAX
, atoi(&envline
[10]));
527 if (memcmp (envline
, "TRIM_THRESHOLD_", 15) == 0)
528 mALLOPt(M_TRIM_THRESHOLD
, atoi(&envline
[16]));
529 else if (memcmp (envline
, "MMAP_THRESHOLD_", 15) == 0)
530 mALLOPt(M_MMAP_THRESHOLD
, atoi(&envline
[16]));
541 if((s
= getenv("MALLOC_TRIM_THRESHOLD_")))
542 mALLOPt(M_TRIM_THRESHOLD
, atoi(s
));
543 if((s
= getenv("MALLOC_TOP_PAD_")))
544 mALLOPt(M_TOP_PAD
, atoi(s
));
545 if((s
= getenv("MALLOC_PERTURB_")))
546 mALLOPt(M_PERTURB
, atoi(s
));
547 if((s
= getenv("MALLOC_MMAP_THRESHOLD_")))
548 mALLOPt(M_MMAP_THRESHOLD
, atoi(s
));
549 if((s
= getenv("MALLOC_MMAP_MAX_")))
550 mALLOPt(M_MMAP_MAX
, atoi(s
));
552 s
= getenv("MALLOC_CHECK_");
555 mALLOPt(M_CHECK_ACTION
, (int)(s
[0] - '0'));
556 if (check_action
!= 0)
557 __malloc_check_init();
559 if(__malloc_initialize_hook
!= NULL
)
560 (*__malloc_initialize_hook
)();
561 __malloc_initialized
= 1;
564 /* There are platforms (e.g. Hurd) with a link-time hook mechanism. */
565 #ifdef thread_atfork_static
566 thread_atfork_static(ptmalloc_lock_all
, ptmalloc_unlock_all
, \
567 ptmalloc_unlock_all2
)
572 /* Managing heaps and arenas (for concurrent threads) */
578 /* Print the complete contents of a single heap to stderr. */
582 dump_heap(heap_info
*heap
)
584 dump_heap(heap
) heap_info
*heap
;
590 fprintf(stderr
, "Heap %p, size %10lx:\n", heap
, (long)heap
->size
);
591 ptr
= (heap
->ar_ptr
!= (mstate
)(heap
+1)) ?
592 (char*)(heap
+ 1) : (char*)(heap
+ 1) + sizeof(struct malloc_state
);
593 p
= (mchunkptr
)(((unsigned long)ptr
+ MALLOC_ALIGN_MASK
) &
596 fprintf(stderr
, "chunk %p size %10lx", p
, (long)p
->size
);
597 if(p
== top(heap
->ar_ptr
)) {
598 fprintf(stderr
, " (top)\n");
600 } else if(p
->size
== (0|PREV_INUSE
)) {
601 fprintf(stderr
, " (fence)\n");
604 fprintf(stderr
, "\n");
609 #endif /* MALLOC_DEBUG > 1 */
611 /* If consecutive mmap (0, HEAP_MAX_SIZE << 1, ...) calls return decreasing
612 addresses as opposed to increasing, new_heap would badly fragment the
613 address space. In that case remember the second HEAP_MAX_SIZE part
614 aligned to HEAP_MAX_SIZE from last mmap (0, HEAP_MAX_SIZE << 1, ...)
615 call (if it is already aligned) and try to reuse it next time. We need
616 no locking for it, as kernel ensures the atomicity for us - worst case
617 we'll call mmap (addr, HEAP_MAX_SIZE, ...) for some value of addr in
618 multiple threads, but only one will succeed. */
619 static char *aligned_heap_area
;
621 /* Create a new heap. size is automatically rounded up to a multiple
627 new_heap(size_t size
, size_t top_pad
)
629 new_heap(size
, top_pad
) size_t size
, top_pad
;
632 size_t page_mask
= malloc_getpagesize
- 1;
637 if(size
+top_pad
< HEAP_MIN_SIZE
)
638 size
= HEAP_MIN_SIZE
;
639 else if(size
+top_pad
<= HEAP_MAX_SIZE
)
641 else if(size
> HEAP_MAX_SIZE
)
644 size
= HEAP_MAX_SIZE
;
645 size
= (size
+ page_mask
) & ~page_mask
;
647 /* A memory region aligned to a multiple of HEAP_MAX_SIZE is needed.
648 No swap space needs to be reserved for the following large
649 mapping (on Linux, this is the case for all non-writable mappings
652 if(aligned_heap_area
) {
653 p2
= (char *)MMAP(aligned_heap_area
, HEAP_MAX_SIZE
, PROT_NONE
,
654 MAP_PRIVATE
|MAP_NORESERVE
);
655 aligned_heap_area
= NULL
;
656 if (p2
!= MAP_FAILED
&& ((unsigned long)p2
& (HEAP_MAX_SIZE
-1))) {
657 munmap(p2
, HEAP_MAX_SIZE
);
661 if(p2
== MAP_FAILED
) {
662 p1
= (char *)MMAP(0, HEAP_MAX_SIZE
<<1, PROT_NONE
,
663 MAP_PRIVATE
|MAP_NORESERVE
);
664 if(p1
!= MAP_FAILED
) {
665 p2
= (char *)(((unsigned long)p1
+ (HEAP_MAX_SIZE
-1))
666 & ~(HEAP_MAX_SIZE
-1));
671 aligned_heap_area
= p2
+ HEAP_MAX_SIZE
;
672 munmap(p2
+ HEAP_MAX_SIZE
, HEAP_MAX_SIZE
- ul
);
674 /* Try to take the chance that an allocation of only HEAP_MAX_SIZE
675 is already aligned. */
676 p2
= (char *)MMAP(0, HEAP_MAX_SIZE
, PROT_NONE
, MAP_PRIVATE
|MAP_NORESERVE
);
679 if((unsigned long)p2
& (HEAP_MAX_SIZE
-1)) {
680 munmap(p2
, HEAP_MAX_SIZE
);
685 if(mprotect(p2
, size
, PROT_READ
|PROT_WRITE
) != 0) {
686 munmap(p2
, HEAP_MAX_SIZE
);
691 THREAD_STAT(stat_n_heaps
++);
695 /* Grow or shrink a heap. size is automatically rounded up to a
696 multiple of the page size if it is positive. */
700 grow_heap(heap_info
*h
, long diff
)
702 grow_heap(h
, diff
) heap_info
*h
; long diff
;
705 size_t page_mask
= malloc_getpagesize
- 1;
709 diff
= (diff
+ page_mask
) & ~page_mask
;
710 new_size
= (long)h
->size
+ diff
;
711 if(new_size
> HEAP_MAX_SIZE
)
713 if(mprotect((char *)h
+ h
->size
, diff
, PROT_READ
|PROT_WRITE
) != 0)
716 new_size
= (long)h
->size
+ diff
;
717 if(new_size
< (long)sizeof(*h
))
719 /* Try to re-map the extra heap space freshly to save memory, and
720 make it inaccessible. */
721 if((char *)MMAP((char *)h
+ new_size
, -diff
, PROT_NONE
,
722 MAP_PRIVATE
|MAP_FIXED
) == (char *) MAP_FAILED
)
724 /*fprintf(stderr, "shrink %p %08lx\n", h, new_size);*/
732 #define delete_heap(heap) \
734 if ((char *)(heap) + HEAP_MAX_SIZE == aligned_heap_area) \
735 aligned_heap_area = NULL; \
736 munmap((char*)(heap), HEAP_MAX_SIZE); \
742 heap_trim(heap_info
*heap
, size_t pad
)
744 heap_trim(heap
, pad
) heap_info
*heap
; size_t pad
;
747 mstate ar_ptr
= heap
->ar_ptr
;
748 unsigned long pagesz
= mp_
.pagesize
;
749 mchunkptr top_chunk
= top(ar_ptr
), p
, bck
, fwd
;
750 heap_info
*prev_heap
;
751 long new_size
, top_size
, extra
;
753 /* Can this heap go away completely? */
754 while(top_chunk
== chunk_at_offset(heap
, sizeof(*heap
))) {
755 prev_heap
= heap
->prev
;
756 p
= chunk_at_offset(prev_heap
, prev_heap
->size
- (MINSIZE
-2*SIZE_SZ
));
757 assert(p
->size
== (0|PREV_INUSE
)); /* must be fencepost */
759 new_size
= chunksize(p
) + (MINSIZE
-2*SIZE_SZ
);
760 assert(new_size
>0 && new_size
<(long)(2*MINSIZE
));
762 new_size
+= p
->prev_size
;
763 assert(new_size
>0 && new_size
<HEAP_MAX_SIZE
);
764 if(new_size
+ (HEAP_MAX_SIZE
- prev_heap
->size
) < pad
+ MINSIZE
+ pagesz
)
766 ar_ptr
->system_mem
-= heap
->size
;
767 arena_mem
-= heap
->size
;
770 if(!prev_inuse(p
)) { /* consolidate backward */
774 assert(((unsigned long)((char*)p
+ new_size
) & (pagesz
-1)) == 0);
775 assert( ((char*)p
+ new_size
) == ((char*)heap
+ heap
->size
) );
776 top(ar_ptr
) = top_chunk
= p
;
777 set_head(top_chunk
, new_size
| PREV_INUSE
);
778 /*check_chunk(ar_ptr, top_chunk);*/
780 top_size
= chunksize(top_chunk
);
781 extra
= ((top_size
- pad
- MINSIZE
+ (pagesz
-1))/pagesz
- 1) * pagesz
;
782 if(extra
< (long)pagesz
)
785 if(grow_heap(heap
, -extra
) != 0)
787 ar_ptr
->system_mem
-= extra
;
790 /* Success. Adjust top accordingly. */
791 set_head(top_chunk
, (top_size
- extra
) | PREV_INUSE
);
792 /*check_chunk(ar_ptr, top_chunk);*/
796 /* Create a new arena with initial size "size". */
799 _int_new_arena(size_t size
)
804 unsigned long misalign
;
806 h
= new_heap(size
+ (sizeof(*h
) + sizeof(*a
) + MALLOC_ALIGNMENT
),
809 /* Maybe size is too large to fit in a single heap. So, just try
810 to create a minimally-sized arena and let _int_malloc() attempt
811 to deal with the large request via mmap_chunk(). */
812 h
= new_heap(sizeof(*h
) + sizeof(*a
) + MALLOC_ALIGNMENT
, mp_
.top_pad
);
816 a
= h
->ar_ptr
= (mstate
)(h
+1);
817 malloc_init_state(a
);
819 a
->system_mem
= a
->max_system_mem
= h
->size
;
820 arena_mem
+= h
->size
;
822 if((unsigned long)(mp_
.mmapped_mem
+ arena_mem
+ main_arena
.system_mem
) >
824 mp_
.max_total_mem
= mp_
.mmapped_mem
+ arena_mem
+ main_arena
.system_mem
;
827 /* Set up the top chunk, with proper alignment. */
828 ptr
= (char *)(a
+ 1);
829 misalign
= (unsigned long)chunk2mem(ptr
) & MALLOC_ALIGN_MASK
;
831 ptr
+= MALLOC_ALIGNMENT
- misalign
;
832 top(a
) = (mchunkptr
)ptr
;
833 set_head(top(a
), (((char*)h
+ h
->size
) - ptr
) | PREV_INUSE
);
841 arena_get2(mstate a_tsd
, size_t size
)
843 arena_get2(a_tsd
, size
) mstate a_tsd
; size_t size
;
849 a
= a_tsd
= &main_arena
;
853 /* This can only happen while initializing the new arena. */
854 (void)mutex_lock(&main_arena
.mutex
);
855 THREAD_STAT(++(main_arena
.stat_lock_wait
));
860 /* Check the global, circularly linked list for available arenas. */
861 bool retried
= false;
864 if(!mutex_trylock(&a
->mutex
)) {
866 (void)mutex_unlock(&list_lock
);
867 THREAD_STAT(++(a
->stat_lock_loop
));
868 tsd_setspecific(arena_key
, (Void_t
*)a
);
874 /* If not even the list_lock can be obtained, try again. This can
875 happen during `atfork', or for example on systems where thread
876 creation makes it temporarily impossible to obtain _any_
878 if(!retried
&& mutex_trylock(&list_lock
)) {
879 /* We will block to not run in a busy loop. */
880 (void)mutex_lock(&list_lock
);
882 /* Since we blocked there might be an arena available now. */
888 /* Nothing immediately available, so generate a new arena. */
889 a
= _int_new_arena(size
);
892 tsd_setspecific(arena_key
, (Void_t
*)a
);
893 mutex_init(&a
->mutex
);
894 mutex_lock(&a
->mutex
); /* remember result */
896 /* Add the new arena to the global list. */
897 a
->next
= main_arena
.next
;
898 atomic_write_barrier ();
901 THREAD_STAT(++(a
->stat_lock_loop
));
903 (void)mutex_unlock(&list_lock
);
908 #endif /* USE_ARENAS */