]> git.ipfire.org Git - thirdparty/glibc.git/blob - malloc/arena.c
Cleanup of configuration options
[thirdparty/glibc.git] / malloc / arena.c
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2009,2010,2011
3 Free Software Foundation, Inc.
4 This file is part of the GNU C Library.
5 Contributed by Wolfram Gloger <wg@malloc.de>, 2001.
6
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.
11
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.
16
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. */
21
22 #include <stdbool.h>
23
24 /* Compile-time constants. */
25
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
34
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. */
41
42
43 #ifndef THREAD_STATS
44 #define THREAD_STATS 0
45 #endif
46
47 /* If THREAD_STATS is non-zero, some statistics on mutex locking are
48 computed. */
49
50 /***************************************************************************/
51
52 #define top(ar_ptr) ((ar_ptr)->top)
53
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. */
58
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;
70
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];
76
77 /* Thread specific data */
78
79 static tsd_key_t arena_key;
80 static mutex_t list_lock;
81 #ifdef PER_THREAD
82 static size_t narenas;
83 static mstate free_list;
84 #endif
85
86 #if THREAD_STATS
87 static int stat_n_heaps;
88 #define THREAD_STAT(x) x
89 #else
90 #define THREAD_STAT(x) do ; while(0)
91 #endif
92
93 /* Mapped memory in non-main arenas (reliable only for NO_THREADS). */
94 static unsigned long arena_mem;
95
96 /* Already initialized? */
97 int __malloc_initialized = -1;
98
99 /**************************************************************************/
100
101 #if USE_ARENAS
102
103 /* arena_get() acquires an arena and locks the corresponding mutex.
104 First, try the one last locked successfully by this thread. (This
105 is the common case and handled with a macro for speed.) Then, loop
106 once over the circularly linked list of arenas. If no arena is
107 readily available, create a new one. In this latter case, `size'
108 is just a hint as to how much memory will be required immediately
109 in the new arena. */
110
111 #define arena_get(ptr, size) do { \
112 arena_lookup(ptr); \
113 arena_lock(ptr, size); \
114 } while(0)
115
116 #define arena_lookup(ptr) do { \
117 Void_t *vptr = NULL; \
118 ptr = (mstate)tsd_getspecific(arena_key, vptr); \
119 } while(0)
120
121 #ifdef PER_THREAD
122 #define arena_lock(ptr, size) do { \
123 if(ptr) \
124 (void)mutex_lock(&ptr->mutex); \
125 else \
126 ptr = arena_get2(ptr, (size)); \
127 } while(0)
128 #else
129 #define arena_lock(ptr, size) do { \
130 if(ptr && !mutex_trylock(&ptr->mutex)) { \
131 THREAD_STAT(++(ptr->stat_lock_direct)); \
132 } else \
133 ptr = arena_get2(ptr, (size)); \
134 } while(0)
135 #endif
136
137 /* find the heap and corresponding arena for a given ptr */
138
139 #define heap_for_ptr(ptr) \
140 ((heap_info *)((unsigned long)(ptr) & ~(HEAP_MAX_SIZE-1)))
141 #define arena_for_chunk(ptr) \
142 (chunk_non_main_arena(ptr) ? heap_for_ptr(ptr)->ar_ptr : &main_arena)
143
144 #else /* !USE_ARENAS */
145
146 /* There is only one arena, main_arena. */
147
148 #if THREAD_STATS
149 #define arena_get(ar_ptr, sz) do { \
150 ar_ptr = &main_arena; \
151 if(!mutex_trylock(&ar_ptr->mutex)) \
152 ++(ar_ptr->stat_lock_direct); \
153 else { \
154 (void)mutex_lock(&ar_ptr->mutex); \
155 ++(ar_ptr->stat_lock_wait); \
156 } \
157 } while(0)
158 #else
159 #define arena_get(ar_ptr, sz) do { \
160 ar_ptr = &main_arena; \
161 (void)mutex_lock(&ar_ptr->mutex); \
162 } while(0)
163 #endif
164 #define arena_for_chunk(ptr) (&main_arena)
165
166 #endif /* USE_ARENAS */
167
168 /**************************************************************************/
169
170 #ifndef NO_THREADS
171
172 /* atfork support. */
173
174 static __malloc_ptr_t (*save_malloc_hook) (size_t __size,
175 __const __malloc_ptr_t);
176 # if !defined _LIBC || (defined SHARED && !USE___THREAD)
177 static __malloc_ptr_t (*save_memalign_hook) (size_t __align, size_t __size,
178 __const __malloc_ptr_t);
179 # endif
180 static void (*save_free_hook) (__malloc_ptr_t __ptr,
181 __const __malloc_ptr_t);
182 static Void_t* save_arena;
183
184 #ifdef ATFORK_MEM
185 ATFORK_MEM;
186 #endif
187
188 /* Magic value for the thread-specific arena pointer when
189 malloc_atfork() is in use. */
190
191 #define ATFORK_ARENA_PTR ((Void_t*)-1)
192
193 /* The following hooks are used while the `atfork' handling mechanism
194 is active. */
195
196 static Void_t*
197 malloc_atfork(size_t sz, const Void_t *caller)
198 {
199 Void_t *vptr = NULL;
200 Void_t *victim;
201
202 tsd_getspecific(arena_key, vptr);
203 if(vptr == ATFORK_ARENA_PTR) {
204 /* We are the only thread that may allocate at all. */
205 if(save_malloc_hook != malloc_check) {
206 return _int_malloc(&main_arena, sz);
207 } else {
208 if(top_check()<0)
209 return 0;
210 victim = _int_malloc(&main_arena, sz+1);
211 return mem2mem_check(victim, sz);
212 }
213 } else {
214 /* Suspend the thread until the `atfork' handlers have completed.
215 By that time, the hooks will have been reset as well, so that
216 mALLOc() can be used again. */
217 (void)mutex_lock(&list_lock);
218 (void)mutex_unlock(&list_lock);
219 return public_mALLOc(sz);
220 }
221 }
222
223 static void
224 free_atfork(Void_t* mem, const Void_t *caller)
225 {
226 Void_t *vptr = NULL;
227 mstate ar_ptr;
228 mchunkptr p; /* chunk corresponding to mem */
229
230 if (mem == 0) /* free(0) has no effect */
231 return;
232
233 p = mem2chunk(mem); /* do not bother to replicate free_check here */
234
235 #if HAVE_MMAP
236 if (chunk_is_mmapped(p)) /* release mmapped memory. */
237 {
238 munmap_chunk(p);
239 return;
240 }
241 #endif
242
243 #ifdef ATOMIC_FASTBINS
244 ar_ptr = arena_for_chunk(p);
245 tsd_getspecific(arena_key, vptr);
246 _int_free(ar_ptr, p, vptr == ATFORK_ARENA_PTR);
247 #else
248 ar_ptr = arena_for_chunk(p);
249 tsd_getspecific(arena_key, vptr);
250 if(vptr != ATFORK_ARENA_PTR)
251 (void)mutex_lock(&ar_ptr->mutex);
252 _int_free(ar_ptr, p);
253 if(vptr != ATFORK_ARENA_PTR)
254 (void)mutex_unlock(&ar_ptr->mutex);
255 #endif
256 }
257
258
259 /* Counter for number of times the list is locked by the same thread. */
260 static unsigned int atfork_recursive_cntr;
261
262 /* The following two functions are registered via thread_atfork() to
263 make sure that the mutexes remain in a consistent state in the
264 fork()ed version of a thread. Also adapt the malloc and free hooks
265 temporarily, because the `atfork' handler mechanism may use
266 malloc/free internally (e.g. in LinuxThreads). */
267
268 static void
269 ptmalloc_lock_all (void)
270 {
271 mstate ar_ptr;
272
273 if(__malloc_initialized < 1)
274 return;
275 if (mutex_trylock(&list_lock))
276 {
277 Void_t *my_arena;
278 tsd_getspecific(arena_key, my_arena);
279 if (my_arena == ATFORK_ARENA_PTR)
280 /* This is the same thread which already locks the global list.
281 Just bump the counter. */
282 goto out;
283
284 /* This thread has to wait its turn. */
285 (void)mutex_lock(&list_lock);
286 }
287 for(ar_ptr = &main_arena;;) {
288 (void)mutex_lock(&ar_ptr->mutex);
289 ar_ptr = ar_ptr->next;
290 if(ar_ptr == &main_arena) break;
291 }
292 save_malloc_hook = __malloc_hook;
293 save_free_hook = __free_hook;
294 __malloc_hook = malloc_atfork;
295 __free_hook = free_atfork;
296 /* Only the current thread may perform malloc/free calls now. */
297 tsd_getspecific(arena_key, save_arena);
298 tsd_setspecific(arena_key, ATFORK_ARENA_PTR);
299 out:
300 ++atfork_recursive_cntr;
301 }
302
303 static void
304 ptmalloc_unlock_all (void)
305 {
306 mstate ar_ptr;
307
308 if(__malloc_initialized < 1)
309 return;
310 if (--atfork_recursive_cntr != 0)
311 return;
312 tsd_setspecific(arena_key, save_arena);
313 __malloc_hook = save_malloc_hook;
314 __free_hook = save_free_hook;
315 for(ar_ptr = &main_arena;;) {
316 (void)mutex_unlock(&ar_ptr->mutex);
317 ar_ptr = ar_ptr->next;
318 if(ar_ptr == &main_arena) break;
319 }
320 (void)mutex_unlock(&list_lock);
321 }
322
323 #ifdef __linux__
324
325 /* In NPTL, unlocking a mutex in the child process after a
326 fork() is currently unsafe, whereas re-initializing it is safe and
327 does not leak resources. Therefore, a special atfork handler is
328 installed for the child. */
329
330 static void
331 ptmalloc_unlock_all2 (void)
332 {
333 mstate ar_ptr;
334
335 if(__malloc_initialized < 1)
336 return;
337 #if defined _LIBC || defined MALLOC_HOOKS
338 tsd_setspecific(arena_key, save_arena);
339 __malloc_hook = save_malloc_hook;
340 __free_hook = save_free_hook;
341 #endif
342 #ifdef PER_THREAD
343 free_list = NULL;
344 #endif
345 for(ar_ptr = &main_arena;;) {
346 mutex_init(&ar_ptr->mutex);
347 #ifdef PER_THREAD
348 if (ar_ptr != save_arena) {
349 ar_ptr->next_free = free_list;
350 free_list = ar_ptr;
351 }
352 #endif
353 ar_ptr = ar_ptr->next;
354 if(ar_ptr == &main_arena) break;
355 }
356 mutex_init(&list_lock);
357 atfork_recursive_cntr = 0;
358 }
359
360 #else
361
362 #define ptmalloc_unlock_all2 ptmalloc_unlock_all
363
364 #endif
365
366 #endif /* !defined NO_THREADS */
367
368 /* Initialization routine. */
369 #ifdef _LIBC
370 #include <string.h>
371 extern char **_environ;
372
373 static char *
374 internal_function
375 next_env_entry (char ***position)
376 {
377 char **current = *position;
378 char *result = NULL;
379
380 while (*current != NULL)
381 {
382 if (__builtin_expect ((*current)[0] == 'M', 0)
383 && (*current)[1] == 'A'
384 && (*current)[2] == 'L'
385 && (*current)[3] == 'L'
386 && (*current)[4] == 'O'
387 && (*current)[5] == 'C'
388 && (*current)[6] == '_')
389 {
390 result = &(*current)[7];
391
392 /* Save current position for next visit. */
393 *position = ++current;
394
395 break;
396 }
397
398 ++current;
399 }
400
401 return result;
402 }
403 #endif /* _LIBC */
404
405 /* Set up basic state so that _int_malloc et al can work. */
406 static void
407 ptmalloc_init_minimal (void)
408 {
409 #if DEFAULT_TOP_PAD != 0
410 mp_.top_pad = DEFAULT_TOP_PAD;
411 #endif
412 mp_.n_mmaps_max = DEFAULT_MMAP_MAX;
413 mp_.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
414 mp_.trim_threshold = DEFAULT_TRIM_THRESHOLD;
415 mp_.pagesize = malloc_getpagesize;
416 #ifdef PER_THREAD
417 # define NARENAS_FROM_NCORES(n) ((n) * (sizeof(long) == 4 ? 2 : 8))
418 mp_.arena_test = NARENAS_FROM_NCORES (1);
419 narenas = 1;
420 #endif
421 }
422
423
424 #ifdef _LIBC
425 # ifdef SHARED
426 static void *
427 __failing_morecore (ptrdiff_t d)
428 {
429 return (void *) MORECORE_FAILURE;
430 }
431
432 extern struct dl_open_hook *_dl_open_hook;
433 libc_hidden_proto (_dl_open_hook);
434 # endif
435
436 # if defined SHARED && !USE___THREAD
437 /* This is called by __pthread_initialize_minimal when it needs to use
438 malloc to set up the TLS state. We cannot do the full work of
439 ptmalloc_init (below) until __pthread_initialize_minimal has finished,
440 so it has to switch to using the special startup-time hooks while doing
441 those allocations. */
442 void
443 __libc_malloc_pthread_startup (bool first_time)
444 {
445 if (first_time)
446 {
447 ptmalloc_init_minimal ();
448 save_malloc_hook = __malloc_hook;
449 save_memalign_hook = __memalign_hook;
450 save_free_hook = __free_hook;
451 __malloc_hook = malloc_starter;
452 __memalign_hook = memalign_starter;
453 __free_hook = free_starter;
454 }
455 else
456 {
457 __malloc_hook = save_malloc_hook;
458 __memalign_hook = save_memalign_hook;
459 __free_hook = save_free_hook;
460 }
461 }
462 # endif
463 #endif
464
465 static void
466 ptmalloc_init (void)
467 {
468 #if __STD_C
469 const char* s;
470 #else
471 char* s;
472 #endif
473 int secure = 0;
474
475 if(__malloc_initialized >= 0) return;
476 __malloc_initialized = 0;
477
478 #ifdef _LIBC
479 # if defined SHARED && !USE___THREAD
480 /* ptmalloc_init_minimal may already have been called via
481 __libc_malloc_pthread_startup, above. */
482 if (mp_.pagesize == 0)
483 # endif
484 #endif
485 ptmalloc_init_minimal();
486
487 mutex_init(&main_arena.mutex);
488 main_arena.next = &main_arena;
489
490 #if defined _LIBC && defined SHARED
491 /* In case this libc copy is in a non-default namespace, never use brk.
492 Likewise if dlopened from statically linked program. */
493 Dl_info di;
494 struct link_map *l;
495
496 if (_dl_open_hook != NULL
497 || (_dl_addr (ptmalloc_init, &di, &l, NULL) != 0
498 && l->l_ns != LM_ID_BASE))
499 __morecore = __failing_morecore;
500 #endif
501
502 mutex_init(&list_lock);
503 tsd_key_create(&arena_key, NULL);
504 tsd_setspecific(arena_key, (Void_t *)&main_arena);
505 thread_atfork(ptmalloc_lock_all, ptmalloc_unlock_all, ptmalloc_unlock_all2);
506 #ifdef _LIBC
507 secure = __libc_enable_secure;
508 s = NULL;
509 if (__builtin_expect (_environ != NULL, 1))
510 {
511 char **runp = _environ;
512 char *envline;
513
514 while (__builtin_expect ((envline = next_env_entry (&runp)) != NULL,
515 0))
516 {
517 size_t len = strcspn (envline, "=");
518
519 if (envline[len] != '=')
520 /* This is a "MALLOC_" variable at the end of the string
521 without a '=' character. Ignore it since otherwise we
522 will access invalid memory below. */
523 continue;
524
525 switch (len)
526 {
527 case 6:
528 if (memcmp (envline, "CHECK_", 6) == 0)
529 s = &envline[7];
530 break;
531 case 8:
532 if (! secure)
533 {
534 if (memcmp (envline, "TOP_PAD_", 8) == 0)
535 mALLOPt(M_TOP_PAD, atoi(&envline[9]));
536 else if (memcmp (envline, "PERTURB_", 8) == 0)
537 mALLOPt(M_PERTURB, atoi(&envline[9]));
538 }
539 break;
540 case 9:
541 if (! secure)
542 {
543 if (memcmp (envline, "MMAP_MAX_", 9) == 0)
544 mALLOPt(M_MMAP_MAX, atoi(&envline[10]));
545 #ifdef PER_THREAD
546 else if (memcmp (envline, "ARENA_MAX", 9) == 0)
547 mALLOPt(M_ARENA_MAX, atoi(&envline[10]));
548 #endif
549 }
550 break;
551 #ifdef PER_THREAD
552 case 10:
553 if (! secure)
554 {
555 if (memcmp (envline, "ARENA_TEST", 10) == 0)
556 mALLOPt(M_ARENA_TEST, atoi(&envline[11]));
557 }
558 break;
559 #endif
560 case 15:
561 if (! secure)
562 {
563 if (memcmp (envline, "TRIM_THRESHOLD_", 15) == 0)
564 mALLOPt(M_TRIM_THRESHOLD, atoi(&envline[16]));
565 else if (memcmp (envline, "MMAP_THRESHOLD_", 15) == 0)
566 mALLOPt(M_MMAP_THRESHOLD, atoi(&envline[16]));
567 }
568 break;
569 default:
570 break;
571 }
572 }
573 }
574 #else
575 if (! secure)
576 {
577 if((s = getenv("MALLOC_TRIM_THRESHOLD_")))
578 mALLOPt(M_TRIM_THRESHOLD, atoi(s));
579 if((s = getenv("MALLOC_TOP_PAD_")))
580 mALLOPt(M_TOP_PAD, atoi(s));
581 if((s = getenv("MALLOC_PERTURB_")))
582 mALLOPt(M_PERTURB, atoi(s));
583 if((s = getenv("MALLOC_MMAP_THRESHOLD_")))
584 mALLOPt(M_MMAP_THRESHOLD, atoi(s));
585 if((s = getenv("MALLOC_MMAP_MAX_")))
586 mALLOPt(M_MMAP_MAX, atoi(s));
587 }
588 s = getenv("MALLOC_CHECK_");
589 #endif
590 if(s && s[0]) {
591 mALLOPt(M_CHECK_ACTION, (int)(s[0] - '0'));
592 if (check_action != 0)
593 __malloc_check_init();
594 }
595 void (*hook) (void) = force_reg (__malloc_initialize_hook);
596 if (hook != NULL)
597 (*hook)();
598 __malloc_initialized = 1;
599 }
600
601 /* There are platforms (e.g. Hurd) with a link-time hook mechanism. */
602 #ifdef thread_atfork_static
603 thread_atfork_static(ptmalloc_lock_all, ptmalloc_unlock_all, \
604 ptmalloc_unlock_all2)
605 #endif
606
607 \f
608
609 /* Managing heaps and arenas (for concurrent threads) */
610
611 #if USE_ARENAS
612
613 #if MALLOC_DEBUG > 1
614
615 /* Print the complete contents of a single heap to stderr. */
616
617 static void
618 #if __STD_C
619 dump_heap(heap_info *heap)
620 #else
621 dump_heap(heap) heap_info *heap;
622 #endif
623 {
624 char *ptr;
625 mchunkptr p;
626
627 fprintf(stderr, "Heap %p, size %10lx:\n", heap, (long)heap->size);
628 ptr = (heap->ar_ptr != (mstate)(heap+1)) ?
629 (char*)(heap + 1) : (char*)(heap + 1) + sizeof(struct malloc_state);
630 p = (mchunkptr)(((unsigned long)ptr + MALLOC_ALIGN_MASK) &
631 ~MALLOC_ALIGN_MASK);
632 for(;;) {
633 fprintf(stderr, "chunk %p size %10lx", p, (long)p->size);
634 if(p == top(heap->ar_ptr)) {
635 fprintf(stderr, " (top)\n");
636 break;
637 } else if(p->size == (0|PREV_INUSE)) {
638 fprintf(stderr, " (fence)\n");
639 break;
640 }
641 fprintf(stderr, "\n");
642 p = next_chunk(p);
643 }
644 }
645
646 #endif /* MALLOC_DEBUG > 1 */
647
648 /* If consecutive mmap (0, HEAP_MAX_SIZE << 1, ...) calls return decreasing
649 addresses as opposed to increasing, new_heap would badly fragment the
650 address space. In that case remember the second HEAP_MAX_SIZE part
651 aligned to HEAP_MAX_SIZE from last mmap (0, HEAP_MAX_SIZE << 1, ...)
652 call (if it is already aligned) and try to reuse it next time. We need
653 no locking for it, as kernel ensures the atomicity for us - worst case
654 we'll call mmap (addr, HEAP_MAX_SIZE, ...) for some value of addr in
655 multiple threads, but only one will succeed. */
656 static char *aligned_heap_area;
657
658 /* Create a new heap. size is automatically rounded up to a multiple
659 of the page size. */
660
661 static heap_info *
662 internal_function
663 #if __STD_C
664 new_heap(size_t size, size_t top_pad)
665 #else
666 new_heap(size, top_pad) size_t size, top_pad;
667 #endif
668 {
669 size_t page_mask = malloc_getpagesize - 1;
670 char *p1, *p2;
671 unsigned long ul;
672 heap_info *h;
673
674 if(size+top_pad < HEAP_MIN_SIZE)
675 size = HEAP_MIN_SIZE;
676 else if(size+top_pad <= HEAP_MAX_SIZE)
677 size += top_pad;
678 else if(size > HEAP_MAX_SIZE)
679 return 0;
680 else
681 size = HEAP_MAX_SIZE;
682 size = (size + page_mask) & ~page_mask;
683
684 /* A memory region aligned to a multiple of HEAP_MAX_SIZE is needed.
685 No swap space needs to be reserved for the following large
686 mapping (on Linux, this is the case for all non-writable mappings
687 anyway). */
688 p2 = MAP_FAILED;
689 if(aligned_heap_area) {
690 p2 = (char *)MMAP(aligned_heap_area, HEAP_MAX_SIZE, PROT_NONE,
691 MAP_PRIVATE|MAP_NORESERVE);
692 aligned_heap_area = NULL;
693 if (p2 != MAP_FAILED && ((unsigned long)p2 & (HEAP_MAX_SIZE-1))) {
694 munmap(p2, HEAP_MAX_SIZE);
695 p2 = MAP_FAILED;
696 }
697 }
698 if(p2 == MAP_FAILED) {
699 p1 = (char *)MMAP(0, HEAP_MAX_SIZE<<1, PROT_NONE,
700 MAP_PRIVATE|MAP_NORESERVE);
701 if(p1 != MAP_FAILED) {
702 p2 = (char *)(((unsigned long)p1 + (HEAP_MAX_SIZE-1))
703 & ~(HEAP_MAX_SIZE-1));
704 ul = p2 - p1;
705 if (ul)
706 munmap(p1, ul);
707 else
708 aligned_heap_area = p2 + HEAP_MAX_SIZE;
709 munmap(p2 + HEAP_MAX_SIZE, HEAP_MAX_SIZE - ul);
710 } else {
711 /* Try to take the chance that an allocation of only HEAP_MAX_SIZE
712 is already aligned. */
713 p2 = (char *)MMAP(0, HEAP_MAX_SIZE, PROT_NONE, MAP_PRIVATE|MAP_NORESERVE);
714 if(p2 == MAP_FAILED)
715 return 0;
716 if((unsigned long)p2 & (HEAP_MAX_SIZE-1)) {
717 munmap(p2, HEAP_MAX_SIZE);
718 return 0;
719 }
720 }
721 }
722 if(mprotect(p2, size, PROT_READ|PROT_WRITE) != 0) {
723 munmap(p2, HEAP_MAX_SIZE);
724 return 0;
725 }
726 h = (heap_info *)p2;
727 h->size = size;
728 h->mprotect_size = size;
729 THREAD_STAT(stat_n_heaps++);
730 return h;
731 }
732
733 /* Grow a heap. size is automatically rounded up to a
734 multiple of the page size. */
735
736 static int
737 #if __STD_C
738 grow_heap(heap_info *h, long diff)
739 #else
740 grow_heap(h, diff) heap_info *h; long diff;
741 #endif
742 {
743 size_t page_mask = malloc_getpagesize - 1;
744 long new_size;
745
746 diff = (diff + page_mask) & ~page_mask;
747 new_size = (long)h->size + diff;
748 if((unsigned long) new_size > (unsigned long) HEAP_MAX_SIZE)
749 return -1;
750 if((unsigned long) new_size > h->mprotect_size) {
751 if (mprotect((char *)h + h->mprotect_size,
752 (unsigned long) new_size - h->mprotect_size,
753 PROT_READ|PROT_WRITE) != 0)
754 return -2;
755 h->mprotect_size = new_size;
756 }
757
758 h->size = new_size;
759 return 0;
760 }
761
762 /* Shrink a heap. */
763
764 static int
765 #if __STD_C
766 shrink_heap(heap_info *h, long diff)
767 #else
768 shrink_heap(h, diff) heap_info *h; long diff;
769 #endif
770 {
771 long new_size;
772
773 new_size = (long)h->size - diff;
774 if(new_size < (long)sizeof(*h))
775 return -1;
776 /* Try to re-map the extra heap space freshly to save memory, and
777 make it inaccessible. */
778 #ifdef _LIBC
779 if (__builtin_expect (__libc_enable_secure, 0))
780 #else
781 if (1)
782 #endif
783 {
784 if((char *)MMAP((char *)h + new_size, diff, PROT_NONE,
785 MAP_PRIVATE|MAP_FIXED) == (char *) MAP_FAILED)
786 return -2;
787 h->mprotect_size = new_size;
788 }
789 #ifdef _LIBC
790 else
791 madvise ((char *)h + new_size, diff, MADV_DONTNEED);
792 #endif
793 /*fprintf(stderr, "shrink %p %08lx\n", h, new_size);*/
794
795 h->size = new_size;
796 return 0;
797 }
798
799 /* Delete a heap. */
800
801 #define delete_heap(heap) \
802 do { \
803 if ((char *)(heap) + HEAP_MAX_SIZE == aligned_heap_area) \
804 aligned_heap_area = NULL; \
805 munmap((char*)(heap), HEAP_MAX_SIZE); \
806 } while (0)
807
808 static int
809 internal_function
810 #if __STD_C
811 heap_trim(heap_info *heap, size_t pad)
812 #else
813 heap_trim(heap, pad) heap_info *heap; size_t pad;
814 #endif
815 {
816 mstate ar_ptr = heap->ar_ptr;
817 unsigned long pagesz = mp_.pagesize;
818 mchunkptr top_chunk = top(ar_ptr), p, bck, fwd;
819 heap_info *prev_heap;
820 long new_size, top_size, extra;
821
822 /* Can this heap go away completely? */
823 while(top_chunk == chunk_at_offset(heap, sizeof(*heap))) {
824 prev_heap = heap->prev;
825 p = chunk_at_offset(prev_heap, prev_heap->size - (MINSIZE-2*SIZE_SZ));
826 assert(p->size == (0|PREV_INUSE)); /* must be fencepost */
827 p = prev_chunk(p);
828 new_size = chunksize(p) + (MINSIZE-2*SIZE_SZ);
829 assert(new_size>0 && new_size<(long)(2*MINSIZE));
830 if(!prev_inuse(p))
831 new_size += p->prev_size;
832 assert(new_size>0 && new_size<HEAP_MAX_SIZE);
833 if(new_size + (HEAP_MAX_SIZE - prev_heap->size) < pad + MINSIZE + pagesz)
834 break;
835 ar_ptr->system_mem -= heap->size;
836 arena_mem -= heap->size;
837 delete_heap(heap);
838 heap = prev_heap;
839 if(!prev_inuse(p)) { /* consolidate backward */
840 p = prev_chunk(p);
841 unlink(p, bck, fwd);
842 }
843 assert(((unsigned long)((char*)p + new_size) & (pagesz-1)) == 0);
844 assert( ((char*)p + new_size) == ((char*)heap + heap->size) );
845 top(ar_ptr) = top_chunk = p;
846 set_head(top_chunk, new_size | PREV_INUSE);
847 /*check_chunk(ar_ptr, top_chunk);*/
848 }
849 top_size = chunksize(top_chunk);
850 extra = (top_size - pad - MINSIZE - 1) & ~(pagesz - 1);
851 if(extra < (long)pagesz)
852 return 0;
853 /* Try to shrink. */
854 if(shrink_heap(heap, extra) != 0)
855 return 0;
856 ar_ptr->system_mem -= extra;
857 arena_mem -= extra;
858
859 /* Success. Adjust top accordingly. */
860 set_head(top_chunk, (top_size - extra) | PREV_INUSE);
861 /*check_chunk(ar_ptr, top_chunk);*/
862 return 1;
863 }
864
865 /* Create a new arena with initial size "size". */
866
867 static mstate
868 _int_new_arena(size_t size)
869 {
870 mstate a;
871 heap_info *h;
872 char *ptr;
873 unsigned long misalign;
874
875 h = new_heap(size + (sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT),
876 mp_.top_pad);
877 if(!h) {
878 /* Maybe size is too large to fit in a single heap. So, just try
879 to create a minimally-sized arena and let _int_malloc() attempt
880 to deal with the large request via mmap_chunk(). */
881 h = new_heap(sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT, mp_.top_pad);
882 if(!h)
883 return 0;
884 }
885 a = h->ar_ptr = (mstate)(h+1);
886 malloc_init_state(a);
887 /*a->next = NULL;*/
888 a->system_mem = a->max_system_mem = h->size;
889 arena_mem += h->size;
890 #ifdef NO_THREADS
891 if((unsigned long)(mp_.mmapped_mem + arena_mem + main_arena.system_mem) >
892 mp_.max_total_mem)
893 mp_.max_total_mem = mp_.mmapped_mem + arena_mem + main_arena.system_mem;
894 #endif
895
896 /* Set up the top chunk, with proper alignment. */
897 ptr = (char *)(a + 1);
898 misalign = (unsigned long)chunk2mem(ptr) & MALLOC_ALIGN_MASK;
899 if (misalign > 0)
900 ptr += MALLOC_ALIGNMENT - misalign;
901 top(a) = (mchunkptr)ptr;
902 set_head(top(a), (((char*)h + h->size) - ptr) | PREV_INUSE);
903
904 tsd_setspecific(arena_key, (Void_t *)a);
905 mutex_init(&a->mutex);
906 (void)mutex_lock(&a->mutex);
907
908 #ifdef PER_THREAD
909 (void)mutex_lock(&list_lock);
910 #endif
911
912 /* Add the new arena to the global list. */
913 a->next = main_arena.next;
914 atomic_write_barrier ();
915 main_arena.next = a;
916
917 #ifdef PER_THREAD
918 ++narenas;
919
920 (void)mutex_unlock(&list_lock);
921 #endif
922
923 THREAD_STAT(++(a->stat_lock_loop));
924
925 return a;
926 }
927
928
929 #ifdef PER_THREAD
930 static mstate
931 get_free_list (void)
932 {
933 mstate result = free_list;
934 if (result != NULL)
935 {
936 (void)mutex_lock(&list_lock);
937 result = free_list;
938 if (result != NULL)
939 free_list = result->next_free;
940 (void)mutex_unlock(&list_lock);
941
942 if (result != NULL)
943 {
944 (void)mutex_lock(&result->mutex);
945 tsd_setspecific(arena_key, (Void_t *)result);
946 THREAD_STAT(++(result->stat_lock_loop));
947 }
948 }
949
950 return result;
951 }
952
953
954 static mstate
955 reused_arena (void)
956 {
957 if (narenas <= mp_.arena_test)
958 return NULL;
959
960 static int narenas_limit;
961 if (narenas_limit == 0)
962 {
963 if (mp_.arena_max != 0)
964 narenas_limit = mp_.arena_max;
965 else
966 {
967 int n = __get_nprocs ();
968
969 if (n >= 1)
970 narenas_limit = NARENAS_FROM_NCORES (n);
971 else
972 /* We have no information about the system. Assume two
973 cores. */
974 narenas_limit = NARENAS_FROM_NCORES (2);
975 }
976 }
977
978 if (narenas < narenas_limit)
979 return NULL;
980
981 mstate result;
982 static mstate next_to_use;
983 if (next_to_use == NULL)
984 next_to_use = &main_arena;
985
986 result = next_to_use;
987 do
988 {
989 if (!mutex_trylock(&result->mutex))
990 goto out;
991
992 result = result->next;
993 }
994 while (result != next_to_use);
995
996 /* No arena available. Wait for the next in line. */
997 (void)mutex_lock(&result->mutex);
998
999 out:
1000 tsd_setspecific(arena_key, (Void_t *)result);
1001 THREAD_STAT(++(result->stat_lock_loop));
1002 next_to_use = result->next;
1003
1004 return result;
1005 }
1006 #endif
1007
1008 static mstate
1009 internal_function
1010 #if __STD_C
1011 arena_get2(mstate a_tsd, size_t size)
1012 #else
1013 arena_get2(a_tsd, size) mstate a_tsd; size_t size;
1014 #endif
1015 {
1016 mstate a;
1017
1018 #ifdef PER_THREAD
1019 if ((a = get_free_list ()) == NULL
1020 && (a = reused_arena ()) == NULL)
1021 /* Nothing immediately available, so generate a new arena. */
1022 a = _int_new_arena(size);
1023 #else
1024 if(!a_tsd)
1025 a = a_tsd = &main_arena;
1026 else {
1027 a = a_tsd->next;
1028 if(!a) {
1029 /* This can only happen while initializing the new arena. */
1030 (void)mutex_lock(&main_arena.mutex);
1031 THREAD_STAT(++(main_arena.stat_lock_wait));
1032 return &main_arena;
1033 }
1034 }
1035
1036 /* Check the global, circularly linked list for available arenas. */
1037 bool retried = false;
1038 repeat:
1039 do {
1040 if(!mutex_trylock(&a->mutex)) {
1041 if (retried)
1042 (void)mutex_unlock(&list_lock);
1043 THREAD_STAT(++(a->stat_lock_loop));
1044 tsd_setspecific(arena_key, (Void_t *)a);
1045 return a;
1046 }
1047 a = a->next;
1048 } while(a != a_tsd);
1049
1050 /* If not even the list_lock can be obtained, try again. This can
1051 happen during `atfork', or for example on systems where thread
1052 creation makes it temporarily impossible to obtain _any_
1053 locks. */
1054 if(!retried && mutex_trylock(&list_lock)) {
1055 /* We will block to not run in a busy loop. */
1056 (void)mutex_lock(&list_lock);
1057
1058 /* Since we blocked there might be an arena available now. */
1059 retried = true;
1060 a = a_tsd;
1061 goto repeat;
1062 }
1063
1064 /* Nothing immediately available, so generate a new arena. */
1065 a = _int_new_arena(size);
1066 (void)mutex_unlock(&list_lock);
1067 #endif
1068
1069 return a;
1070 }
1071
1072 #ifdef PER_THREAD
1073 static void __attribute__ ((section ("__libc_thread_freeres_fn")))
1074 arena_thread_freeres (void)
1075 {
1076 Void_t *vptr = NULL;
1077 mstate a = tsd_getspecific(arena_key, vptr);
1078 tsd_setspecific(arena_key, NULL);
1079
1080 if (a != NULL)
1081 {
1082 (void)mutex_lock(&list_lock);
1083 a->next_free = free_list;
1084 free_list = a;
1085 (void)mutex_unlock(&list_lock);
1086 }
1087 }
1088 text_set_element (__libc_thread_subfreeres, arena_thread_freeres);
1089 #endif
1090
1091 #endif /* USE_ARENAS */
1092
1093 /*
1094 * Local variables:
1095 * c-basic-offset: 2
1096 * End:
1097 */