1 | /* Malloc implementation for multiple threads without lock contention. |
2 | Copyright (C) 2001-2021 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 |
18 | not, see <https://www.gnu.org/licenses/>. */ |
19 | |
20 | #include <stdbool.h> |
21 | |
22 | #if HAVE_TUNABLES |
23 | # define TUNABLE_NAMESPACE malloc |
24 | #endif |
25 | #include <elf/dl-tunables.h> |
26 | |
27 | /* Compile-time constants. */ |
28 | |
29 | #define HEAP_MIN_SIZE (32 * 1024) |
30 | #ifndef HEAP_MAX_SIZE |
31 | # ifdef DEFAULT_MMAP_THRESHOLD_MAX |
32 | # define HEAP_MAX_SIZE (2 * DEFAULT_MMAP_THRESHOLD_MAX) |
33 | # else |
34 | # define HEAP_MAX_SIZE (1024 * 1024) /* must be a power of two */ |
35 | # endif |
36 | #endif |
37 | |
38 | /* HEAP_MIN_SIZE and HEAP_MAX_SIZE limit the size of mmap()ed heaps |
39 | that are dynamically created for multi-threaded programs. The |
40 | maximum size must be a power of two, for fast determination of |
41 | which heap belongs to a chunk. It should be much larger than the |
42 | mmap threshold, so that requests with a size just below that |
43 | threshold can be fulfilled without creating too many heaps. */ |
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. */ |
52 | |
53 | typedef struct _heap_info |
54 | { |
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 mprotect_size; /* Size in bytes that has been mprotected |
59 | PROT_READ|PROT_WRITE. */ |
60 | /* Make sure the following data is properly aligned, particularly |
61 | that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of |
62 | MALLOC_ALIGNMENT. */ |
63 | char pad[-6 * SIZE_SZ & MALLOC_ALIGN_MASK]; |
64 | } heap_info; |
65 | |
66 | /* Get a compile-time error if the heap_info padding is not correct |
67 | to make alignment work as expected in sYSMALLOc. */ |
68 | extern int sanity_check_heap_info_alignment[(sizeof (heap_info) |
69 | + 2 * SIZE_SZ) % MALLOC_ALIGNMENT |
70 | ? -1 : 1]; |
71 | |
72 | /* Thread specific data. */ |
73 | |
74 | static __thread mstate thread_arena attribute_tls_model_ie; |
75 | |
76 | /* Arena free list. free_list_lock synchronizes access to the |
77 | free_list variable below, and the next_free and attached_threads |
78 | members of struct malloc_state objects. No other locks must be |
79 | acquired after free_list_lock has been acquired. */ |
80 | |
81 | __libc_lock_define_initialized (static, free_list_lock); |
82 | #if IS_IN (libc) |
83 | static size_t narenas = 1; |
84 | #endif |
85 | static mstate free_list; |
86 | |
87 | /* list_lock prevents concurrent writes to the next member of struct |
88 | malloc_state objects. |
89 | |
90 | Read access to the next member is supposed to synchronize with the |
91 | atomic_write_barrier and the write to the next member in |
92 | _int_new_arena. This suffers from data races; see the FIXME |
93 | comments in _int_new_arena and reused_arena. |
94 | |
95 | list_lock also prevents concurrent forks. At the time list_lock is |
96 | acquired, no arena lock must have been acquired, but it is |
97 | permitted to acquire arena locks subsequently, while list_lock is |
98 | acquired. */ |
99 | __libc_lock_define_initialized (static, list_lock); |
100 | |
101 | /* Already initialized? */ |
102 | static bool __malloc_initialized = false; |
103 | |
104 | /**************************************************************************/ |
105 | |
106 | |
107 | /* arena_get() acquires an arena and locks the corresponding mutex. |
108 | First, try the one last locked successfully by this thread. (This |
109 | is the common case and handled with a macro for speed.) Then, loop |
110 | once over the circularly linked list of arenas. If no arena is |
111 | readily available, create a new one. In this latter case, `size' |
112 | is just a hint as to how much memory will be required immediately |
113 | in the new arena. */ |
114 | |
115 | #define arena_get(ptr, size) do { \ |
116 | ptr = thread_arena; \ |
117 | arena_lock (ptr, size); \ |
118 | } while (0) |
119 | |
120 | #define arena_lock(ptr, size) do { \ |
121 | if (ptr) \ |
122 | __libc_lock_lock (ptr->mutex); \ |
123 | else \ |
124 | ptr = arena_get2 ((size), NULL); \ |
125 | } while (0) |
126 | |
127 | /* find the heap and corresponding arena for a given ptr */ |
128 | |
129 | #define heap_for_ptr(ptr) \ |
130 | ((heap_info *) ((unsigned long) (ptr) & ~(HEAP_MAX_SIZE - 1))) |
131 | #define arena_for_chunk(ptr) \ |
132 | (chunk_main_arena (ptr) ? &main_arena : heap_for_ptr (ptr)->ar_ptr) |
133 | |
134 | |
135 | /**************************************************************************/ |
136 | |
137 | /* atfork support. */ |
138 | |
139 | /* The following three functions are called around fork from a |
140 | multi-threaded process. We do not use the general fork handler |
141 | mechanism to make sure that our handlers are the last ones being |
142 | called, so that other fork handlers can use the malloc |
143 | subsystem. */ |
144 | |
145 | void |
146 | __malloc_fork_lock_parent (void) |
147 | { |
148 | if (!__malloc_initialized) |
149 | return; |
150 | |
151 | /* We do not acquire free_list_lock here because we completely |
152 | reconstruct free_list in __malloc_fork_unlock_child. */ |
153 | |
154 | __libc_lock_lock (list_lock); |
155 | |
156 | for (mstate ar_ptr = &main_arena;; ) |
157 | { |
158 | __libc_lock_lock (ar_ptr->mutex); |
159 | ar_ptr = ar_ptr->next; |
160 | if (ar_ptr == &main_arena) |
161 | break; |
162 | } |
163 | } |
164 | |
165 | void |
166 | __malloc_fork_unlock_parent (void) |
167 | { |
168 | if (!__malloc_initialized) |
169 | return; |
170 | |
171 | for (mstate ar_ptr = &main_arena;; ) |
172 | { |
173 | __libc_lock_unlock (ar_ptr->mutex); |
174 | ar_ptr = ar_ptr->next; |
175 | if (ar_ptr == &main_arena) |
176 | break; |
177 | } |
178 | __libc_lock_unlock (list_lock); |
179 | } |
180 | |
181 | void |
182 | __malloc_fork_unlock_child (void) |
183 | { |
184 | if (!__malloc_initialized) |
185 | return; |
186 | |
187 | /* Push all arenas to the free list, except thread_arena, which is |
188 | attached to the current thread. */ |
189 | __libc_lock_init (free_list_lock); |
190 | if (thread_arena != NULL) |
191 | thread_arena->attached_threads = 1; |
192 | free_list = NULL; |
193 | for (mstate ar_ptr = &main_arena;; ) |
194 | { |
195 | __libc_lock_init (ar_ptr->mutex); |
196 | if (ar_ptr != thread_arena) |
197 | { |
198 | /* This arena is no longer attached to any thread. */ |
199 | ar_ptr->attached_threads = 0; |
200 | ar_ptr->next_free = free_list; |
201 | free_list = ar_ptr; |
202 | } |
203 | ar_ptr = ar_ptr->next; |
204 | if (ar_ptr == &main_arena) |
205 | break; |
206 | } |
207 | |
208 | __libc_lock_init (list_lock); |
209 | } |
210 | |
211 | #if HAVE_TUNABLES |
212 | # define TUNABLE_CALLBACK_FNDECL(__name, __type) \ |
213 | static inline int do_ ## __name (__type value); \ |
214 | static void \ |
215 | TUNABLE_CALLBACK (__name) (tunable_val_t *valp) \ |
216 | { \ |
217 | __type value = (__type) (valp)->numval; \ |
218 | do_ ## __name (value); \ |
219 | } |
220 | |
221 | TUNABLE_CALLBACK_FNDECL (set_mmap_threshold, size_t) |
222 | TUNABLE_CALLBACK_FNDECL (set_mmaps_max, int32_t) |
223 | TUNABLE_CALLBACK_FNDECL (set_top_pad, size_t) |
224 | TUNABLE_CALLBACK_FNDECL (set_perturb_byte, int32_t) |
225 | TUNABLE_CALLBACK_FNDECL (set_trim_threshold, size_t) |
226 | TUNABLE_CALLBACK_FNDECL (set_arena_max, size_t) |
227 | TUNABLE_CALLBACK_FNDECL (set_arena_test, size_t) |
228 | #if USE_TCACHE |
229 | TUNABLE_CALLBACK_FNDECL (set_tcache_max, size_t) |
230 | TUNABLE_CALLBACK_FNDECL (set_tcache_count, size_t) |
231 | TUNABLE_CALLBACK_FNDECL (set_tcache_unsorted_limit, size_t) |
232 | #endif |
233 | TUNABLE_CALLBACK_FNDECL (set_mxfast, size_t) |
234 | #else |
235 | /* Initialization routine. */ |
236 | #include <string.h> |
237 | extern char **_environ; |
238 | |
239 | static char * |
240 | next_env_entry (char ***position) |
241 | { |
242 | char **current = *position; |
243 | char *result = NULL; |
244 | |
245 | while (*current != NULL) |
246 | { |
247 | if (__builtin_expect ((*current)[0] == 'M', 0) |
248 | && (*current)[1] == 'A' |
249 | && (*current)[2] == 'L' |
250 | && (*current)[3] == 'L' |
251 | && (*current)[4] == 'O' |
252 | && (*current)[5] == 'C' |
253 | && (*current)[6] == '_') |
254 | { |
255 | result = &(*current)[7]; |
256 | |
257 | /* Save current position for next visit. */ |
258 | *position = ++current; |
259 | |
260 | break; |
261 | } |
262 | |
263 | ++current; |
264 | } |
265 | |
266 | return result; |
267 | } |
268 | #endif |
269 | |
270 | |
271 | #ifdef SHARED |
272 | extern struct dl_open_hook *_dl_open_hook; |
273 | libc_hidden_proto (_dl_open_hook); |
274 | #endif |
275 | |
276 | #if USE_TCACHE |
277 | static void tcache_key_initialize (void); |
278 | #endif |
279 | |
280 | static void |
281 | ptmalloc_init (void) |
282 | { |
283 | if (__malloc_initialized) |
284 | return; |
285 | |
286 | __malloc_initialized = true; |
287 | |
288 | #if USE_TCACHE |
289 | tcache_key_initialize (); |
290 | #endif |
291 | |
292 | #ifdef USE_MTAG |
293 | if ((TUNABLE_GET_FULL (glibc, mem, tagging, int32_t, NULL) & 1) != 0) |
294 | { |
295 | /* If the tunable says that we should be using tagged memory |
296 | and that morecore does not support tagged regions, then |
297 | disable it. */ |
298 | if (__MTAG_SBRK_UNTAGGED) |
299 | __always_fail_morecore = true; |
300 | |
301 | mtag_enabled = true; |
302 | mtag_mmap_flags = __MTAG_MMAP_FLAGS; |
303 | } |
304 | #endif |
305 | |
306 | #if defined SHARED && IS_IN (libc) |
307 | /* In case this libc copy is in a non-default namespace, never use |
308 | brk. Likewise if dlopened from statically linked program. The |
309 | generic sbrk implementation also enforces this, but it is not |
310 | used on Hurd. */ |
311 | if (!__libc_initial) |
312 | __always_fail_morecore = true; |
313 | #endif |
314 | |
315 | thread_arena = &main_arena; |
316 | |
317 | malloc_init_state (&main_arena); |
318 | |
319 | #if HAVE_TUNABLES |
320 | TUNABLE_GET (top_pad, size_t, TUNABLE_CALLBACK (set_top_pad)); |
321 | TUNABLE_GET (perturb, int32_t, TUNABLE_CALLBACK (set_perturb_byte)); |
322 | TUNABLE_GET (mmap_threshold, size_t, TUNABLE_CALLBACK (set_mmap_threshold)); |
323 | TUNABLE_GET (trim_threshold, size_t, TUNABLE_CALLBACK (set_trim_threshold)); |
324 | TUNABLE_GET (mmap_max, int32_t, TUNABLE_CALLBACK (set_mmaps_max)); |
325 | TUNABLE_GET (arena_max, size_t, TUNABLE_CALLBACK (set_arena_max)); |
326 | TUNABLE_GET (arena_test, size_t, TUNABLE_CALLBACK (set_arena_test)); |
327 | # if USE_TCACHE |
328 | TUNABLE_GET (tcache_max, size_t, TUNABLE_CALLBACK (set_tcache_max)); |
329 | TUNABLE_GET (tcache_count, size_t, TUNABLE_CALLBACK (set_tcache_count)); |
330 | TUNABLE_GET (tcache_unsorted_limit, size_t, |
331 | TUNABLE_CALLBACK (set_tcache_unsorted_limit)); |
332 | # endif |
333 | TUNABLE_GET (mxfast, size_t, TUNABLE_CALLBACK (set_mxfast)); |
334 | #else |
335 | if (__glibc_likely (_environ != NULL)) |
336 | { |
337 | char **runp = _environ; |
338 | char *envline; |
339 | |
340 | while (__builtin_expect ((envline = next_env_entry (&runp)) != NULL, |
341 | 0)) |
342 | { |
343 | size_t len = strcspn (envline, "=" ); |
344 | |
345 | if (envline[len] != '=') |
346 | /* This is a "MALLOC_" variable at the end of the string |
347 | without a '=' character. Ignore it since otherwise we |
348 | will access invalid memory below. */ |
349 | continue; |
350 | |
351 | switch (len) |
352 | { |
353 | case 8: |
354 | if (!__builtin_expect (__libc_enable_secure, 0)) |
355 | { |
356 | if (memcmp (envline, "TOP_PAD_" , 8) == 0) |
357 | __libc_mallopt (M_TOP_PAD, atoi (&envline[9])); |
358 | else if (memcmp (envline, "PERTURB_" , 8) == 0) |
359 | __libc_mallopt (M_PERTURB, atoi (&envline[9])); |
360 | } |
361 | break; |
362 | case 9: |
363 | if (!__builtin_expect (__libc_enable_secure, 0)) |
364 | { |
365 | if (memcmp (envline, "MMAP_MAX_" , 9) == 0) |
366 | __libc_mallopt (M_MMAP_MAX, atoi (&envline[10])); |
367 | else if (memcmp (envline, "ARENA_MAX" , 9) == 0) |
368 | __libc_mallopt (M_ARENA_MAX, atoi (&envline[10])); |
369 | } |
370 | break; |
371 | case 10: |
372 | if (!__builtin_expect (__libc_enable_secure, 0)) |
373 | { |
374 | if (memcmp (envline, "ARENA_TEST" , 10) == 0) |
375 | __libc_mallopt (M_ARENA_TEST, atoi (&envline[11])); |
376 | } |
377 | break; |
378 | case 15: |
379 | if (!__builtin_expect (__libc_enable_secure, 0)) |
380 | { |
381 | if (memcmp (envline, "TRIM_THRESHOLD_" , 15) == 0) |
382 | __libc_mallopt (M_TRIM_THRESHOLD, atoi (&envline[16])); |
383 | else if (memcmp (envline, "MMAP_THRESHOLD_" , 15) == 0) |
384 | __libc_mallopt (M_MMAP_THRESHOLD, atoi (&envline[16])); |
385 | } |
386 | break; |
387 | default: |
388 | break; |
389 | } |
390 | } |
391 | } |
392 | #endif |
393 | } |
394 | |
395 | /* Managing heaps and arenas (for concurrent threads) */ |
396 | |
397 | #if MALLOC_DEBUG > 1 |
398 | |
399 | /* Print the complete contents of a single heap to stderr. */ |
400 | |
401 | static void |
402 | dump_heap (heap_info *heap) |
403 | { |
404 | char *ptr; |
405 | mchunkptr p; |
406 | |
407 | fprintf (stderr, "Heap %p, size %10lx:\n" , heap, (long) heap->size); |
408 | ptr = (heap->ar_ptr != (mstate) (heap + 1)) ? |
409 | (char *) (heap + 1) : (char *) (heap + 1) + sizeof (struct malloc_state); |
410 | p = (mchunkptr) (((unsigned long) ptr + MALLOC_ALIGN_MASK) & |
411 | ~MALLOC_ALIGN_MASK); |
412 | for (;; ) |
413 | { |
414 | fprintf (stderr, "chunk %p size %10lx" , p, (long) chunksize_nomask(p)); |
415 | if (p == top (heap->ar_ptr)) |
416 | { |
417 | fprintf (stderr, " (top)\n" ); |
418 | break; |
419 | } |
420 | else if (chunksize_nomask(p) == (0 | PREV_INUSE)) |
421 | { |
422 | fprintf (stderr, " (fence)\n" ); |
423 | break; |
424 | } |
425 | fprintf (stderr, "\n" ); |
426 | p = next_chunk (p); |
427 | } |
428 | } |
429 | #endif /* MALLOC_DEBUG > 1 */ |
430 | |
431 | /* If consecutive mmap (0, HEAP_MAX_SIZE << 1, ...) calls return decreasing |
432 | addresses as opposed to increasing, new_heap would badly fragment the |
433 | address space. In that case remember the second HEAP_MAX_SIZE part |
434 | aligned to HEAP_MAX_SIZE from last mmap (0, HEAP_MAX_SIZE << 1, ...) |
435 | call (if it is already aligned) and try to reuse it next time. We need |
436 | no locking for it, as kernel ensures the atomicity for us - worst case |
437 | we'll call mmap (addr, HEAP_MAX_SIZE, ...) for some value of addr in |
438 | multiple threads, but only one will succeed. */ |
439 | static char *aligned_heap_area; |
440 | |
441 | /* Create a new heap. size is automatically rounded up to a multiple |
442 | of the page size. */ |
443 | |
444 | static heap_info * |
445 | new_heap (size_t size, size_t top_pad) |
446 | { |
447 | size_t pagesize = GLRO (dl_pagesize); |
448 | char *p1, *p2; |
449 | unsigned long ul; |
450 | heap_info *h; |
451 | |
452 | if (size + top_pad < HEAP_MIN_SIZE) |
453 | size = HEAP_MIN_SIZE; |
454 | else if (size + top_pad <= HEAP_MAX_SIZE) |
455 | size += top_pad; |
456 | else if (size > HEAP_MAX_SIZE) |
457 | return 0; |
458 | else |
459 | size = HEAP_MAX_SIZE; |
460 | size = ALIGN_UP (size, pagesize); |
461 | |
462 | /* A memory region aligned to a multiple of HEAP_MAX_SIZE is needed. |
463 | No swap space needs to be reserved for the following large |
464 | mapping (on Linux, this is the case for all non-writable mappings |
465 | anyway). */ |
466 | p2 = MAP_FAILED; |
467 | if (aligned_heap_area) |
468 | { |
469 | p2 = (char *) MMAP (aligned_heap_area, HEAP_MAX_SIZE, PROT_NONE, |
470 | MAP_NORESERVE); |
471 | aligned_heap_area = NULL; |
472 | if (p2 != MAP_FAILED && ((unsigned long) p2 & (HEAP_MAX_SIZE - 1))) |
473 | { |
474 | __munmap (p2, HEAP_MAX_SIZE); |
475 | p2 = MAP_FAILED; |
476 | } |
477 | } |
478 | if (p2 == MAP_FAILED) |
479 | { |
480 | p1 = (char *) MMAP (0, HEAP_MAX_SIZE << 1, PROT_NONE, MAP_NORESERVE); |
481 | if (p1 != MAP_FAILED) |
482 | { |
483 | p2 = (char *) (((unsigned long) p1 + (HEAP_MAX_SIZE - 1)) |
484 | & ~(HEAP_MAX_SIZE - 1)); |
485 | ul = p2 - p1; |
486 | if (ul) |
487 | __munmap (p1, ul); |
488 | else |
489 | aligned_heap_area = p2 + HEAP_MAX_SIZE; |
490 | __munmap (p2 + HEAP_MAX_SIZE, HEAP_MAX_SIZE - ul); |
491 | } |
492 | else |
493 | { |
494 | /* Try to take the chance that an allocation of only HEAP_MAX_SIZE |
495 | is already aligned. */ |
496 | p2 = (char *) MMAP (0, HEAP_MAX_SIZE, PROT_NONE, MAP_NORESERVE); |
497 | if (p2 == MAP_FAILED) |
498 | return 0; |
499 | |
500 | if ((unsigned long) p2 & (HEAP_MAX_SIZE - 1)) |
501 | { |
502 | __munmap (p2, HEAP_MAX_SIZE); |
503 | return 0; |
504 | } |
505 | } |
506 | } |
507 | if (__mprotect (p2, size, mtag_mmap_flags | PROT_READ | PROT_WRITE) != 0) |
508 | { |
509 | __munmap (p2, HEAP_MAX_SIZE); |
510 | return 0; |
511 | } |
512 | h = (heap_info *) p2; |
513 | h->size = size; |
514 | h->mprotect_size = size; |
515 | LIBC_PROBE (memory_heap_new, 2, h, h->size); |
516 | return h; |
517 | } |
518 | |
519 | /* Grow a heap. size is automatically rounded up to a |
520 | multiple of the page size. */ |
521 | |
522 | static int |
523 | grow_heap (heap_info *h, long diff) |
524 | { |
525 | size_t pagesize = GLRO (dl_pagesize); |
526 | long new_size; |
527 | |
528 | diff = ALIGN_UP (diff, pagesize); |
529 | new_size = (long) h->size + diff; |
530 | if ((unsigned long) new_size > (unsigned long) HEAP_MAX_SIZE) |
531 | return -1; |
532 | |
533 | if ((unsigned long) new_size > h->mprotect_size) |
534 | { |
535 | if (__mprotect ((char *) h + h->mprotect_size, |
536 | (unsigned long) new_size - h->mprotect_size, |
537 | mtag_mmap_flags | PROT_READ | PROT_WRITE) != 0) |
538 | return -2; |
539 | |
540 | h->mprotect_size = new_size; |
541 | } |
542 | |
543 | h->size = new_size; |
544 | LIBC_PROBE (memory_heap_more, 2, h, h->size); |
545 | return 0; |
546 | } |
547 | |
548 | /* Shrink a heap. */ |
549 | |
550 | static int |
551 | shrink_heap (heap_info *h, long diff) |
552 | { |
553 | long new_size; |
554 | |
555 | new_size = (long) h->size - diff; |
556 | if (new_size < (long) sizeof (*h)) |
557 | return -1; |
558 | |
559 | /* Try to re-map the extra heap space freshly to save memory, and make it |
560 | inaccessible. See malloc-sysdep.h to know when this is true. */ |
561 | if (__glibc_unlikely (check_may_shrink_heap ())) |
562 | { |
563 | if ((char *) MMAP ((char *) h + new_size, diff, PROT_NONE, |
564 | MAP_FIXED) == (char *) MAP_FAILED) |
565 | return -2; |
566 | |
567 | h->mprotect_size = new_size; |
568 | } |
569 | else |
570 | __madvise ((char *) h + new_size, diff, MADV_DONTNEED); |
571 | /*fprintf(stderr, "shrink %p %08lx\n", h, new_size);*/ |
572 | |
573 | h->size = new_size; |
574 | LIBC_PROBE (memory_heap_less, 2, h, h->size); |
575 | return 0; |
576 | } |
577 | |
578 | /* Delete a heap. */ |
579 | |
580 | #define delete_heap(heap) \ |
581 | do { \ |
582 | if ((char *) (heap) + HEAP_MAX_SIZE == aligned_heap_area) \ |
583 | aligned_heap_area = NULL; \ |
584 | __munmap ((char *) (heap), HEAP_MAX_SIZE); \ |
585 | } while (0) |
586 | |
587 | static int |
588 | heap_trim (heap_info *heap, size_t pad) |
589 | { |
590 | mstate ar_ptr = heap->ar_ptr; |
591 | unsigned long pagesz = GLRO (dl_pagesize); |
592 | mchunkptr top_chunk = top (ar_ptr), p; |
593 | heap_info *prev_heap; |
594 | long new_size, top_size, top_area, , prev_size, misalign; |
595 | |
596 | /* Can this heap go away completely? */ |
597 | while (top_chunk == chunk_at_offset (heap, sizeof (*heap))) |
598 | { |
599 | prev_heap = heap->prev; |
600 | prev_size = prev_heap->size - (MINSIZE - 2 * SIZE_SZ); |
601 | p = chunk_at_offset (prev_heap, prev_size); |
602 | /* fencepost must be properly aligned. */ |
603 | misalign = ((long) p) & MALLOC_ALIGN_MASK; |
604 | p = chunk_at_offset (prev_heap, prev_size - misalign); |
605 | assert (chunksize_nomask (p) == (0 | PREV_INUSE)); /* must be fencepost */ |
606 | p = prev_chunk (p); |
607 | new_size = chunksize (p) + (MINSIZE - 2 * SIZE_SZ) + misalign; |
608 | assert (new_size > 0 && new_size < (long) (2 * MINSIZE)); |
609 | if (!prev_inuse (p)) |
610 | new_size += prev_size (p); |
611 | assert (new_size > 0 && new_size < HEAP_MAX_SIZE); |
612 | if (new_size + (HEAP_MAX_SIZE - prev_heap->size) < pad + MINSIZE + pagesz) |
613 | break; |
614 | ar_ptr->system_mem -= heap->size; |
615 | LIBC_PROBE (memory_heap_free, 2, heap, heap->size); |
616 | delete_heap (heap); |
617 | heap = prev_heap; |
618 | if (!prev_inuse (p)) /* consolidate backward */ |
619 | { |
620 | p = prev_chunk (p); |
621 | unlink_chunk (ar_ptr, p); |
622 | } |
623 | assert (((unsigned long) ((char *) p + new_size) & (pagesz - 1)) == 0); |
624 | assert (((char *) p + new_size) == ((char *) heap + heap->size)); |
625 | top (ar_ptr) = top_chunk = p; |
626 | set_head (top_chunk, new_size | PREV_INUSE); |
627 | /*check_chunk(ar_ptr, top_chunk);*/ |
628 | } |
629 | |
630 | /* Uses similar logic for per-thread arenas as the main arena with systrim |
631 | and _int_free by preserving the top pad and rounding down to the nearest |
632 | page. */ |
633 | top_size = chunksize (top_chunk); |
634 | if ((unsigned long)(top_size) < |
635 | (unsigned long)(mp_.trim_threshold)) |
636 | return 0; |
637 | |
638 | top_area = top_size - MINSIZE - 1; |
639 | if (top_area < 0 || (size_t) top_area <= pad) |
640 | return 0; |
641 | |
642 | /* Release in pagesize units and round down to the nearest page. */ |
643 | extra = ALIGN_DOWN(top_area - pad, pagesz); |
644 | if (extra == 0) |
645 | return 0; |
646 | |
647 | /* Try to shrink. */ |
648 | if (shrink_heap (heap, extra) != 0) |
649 | return 0; |
650 | |
651 | ar_ptr->system_mem -= extra; |
652 | |
653 | /* Success. Adjust top accordingly. */ |
654 | set_head (top_chunk, (top_size - extra) | PREV_INUSE); |
655 | /*check_chunk(ar_ptr, top_chunk);*/ |
656 | return 1; |
657 | } |
658 | |
659 | /* Create a new arena with initial size "size". */ |
660 | |
661 | #if IS_IN (libc) |
662 | /* If REPLACED_ARENA is not NULL, detach it from this thread. Must be |
663 | called while free_list_lock is held. */ |
664 | static void |
665 | detach_arena (mstate replaced_arena) |
666 | { |
667 | if (replaced_arena != NULL) |
668 | { |
669 | assert (replaced_arena->attached_threads > 0); |
670 | /* The current implementation only detaches from main_arena in |
671 | case of allocation failure. This means that it is likely not |
672 | beneficial to put the arena on free_list even if the |
673 | reference count reaches zero. */ |
674 | --replaced_arena->attached_threads; |
675 | } |
676 | } |
677 | |
678 | static mstate |
679 | _int_new_arena (size_t size) |
680 | { |
681 | mstate a; |
682 | heap_info *h; |
683 | char *ptr; |
684 | unsigned long misalign; |
685 | |
686 | h = new_heap (size + (sizeof (*h) + sizeof (*a) + MALLOC_ALIGNMENT), |
687 | mp_.top_pad); |
688 | if (!h) |
689 | { |
690 | /* Maybe size is too large to fit in a single heap. So, just try |
691 | to create a minimally-sized arena and let _int_malloc() attempt |
692 | to deal with the large request via mmap_chunk(). */ |
693 | h = new_heap (sizeof (*h) + sizeof (*a) + MALLOC_ALIGNMENT, mp_.top_pad); |
694 | if (!h) |
695 | return 0; |
696 | } |
697 | a = h->ar_ptr = (mstate) (h + 1); |
698 | malloc_init_state (a); |
699 | a->attached_threads = 1; |
700 | /*a->next = NULL;*/ |
701 | a->system_mem = a->max_system_mem = h->size; |
702 | |
703 | /* Set up the top chunk, with proper alignment. */ |
704 | ptr = (char *) (a + 1); |
705 | misalign = (unsigned long) chunk2mem (ptr) & MALLOC_ALIGN_MASK; |
706 | if (misalign > 0) |
707 | ptr += MALLOC_ALIGNMENT - misalign; |
708 | top (a) = (mchunkptr) ptr; |
709 | set_head (top (a), (((char *) h + h->size) - ptr) | PREV_INUSE); |
710 | |
711 | LIBC_PROBE (memory_arena_new, 2, a, size); |
712 | mstate replaced_arena = thread_arena; |
713 | thread_arena = a; |
714 | __libc_lock_init (a->mutex); |
715 | |
716 | __libc_lock_lock (list_lock); |
717 | |
718 | /* Add the new arena to the global list. */ |
719 | a->next = main_arena.next; |
720 | /* FIXME: The barrier is an attempt to synchronize with read access |
721 | in reused_arena, which does not acquire list_lock while |
722 | traversing the list. */ |
723 | atomic_write_barrier (); |
724 | main_arena.next = a; |
725 | |
726 | __libc_lock_unlock (list_lock); |
727 | |
728 | __libc_lock_lock (free_list_lock); |
729 | detach_arena (replaced_arena); |
730 | __libc_lock_unlock (free_list_lock); |
731 | |
732 | /* Lock this arena. NB: Another thread may have been attached to |
733 | this arena because the arena is now accessible from the |
734 | main_arena.next list and could have been picked by reused_arena. |
735 | This can only happen for the last arena created (before the arena |
736 | limit is reached). At this point, some arena has to be attached |
737 | to two threads. We could acquire the arena lock before list_lock |
738 | to make it less likely that reused_arena picks this new arena, |
739 | but this could result in a deadlock with |
740 | __malloc_fork_lock_parent. */ |
741 | |
742 | __libc_lock_lock (a->mutex); |
743 | |
744 | return a; |
745 | } |
746 | |
747 | |
748 | /* Remove an arena from free_list. */ |
749 | static mstate |
750 | get_free_list (void) |
751 | { |
752 | mstate replaced_arena = thread_arena; |
753 | mstate result = free_list; |
754 | if (result != NULL) |
755 | { |
756 | __libc_lock_lock (free_list_lock); |
757 | result = free_list; |
758 | if (result != NULL) |
759 | { |
760 | free_list = result->next_free; |
761 | |
762 | /* The arena will be attached to this thread. */ |
763 | assert (result->attached_threads == 0); |
764 | result->attached_threads = 1; |
765 | |
766 | detach_arena (replaced_arena); |
767 | } |
768 | __libc_lock_unlock (free_list_lock); |
769 | |
770 | if (result != NULL) |
771 | { |
772 | LIBC_PROBE (memory_arena_reuse_free_list, 1, result); |
773 | __libc_lock_lock (result->mutex); |
774 | thread_arena = result; |
775 | } |
776 | } |
777 | |
778 | return result; |
779 | } |
780 | |
781 | /* Remove the arena from the free list (if it is present). |
782 | free_list_lock must have been acquired by the caller. */ |
783 | static void |
784 | remove_from_free_list (mstate arena) |
785 | { |
786 | mstate *previous = &free_list; |
787 | for (mstate p = free_list; p != NULL; p = p->next_free) |
788 | { |
789 | assert (p->attached_threads == 0); |
790 | if (p == arena) |
791 | { |
792 | /* Remove the requested arena from the list. */ |
793 | *previous = p->next_free; |
794 | break; |
795 | } |
796 | else |
797 | previous = &p->next_free; |
798 | } |
799 | } |
800 | |
801 | /* Lock and return an arena that can be reused for memory allocation. |
802 | Avoid AVOID_ARENA as we have already failed to allocate memory in |
803 | it and it is currently locked. */ |
804 | static mstate |
805 | reused_arena (mstate avoid_arena) |
806 | { |
807 | mstate result; |
808 | /* FIXME: Access to next_to_use suffers from data races. */ |
809 | static mstate next_to_use; |
810 | if (next_to_use == NULL) |
811 | next_to_use = &main_arena; |
812 | |
813 | /* Iterate over all arenas (including those linked from |
814 | free_list). */ |
815 | result = next_to_use; |
816 | do |
817 | { |
818 | if (!__libc_lock_trylock (result->mutex)) |
819 | goto out; |
820 | |
821 | /* FIXME: This is a data race, see _int_new_arena. */ |
822 | result = result->next; |
823 | } |
824 | while (result != next_to_use); |
825 | |
826 | /* Avoid AVOID_ARENA as we have already failed to allocate memory |
827 | in that arena and it is currently locked. */ |
828 | if (result == avoid_arena) |
829 | result = result->next; |
830 | |
831 | /* No arena available without contention. Wait for the next in line. */ |
832 | LIBC_PROBE (memory_arena_reuse_wait, 3, &result->mutex, result, avoid_arena); |
833 | __libc_lock_lock (result->mutex); |
834 | |
835 | out: |
836 | /* Attach the arena to the current thread. */ |
837 | { |
838 | /* Update the arena thread attachment counters. */ |
839 | mstate replaced_arena = thread_arena; |
840 | __libc_lock_lock (free_list_lock); |
841 | detach_arena (replaced_arena); |
842 | |
843 | /* We may have picked up an arena on the free list. We need to |
844 | preserve the invariant that no arena on the free list has a |
845 | positive attached_threads counter (otherwise, |
846 | arena_thread_freeres cannot use the counter to determine if the |
847 | arena needs to be put on the free list). We unconditionally |
848 | remove the selected arena from the free list. The caller of |
849 | reused_arena checked the free list and observed it to be empty, |
850 | so the list is very short. */ |
851 | remove_from_free_list (result); |
852 | |
853 | ++result->attached_threads; |
854 | |
855 | __libc_lock_unlock (free_list_lock); |
856 | } |
857 | |
858 | LIBC_PROBE (memory_arena_reuse, 2, result, avoid_arena); |
859 | thread_arena = result; |
860 | next_to_use = result->next; |
861 | |
862 | return result; |
863 | } |
864 | |
865 | static mstate |
866 | arena_get2 (size_t size, mstate avoid_arena) |
867 | { |
868 | mstate a; |
869 | |
870 | static size_t narenas_limit; |
871 | |
872 | a = get_free_list (); |
873 | if (a == NULL) |
874 | { |
875 | /* Nothing immediately available, so generate a new arena. */ |
876 | if (narenas_limit == 0) |
877 | { |
878 | if (mp_.arena_max != 0) |
879 | narenas_limit = mp_.arena_max; |
880 | else if (narenas > mp_.arena_test) |
881 | { |
882 | int n = __get_nprocs (); |
883 | |
884 | if (n >= 1) |
885 | narenas_limit = NARENAS_FROM_NCORES (n); |
886 | else |
887 | /* We have no information about the system. Assume two |
888 | cores. */ |
889 | narenas_limit = NARENAS_FROM_NCORES (2); |
890 | } |
891 | } |
892 | repeat:; |
893 | size_t n = narenas; |
894 | /* NB: the following depends on the fact that (size_t)0 - 1 is a |
895 | very large number and that the underflow is OK. If arena_max |
896 | is set the value of arena_test is irrelevant. If arena_test |
897 | is set but narenas is not yet larger or equal to arena_test |
898 | narenas_limit is 0. There is no possibility for narenas to |
899 | be too big for the test to always fail since there is not |
900 | enough address space to create that many arenas. */ |
901 | if (__glibc_unlikely (n <= narenas_limit - 1)) |
902 | { |
903 | if (catomic_compare_and_exchange_bool_acq (&narenas, n + 1, n)) |
904 | goto repeat; |
905 | a = _int_new_arena (size); |
906 | if (__glibc_unlikely (a == NULL)) |
907 | catomic_decrement (&narenas); |
908 | } |
909 | else |
910 | a = reused_arena (avoid_arena); |
911 | } |
912 | return a; |
913 | } |
914 | |
915 | /* If we don't have the main arena, then maybe the failure is due to running |
916 | out of mmapped areas, so we can try allocating on the main arena. |
917 | Otherwise, it is likely that sbrk() has failed and there is still a chance |
918 | to mmap(), so try one of the other arenas. */ |
919 | static mstate |
920 | arena_get_retry (mstate ar_ptr, size_t bytes) |
921 | { |
922 | LIBC_PROBE (memory_arena_retry, 2, bytes, ar_ptr); |
923 | if (ar_ptr != &main_arena) |
924 | { |
925 | __libc_lock_unlock (ar_ptr->mutex); |
926 | ar_ptr = &main_arena; |
927 | __libc_lock_lock (ar_ptr->mutex); |
928 | } |
929 | else |
930 | { |
931 | __libc_lock_unlock (ar_ptr->mutex); |
932 | ar_ptr = arena_get2 (bytes, ar_ptr); |
933 | } |
934 | |
935 | return ar_ptr; |
936 | } |
937 | #endif |
938 | |
939 | void |
940 | __malloc_arena_thread_freeres (void) |
941 | { |
942 | /* Shut down the thread cache first. This could deallocate data for |
943 | the thread arena, so do this before we put the arena on the free |
944 | list. */ |
945 | tcache_thread_shutdown (); |
946 | |
947 | mstate a = thread_arena; |
948 | thread_arena = NULL; |
949 | |
950 | if (a != NULL) |
951 | { |
952 | __libc_lock_lock (free_list_lock); |
953 | /* If this was the last attached thread for this arena, put the |
954 | arena on the free list. */ |
955 | assert (a->attached_threads > 0); |
956 | if (--a->attached_threads == 0) |
957 | { |
958 | a->next_free = free_list; |
959 | free_list = a; |
960 | } |
961 | __libc_lock_unlock (free_list_lock); |
962 | } |
963 | } |
964 | |
965 | /* |
966 | * Local variables: |
967 | * c-basic-offset: 2 |
968 | * End: |
969 | */ |
970 | |