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