]> git.ipfire.org Git - thirdparty/glibc.git/blob - malloc/arena.c
Update.
[thirdparty/glibc.git] / malloc / arena.c
1 /* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Wolfram Gloger <wg@malloc.de>, 2001.
5
6 The GNU C Library is free software; you can redistribute it and/or
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.
10
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
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. */
20
21 /* $Id$ */
22
23 /* Compile-time constants. */
24
25 #define HEAP_MIN_SIZE (32*1024)
26 #ifndef HEAP_MAX_SIZE
27 #define HEAP_MAX_SIZE (1024*1024) /* must be a power of two */
28 #endif
29
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. */
36
37
38 #ifndef THREAD_STATS
39 #define THREAD_STATS 0
40 #endif
41
42 /* If THREAD_STATS is non-zero, some statistics on mutex locking are
43 computed. */
44
45 /***************************************************************************/
46
47 #define top(ar_ptr) ((ar_ptr)->top)
48
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
52 USE_ARENAS. */
53
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 size_t pad; /* Make sure the following data is properly aligned. */
59 } heap_info;
60
61 /* Thread specific data */
62
63 static tsd_key_t arena_key;
64 static mutex_t list_lock;
65
66 #if THREAD_STATS
67 static int stat_n_heaps;
68 #define THREAD_STAT(x) x
69 #else
70 #define THREAD_STAT(x) do ; while(0)
71 #endif
72
73 /* Mapped memory in non-main arenas (reliable only for NO_THREADS). */
74 static unsigned long arena_mem;
75
76 /* Already initialized? */
77 int __malloc_initialized = -1;
78
79 /**************************************************************************/
80
81 #if USE_ARENAS
82
83 /* arena_get() acquires an arena and locks the corresponding mutex.
84 First, try the one last locked successfully by this thread. (This
85 is the common case and handled with a macro for speed.) Then, loop
86 once over the circularly linked list of arenas. If no arena is
87 readily available, create a new one. In this latter case, `size'
88 is just a hint as to how much memory will be required immediately
89 in the new arena. */
90
91 #define arena_get(ptr, size) do { \
92 Void_t *vptr = NULL; \
93 ptr = (mstate)tsd_getspecific(arena_key, vptr); \
94 if(ptr && !mutex_trylock(&ptr->mutex)) { \
95 THREAD_STAT(++(ptr->stat_lock_direct)); \
96 } else \
97 ptr = arena_get2(ptr, (size)); \
98 } while(0)
99
100 /* find the heap and corresponding arena for a given ptr */
101
102 #define heap_for_ptr(ptr) \
103 ((heap_info *)((unsigned long)(ptr) & ~(HEAP_MAX_SIZE-1)))
104 #define arena_for_chunk(ptr) \
105 (chunk_non_main_arena(ptr) ? heap_for_ptr(ptr)->ar_ptr : &main_arena)
106
107 #else /* !USE_ARENAS */
108
109 /* There is only one arena, main_arena. */
110
111 #if THREAD_STATS
112 #define arena_get(ar_ptr, sz) do { \
113 ar_ptr = &main_arena; \
114 if(!mutex_trylock(&ar_ptr->mutex)) \
115 ++(ar_ptr->stat_lock_direct); \
116 else { \
117 (void)mutex_lock(&ar_ptr->mutex); \
118 ++(ar_ptr->stat_lock_wait); \
119 } \
120 } while(0)
121 #else
122 #define arena_get(ar_ptr, sz) do { \
123 ar_ptr = &main_arena; \
124 (void)mutex_lock(&ar_ptr->mutex); \
125 } while(0)
126 #endif
127 #define arena_for_chunk(ptr) (&main_arena)
128
129 #endif /* USE_ARENAS */
130
131 /**************************************************************************/
132
133 #ifndef NO_THREADS
134
135 /* atfork support. */
136
137 static __malloc_ptr_t (*save_malloc_hook) (size_t __size,
138 __const __malloc_ptr_t);
139 # if !defined _LIBC || !defined USE_TLS || (defined SHARED && !USE___THREAD)
140 static __malloc_ptr_t (*save_memalign_hook) (size_t __align, size_t __size,
141 __const __malloc_ptr_t);
142 # endif
143 static void (*save_free_hook) (__malloc_ptr_t __ptr,
144 __const __malloc_ptr_t);
145 static Void_t* save_arena;
146
147 /* Magic value for the thread-specific arena pointer when
148 malloc_atfork() is in use. */
149
150 #define ATFORK_ARENA_PTR ((Void_t*)-1)
151
152 /* The following hooks are used while the `atfork' handling mechanism
153 is active. */
154
155 static Void_t*
156 malloc_atfork(size_t sz, const Void_t *caller)
157 {
158 Void_t *vptr = NULL;
159 Void_t *victim;
160
161 tsd_getspecific(arena_key, vptr);
162 if(vptr == ATFORK_ARENA_PTR) {
163 /* We are the only thread that may allocate at all. */
164 if(save_malloc_hook != malloc_check) {
165 return _int_malloc(&main_arena, sz);
166 } else {
167 if(top_check()<0)
168 return 0;
169 victim = _int_malloc(&main_arena, sz+1);
170 return mem2mem_check(victim, sz);
171 }
172 } else {
173 /* Suspend the thread until the `atfork' handlers have completed.
174 By that time, the hooks will have been reset as well, so that
175 mALLOc() can be used again. */
176 (void)mutex_lock(&list_lock);
177 (void)mutex_unlock(&list_lock);
178 return public_mALLOc(sz);
179 }
180 }
181
182 static void
183 free_atfork(Void_t* mem, const Void_t *caller)
184 {
185 Void_t *vptr = NULL;
186 mstate ar_ptr;
187 mchunkptr p; /* chunk corresponding to mem */
188
189 if (mem == 0) /* free(0) has no effect */
190 return;
191
192 p = mem2chunk(mem); /* do not bother to replicate free_check here */
193
194 #if HAVE_MMAP
195 if (chunk_is_mmapped(p)) /* release mmapped memory. */
196 {
197 munmap_chunk(p);
198 return;
199 }
200 #endif
201
202 ar_ptr = arena_for_chunk(p);
203 tsd_getspecific(arena_key, vptr);
204 if(vptr != ATFORK_ARENA_PTR)
205 (void)mutex_lock(&ar_ptr->mutex);
206 _int_free(ar_ptr, mem);
207 if(vptr != ATFORK_ARENA_PTR)
208 (void)mutex_unlock(&ar_ptr->mutex);
209 }
210
211 /* The following two functions are registered via thread_atfork() to
212 make sure that the mutexes remain in a consistent state in the
213 fork()ed version of a thread. Also adapt the malloc and free hooks
214 temporarily, because the `atfork' handler mechanism may use
215 malloc/free internally (e.g. in LinuxThreads). */
216
217 static void
218 ptmalloc_lock_all (void)
219 {
220 mstate ar_ptr;
221
222 if(__malloc_initialized < 1)
223 return;
224 (void)mutex_lock(&list_lock);
225 for(ar_ptr = &main_arena;;) {
226 (void)mutex_lock(&ar_ptr->mutex);
227 ar_ptr = ar_ptr->next;
228 if(ar_ptr == &main_arena) break;
229 }
230 save_malloc_hook = __malloc_hook;
231 save_free_hook = __free_hook;
232 __malloc_hook = malloc_atfork;
233 __free_hook = free_atfork;
234 /* Only the current thread may perform malloc/free calls now. */
235 tsd_getspecific(arena_key, save_arena);
236 tsd_setspecific(arena_key, ATFORK_ARENA_PTR);
237 }
238
239 static void
240 ptmalloc_unlock_all (void)
241 {
242 mstate ar_ptr;
243
244 if(__malloc_initialized < 1)
245 return;
246 tsd_setspecific(arena_key, save_arena);
247 __malloc_hook = save_malloc_hook;
248 __free_hook = save_free_hook;
249 for(ar_ptr = &main_arena;;) {
250 (void)mutex_unlock(&ar_ptr->mutex);
251 ar_ptr = ar_ptr->next;
252 if(ar_ptr == &main_arena) break;
253 }
254 (void)mutex_unlock(&list_lock);
255 }
256
257 #ifdef __linux__
258
259 /* In LinuxThreads, unlocking a mutex in the child process after a
260 fork() is currently unsafe, whereas re-initializing it is safe and
261 does not leak resources. Therefore, a special atfork handler is
262 installed for the child. */
263
264 static void
265 ptmalloc_unlock_all2 (void)
266 {
267 mstate ar_ptr;
268
269 if(__malloc_initialized < 1)
270 return;
271 #if defined _LIBC || defined MALLOC_HOOKS
272 tsd_setspecific(arena_key, save_arena);
273 __malloc_hook = save_malloc_hook;
274 __free_hook = save_free_hook;
275 #endif
276 for(ar_ptr = &main_arena;;) {
277 mutex_init(&ar_ptr->mutex);
278 ar_ptr = ar_ptr->next;
279 if(ar_ptr == &main_arena) break;
280 }
281 mutex_init(&list_lock);
282 }
283
284 #else
285
286 #define ptmalloc_unlock_all2 ptmalloc_unlock_all
287
288 #endif
289
290 #endif /* !defined NO_THREADS */
291
292 /* Initialization routine. */
293 #ifdef _LIBC
294 #include <string.h>
295 extern char **_environ;
296
297 static char *
298 internal_function
299 next_env_entry (char ***position)
300 {
301 char **current = *position;
302 char *result = NULL;
303
304 while (*current != NULL)
305 {
306 if (__builtin_expect ((*current)[0] == 'M', 0)
307 && (*current)[1] == 'A'
308 && (*current)[2] == 'L'
309 && (*current)[3] == 'L'
310 && (*current)[4] == 'O'
311 && (*current)[5] == 'C'
312 && (*current)[6] == '_')
313 {
314 result = &(*current)[7];
315
316 /* Save current position for next visit. */
317 *position = ++current;
318
319 break;
320 }
321
322 ++current;
323 }
324
325 return result;
326 }
327 #endif /* _LIBC */
328
329 /* Set up basic state so that _int_malloc et al can work. */
330 static void
331 ptmalloc_init_minimal (void)
332 {
333 #if DEFAULT_TOP_PAD != 0
334 mp_.top_pad = DEFAULT_TOP_PAD;
335 #endif
336 mp_.n_mmaps_max = DEFAULT_MMAP_MAX;
337 mp_.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
338 mp_.trim_threshold = DEFAULT_TRIM_THRESHOLD;
339 mp_.pagesize = malloc_getpagesize;
340 }
341
342 #ifdef _LIBC
343 # if defined SHARED && defined USE_TLS && !USE___THREAD
344 # include <stdbool.h>
345
346 /* This is called by __pthread_initialize_minimal when it needs to use
347 malloc to set up the TLS state. We cannot do the full work of
348 ptmalloc_init (below) until __pthread_initialize_minimal has finished,
349 so it has to switch to using the special startup-time hooks while doing
350 those allocations. */
351 void
352 __libc_malloc_pthread_startup (bool first_time)
353 {
354 if (first_time)
355 {
356 ptmalloc_init_minimal ();
357 save_malloc_hook = __malloc_hook;
358 save_memalign_hook = __memalign_hook;
359 save_free_hook = __free_hook;
360 __malloc_hook = malloc_starter;
361 __memalign_hook = memalign_starter;
362 __free_hook = free_starter;
363 }
364 else
365 {
366 __malloc_hook = save_malloc_hook;
367 __memalign_hook = save_memalign_hook;
368 __free_hook = save_free_hook;
369 }
370 }
371 # endif
372 #endif
373
374 static void
375 ptmalloc_init (void)
376 {
377 #if __STD_C
378 const char* s;
379 #else
380 char* s;
381 #endif
382 int secure = 0;
383
384 if(__malloc_initialized >= 0) return;
385 __malloc_initialized = 0;
386
387 #ifdef _LIBC
388 # if defined SHARED && defined USE_TLS && !USE___THREAD
389 /* ptmalloc_init_minimal may already have been called via
390 __libc_malloc_pthread_startup, above. */
391 if (mp_.pagesize == 0)
392 # endif
393 #endif
394 ptmalloc_init_minimal();
395
396 #ifndef NO_THREADS
397 # if defined _LIBC && defined USE_TLS
398 /* We know __pthread_initialize_minimal has already been called,
399 and that is enough. */
400 # define NO_STARTER
401 # endif
402 # ifndef NO_STARTER
403 /* With some threads implementations, creating thread-specific data
404 or initializing a mutex may call malloc() itself. Provide a
405 simple starter version (realloc() won't work). */
406 save_malloc_hook = __malloc_hook;
407 save_memalign_hook = __memalign_hook;
408 save_free_hook = __free_hook;
409 __malloc_hook = malloc_starter;
410 __memalign_hook = memalign_starter;
411 __free_hook = free_starter;
412 # ifdef _LIBC
413 /* Initialize the pthreads interface. */
414 if (__pthread_initialize != NULL)
415 __pthread_initialize();
416 # endif /* !defined _LIBC */
417 # endif /* !defined NO_STARTER */
418 #endif /* !defined NO_THREADS */
419 mutex_init(&main_arena.mutex);
420 main_arena.next = &main_arena;
421
422 mutex_init(&list_lock);
423 tsd_key_create(&arena_key, NULL);
424 tsd_setspecific(arena_key, (Void_t *)&main_arena);
425 thread_atfork(ptmalloc_lock_all, ptmalloc_unlock_all, ptmalloc_unlock_all2);
426 #ifndef NO_THREADS
427 # ifndef NO_STARTER
428 __malloc_hook = save_malloc_hook;
429 __memalign_hook = save_memalign_hook;
430 __free_hook = save_free_hook;
431 # else
432 # undef NO_STARTER
433 # endif
434 #endif
435 #ifdef _LIBC
436 secure = __libc_enable_secure;
437 s = NULL;
438 if (__builtin_expect (_environ != NULL, 1))
439 {
440 char **runp = _environ;
441 char *envline;
442
443 while (__builtin_expect ((envline = next_env_entry (&runp)) != NULL,
444 0))
445 {
446 size_t len = strcspn (envline, "=");
447
448 if (envline[len] != '=')
449 /* This is a "MALLOC_" variable at the end of the string
450 without a '=' character. Ignore it since otherwise we
451 will access invalid memory below. */
452 continue;
453
454 switch (len)
455 {
456 case 6:
457 if (memcmp (envline, "CHECK_", 6) == 0)
458 s = &envline[7];
459 break;
460 case 8:
461 if (! secure && memcmp (envline, "TOP_PAD_", 8) == 0)
462 mALLOPt(M_TOP_PAD, atoi(&envline[9]));
463 break;
464 case 9:
465 if (! secure && memcmp (envline, "MMAP_MAX_", 9) == 0)
466 mALLOPt(M_MMAP_MAX, atoi(&envline[10]));
467 break;
468 case 15:
469 if (! secure)
470 {
471 if (memcmp (envline, "TRIM_THRESHOLD_", 15) == 0)
472 mALLOPt(M_TRIM_THRESHOLD, atoi(&envline[16]));
473 else if (memcmp (envline, "MMAP_THRESHOLD_", 15) == 0)
474 mALLOPt(M_MMAP_THRESHOLD, atoi(&envline[16]));
475 }
476 break;
477 default:
478 break;
479 }
480 }
481 }
482 #else
483 if (! secure)
484 {
485 if((s = getenv("MALLOC_TRIM_THRESHOLD_")))
486 mALLOPt(M_TRIM_THRESHOLD, atoi(s));
487 if((s = getenv("MALLOC_TOP_PAD_")))
488 mALLOPt(M_TOP_PAD, atoi(s));
489 if((s = getenv("MALLOC_MMAP_THRESHOLD_")))
490 mALLOPt(M_MMAP_THRESHOLD, atoi(s));
491 if((s = getenv("MALLOC_MMAP_MAX_")))
492 mALLOPt(M_MMAP_MAX, atoi(s));
493 }
494 s = getenv("MALLOC_CHECK_");
495 #endif
496 if(s) {
497 if(s[0]) mALLOPt(M_CHECK_ACTION, (int)(s[0] - '0'));
498 if (check_action != 0)
499 __malloc_check_init();
500 }
501 if(__malloc_initialize_hook != NULL)
502 (*__malloc_initialize_hook)();
503 __malloc_initialized = 1;
504 }
505
506 /* There are platforms (e.g. Hurd) with a link-time hook mechanism. */
507 #ifdef thread_atfork_static
508 thread_atfork_static(ptmalloc_lock_all, ptmalloc_unlock_all, \
509 ptmalloc_unlock_all2)
510 #endif
511
512 \f
513
514 /* Managing heaps and arenas (for concurrent threads) */
515
516 #if USE_ARENAS
517
518 #if MALLOC_DEBUG > 1
519
520 /* Print the complete contents of a single heap to stderr. */
521
522 static void
523 #if __STD_C
524 dump_heap(heap_info *heap)
525 #else
526 dump_heap(heap) heap_info *heap;
527 #endif
528 {
529 char *ptr;
530 mchunkptr p;
531
532 fprintf(stderr, "Heap %p, size %10lx:\n", heap, (long)heap->size);
533 ptr = (heap->ar_ptr != (mstate)(heap+1)) ?
534 (char*)(heap + 1) : (char*)(heap + 1) + sizeof(struct malloc_state);
535 p = (mchunkptr)(((unsigned long)ptr + MALLOC_ALIGN_MASK) &
536 ~MALLOC_ALIGN_MASK);
537 for(;;) {
538 fprintf(stderr, "chunk %p size %10lx", p, (long)p->size);
539 if(p == top(heap->ar_ptr)) {
540 fprintf(stderr, " (top)\n");
541 break;
542 } else if(p->size == (0|PREV_INUSE)) {
543 fprintf(stderr, " (fence)\n");
544 break;
545 }
546 fprintf(stderr, "\n");
547 p = next_chunk(p);
548 }
549 }
550
551 #endif /* MALLOC_DEBUG > 1 */
552
553 /* If consecutive mmap (0, HEAP_MAX_SIZE << 1, ...) calls return decreasing
554 addresses as opposed to increasing, new_heap would badly fragment the
555 address space. In that case remember the second HEAP_MAX_SIZE part
556 aligned to HEAP_MAX_SIZE from last mmap (0, HEAP_MAX_SIZE << 1, ...)
557 call (if it is already aligned) and try to reuse it next time. We need
558 no locking for it, as kernel ensures the atomicity for us - worst case
559 we'll call mmap (addr, HEAP_MAX_SIZE, ...) for some value of addr in
560 multiple threads, but only one will succeed. */
561 static char *aligned_heap_area;
562
563 /* Create a new heap. size is automatically rounded up to a multiple
564 of the page size. */
565
566 static heap_info *
567 internal_function
568 #if __STD_C
569 new_heap(size_t size, size_t top_pad)
570 #else
571 new_heap(size, top_pad) size_t size, top_pad;
572 #endif
573 {
574 size_t page_mask = malloc_getpagesize - 1;
575 char *p1, *p2;
576 unsigned long ul;
577 heap_info *h;
578
579 if(size+top_pad < HEAP_MIN_SIZE)
580 size = HEAP_MIN_SIZE;
581 else if(size+top_pad <= HEAP_MAX_SIZE)
582 size += top_pad;
583 else if(size > HEAP_MAX_SIZE)
584 return 0;
585 else
586 size = HEAP_MAX_SIZE;
587 size = (size + page_mask) & ~page_mask;
588
589 /* A memory region aligned to a multiple of HEAP_MAX_SIZE is needed.
590 No swap space needs to be reserved for the following large
591 mapping (on Linux, this is the case for all non-writable mappings
592 anyway). */
593 p2 = MAP_FAILED;
594 if(aligned_heap_area) {
595 p2 = (char *)MMAP(aligned_heap_area, HEAP_MAX_SIZE, PROT_NONE,
596 MAP_PRIVATE|MAP_NORESERVE);
597 aligned_heap_area = NULL;
598 if (p2 != MAP_FAILED && ((unsigned long)p2 & (HEAP_MAX_SIZE-1))) {
599 munmap(p2, HEAP_MAX_SIZE);
600 p2 = MAP_FAILED;
601 }
602 }
603 if(p2 == MAP_FAILED) {
604 p1 = (char *)MMAP(0, HEAP_MAX_SIZE<<1, PROT_NONE,
605 MAP_PRIVATE|MAP_NORESERVE);
606 if(p1 != MAP_FAILED) {
607 p2 = (char *)(((unsigned long)p1 + (HEAP_MAX_SIZE-1))
608 & ~(HEAP_MAX_SIZE-1));
609 ul = p2 - p1;
610 if (ul)
611 munmap(p1, ul);
612 else
613 aligned_heap_area = p2 + HEAP_MAX_SIZE;
614 munmap(p2 + HEAP_MAX_SIZE, HEAP_MAX_SIZE - ul);
615 } else {
616 /* Try to take the chance that an allocation of only HEAP_MAX_SIZE
617 is already aligned. */
618 p2 = (char *)MMAP(0, HEAP_MAX_SIZE, PROT_NONE, MAP_PRIVATE|MAP_NORESERVE);
619 if(p2 == MAP_FAILED)
620 return 0;
621 if((unsigned long)p2 & (HEAP_MAX_SIZE-1)) {
622 munmap(p2, HEAP_MAX_SIZE);
623 return 0;
624 }
625 }
626 }
627 if(mprotect(p2, size, PROT_READ|PROT_WRITE) != 0) {
628 munmap(p2, HEAP_MAX_SIZE);
629 return 0;
630 }
631 h = (heap_info *)p2;
632 h->size = size;
633 THREAD_STAT(stat_n_heaps++);
634 return h;
635 }
636
637 /* Grow or shrink a heap. size is automatically rounded up to a
638 multiple of the page size if it is positive. */
639
640 static int
641 #if __STD_C
642 grow_heap(heap_info *h, long diff)
643 #else
644 grow_heap(h, diff) heap_info *h; long diff;
645 #endif
646 {
647 size_t page_mask = malloc_getpagesize - 1;
648 long new_size;
649
650 if(diff >= 0) {
651 diff = (diff + page_mask) & ~page_mask;
652 new_size = (long)h->size + diff;
653 if(new_size > HEAP_MAX_SIZE)
654 return -1;
655 if(mprotect((char *)h + h->size, diff, PROT_READ|PROT_WRITE) != 0)
656 return -2;
657 } else {
658 new_size = (long)h->size + diff;
659 if(new_size < (long)sizeof(*h))
660 return -1;
661 /* Try to re-map the extra heap space freshly to save memory, and
662 make it inaccessible. */
663 if((char *)MMAP((char *)h + new_size, -diff, PROT_NONE,
664 MAP_PRIVATE|MAP_FIXED) == (char *) MAP_FAILED)
665 return -2;
666 /*fprintf(stderr, "shrink %p %08lx\n", h, new_size);*/
667 }
668 h->size = new_size;
669 return 0;
670 }
671
672 /* Delete a heap. */
673
674 #define delete_heap(heap) \
675 do { \
676 if ((char *)(heap) + HEAP_MAX_SIZE == aligned_heap_area) \
677 aligned_heap_area = NULL; \
678 munmap((char*)(heap), HEAP_MAX_SIZE); \
679 } while (0)
680
681 static int
682 internal_function
683 #if __STD_C
684 heap_trim(heap_info *heap, size_t pad)
685 #else
686 heap_trim(heap, pad) heap_info *heap; size_t pad;
687 #endif
688 {
689 mstate ar_ptr = heap->ar_ptr;
690 unsigned long pagesz = mp_.pagesize;
691 mchunkptr top_chunk = top(ar_ptr), p, bck, fwd;
692 heap_info *prev_heap;
693 long new_size, top_size, extra;
694
695 /* Can this heap go away completely? */
696 while(top_chunk == chunk_at_offset(heap, sizeof(*heap))) {
697 prev_heap = heap->prev;
698 p = chunk_at_offset(prev_heap, prev_heap->size - (MINSIZE-2*SIZE_SZ));
699 assert(p->size == (0|PREV_INUSE)); /* must be fencepost */
700 p = prev_chunk(p);
701 new_size = chunksize(p) + (MINSIZE-2*SIZE_SZ);
702 assert(new_size>0 && new_size<(long)(2*MINSIZE));
703 if(!prev_inuse(p))
704 new_size += p->prev_size;
705 assert(new_size>0 && new_size<HEAP_MAX_SIZE);
706 if(new_size + (HEAP_MAX_SIZE - prev_heap->size) < pad + MINSIZE + pagesz)
707 break;
708 ar_ptr->system_mem -= heap->size;
709 arena_mem -= heap->size;
710 delete_heap(heap);
711 heap = prev_heap;
712 if(!prev_inuse(p)) { /* consolidate backward */
713 p = prev_chunk(p);
714 unlink(p, bck, fwd);
715 }
716 assert(((unsigned long)((char*)p + new_size) & (pagesz-1)) == 0);
717 assert( ((char*)p + new_size) == ((char*)heap + heap->size) );
718 top(ar_ptr) = top_chunk = p;
719 set_head(top_chunk, new_size | PREV_INUSE);
720 /*check_chunk(ar_ptr, top_chunk);*/
721 }
722 top_size = chunksize(top_chunk);
723 extra = ((top_size - pad - MINSIZE + (pagesz-1))/pagesz - 1) * pagesz;
724 if(extra < (long)pagesz)
725 return 0;
726 /* Try to shrink. */
727 if(grow_heap(heap, -extra) != 0)
728 return 0;
729 ar_ptr->system_mem -= extra;
730 arena_mem -= extra;
731
732 /* Success. Adjust top accordingly. */
733 set_head(top_chunk, (top_size - extra) | PREV_INUSE);
734 /*check_chunk(ar_ptr, top_chunk);*/
735 return 1;
736 }
737
738 static mstate
739 internal_function
740 #if __STD_C
741 arena_get2(mstate a_tsd, size_t size)
742 #else
743 arena_get2(a_tsd, size) mstate a_tsd; size_t size;
744 #endif
745 {
746 mstate a;
747
748 if(!a_tsd)
749 a = a_tsd = &main_arena;
750 else {
751 a = a_tsd->next;
752 if(!a) {
753 /* This can only happen while initializing the new arena. */
754 (void)mutex_lock(&main_arena.mutex);
755 THREAD_STAT(++(main_arena.stat_lock_wait));
756 return &main_arena;
757 }
758 }
759
760 /* Check the global, circularly linked list for available arenas. */
761 repeat:
762 do {
763 if(!mutex_trylock(&a->mutex)) {
764 THREAD_STAT(++(a->stat_lock_loop));
765 tsd_setspecific(arena_key, (Void_t *)a);
766 return a;
767 }
768 a = a->next;
769 } while(a != a_tsd);
770
771 /* If not even the list_lock can be obtained, try again. This can
772 happen during `atfork', or for example on systems where thread
773 creation makes it temporarily impossible to obtain _any_
774 locks. */
775 if(mutex_trylock(&list_lock)) {
776 a = a_tsd;
777 goto repeat;
778 }
779 (void)mutex_unlock(&list_lock);
780
781 /* Nothing immediately available, so generate a new arena. */
782 a = _int_new_arena(size);
783 if(!a)
784 return 0;
785
786 tsd_setspecific(arena_key, (Void_t *)a);
787 mutex_init(&a->mutex);
788 mutex_lock(&a->mutex); /* remember result */
789
790 /* Add the new arena to the global list. */
791 (void)mutex_lock(&list_lock);
792 a->next = main_arena.next;
793 atomic_write_barrier ();
794 main_arena.next = a;
795 (void)mutex_unlock(&list_lock);
796
797 THREAD_STAT(++(a->stat_lock_loop));
798 return a;
799 }
800
801 /* Create a new arena with initial size "size". */
802
803 mstate
804 _int_new_arena(size_t size)
805 {
806 mstate a;
807 heap_info *h;
808 char *ptr;
809 unsigned long misalign;
810
811 h = new_heap(size + (sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT),
812 mp_.top_pad);
813 if(!h) {
814 /* Maybe size is too large to fit in a single heap. So, just try
815 to create a minimally-sized arena and let _int_malloc() attempt
816 to deal with the large request via mmap_chunk(). */
817 h = new_heap(sizeof(*h) + sizeof(*a) + MALLOC_ALIGNMENT, mp_.top_pad);
818 if(!h)
819 return 0;
820 }
821 a = h->ar_ptr = (mstate)(h+1);
822 malloc_init_state(a);
823 /*a->next = NULL;*/
824 a->system_mem = a->max_system_mem = h->size;
825 arena_mem += h->size;
826 #ifdef NO_THREADS
827 if((unsigned long)(mp_.mmapped_mem + arena_mem + main_arena.system_mem) >
828 mp_.max_total_mem)
829 mp_.max_total_mem = mp_.mmapped_mem + arena_mem + main_arena.system_mem;
830 #endif
831
832 /* Set up the top chunk, with proper alignment. */
833 ptr = (char *)(a + 1);
834 misalign = (unsigned long)chunk2mem(ptr) & MALLOC_ALIGN_MASK;
835 if (misalign > 0)
836 ptr += MALLOC_ALIGNMENT - misalign;
837 top(a) = (mchunkptr)ptr;
838 set_head(top(a), (((char*)h + h->size) - ptr) | PREV_INUSE);
839
840 return a;
841 }
842
843 #endif /* USE_ARENAS */
844
845 /*
846 * Local variables:
847 * c-basic-offset: 2
848 * End:
849 */