arena.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. /* Malloc implementation for multiple threads without lock contention.
  2. Copyright (C) 2001-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public License as
  6. published by the Free Software Foundation; either version 2.1 of the
  7. License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; see the file COPYING.LIB. If
  14. not, see <https://www.gnu.org/licenses/>. */
  15. #include <stdbool.h>
  16. #include <setvmaname.h>
  17. #define TUNABLE_NAMESPACE malloc
  18. #include <elf/dl-tunables.h>
  19. /* Compile-time constants. */
  20. #define HEAP_MIN_SIZE (32 * 1024)
  21. #ifndef HEAP_MAX_SIZE
  22. # ifdef DEFAULT_MMAP_THRESHOLD_MAX
  23. # define HEAP_MAX_SIZE (2 * DEFAULT_MMAP_THRESHOLD_MAX)
  24. # else
  25. # define HEAP_MAX_SIZE (1024 * 1024) /* must be a power of two */
  26. # endif
  27. #endif
  28. /* HEAP_MIN_SIZE and HEAP_MAX_SIZE limit the size of mmap()ed heaps
  29. that are dynamically created for multi-threaded programs. The
  30. maximum size must be a power of two, for fast determination of
  31. which heap belongs to a chunk. It should be much larger than the
  32. mmap threshold, so that requests with a size just below that
  33. threshold can be fulfilled without creating too many heaps. */
  34. /* HEAP_MAX_SIZE should be larger than the huge page size, otherwise heaps will
  35. use not huge pages. It is a constant so arena_for_chunk() is efficient. */
  36. static __always_inline size_t
  37. heap_min_size (void)
  38. {
  39. return mp_.hp_pagesize == 0 || mp_.hp_pagesize > HEAP_MAX_SIZE
  40. ? HEAP_MIN_SIZE : mp_.hp_pagesize;
  41. }
  42. static __always_inline size_t
  43. heap_max_size (void)
  44. {
  45. return HEAP_MAX_SIZE;
  46. }
  47. /***************************************************************************/
  48. #define top(ar_ptr) ((ar_ptr)->top)
  49. /* A heap is a single contiguous memory region holding (coalesceable)
  50. malloc_chunks. It is allocated with mmap() and always starts at an
  51. address aligned to HEAP_MAX_SIZE. */
  52. typedef struct _heap_info
  53. {
  54. mstate ar_ptr; /* Arena for this heap. */
  55. struct _heap_info *prev; /* Previous heap. */
  56. size_t size; /* Current size in bytes. */
  57. size_t mprotect_size; /* Size in bytes that has been mprotected
  58. PROT_READ|PROT_WRITE. */
  59. size_t pagesize; /* Page size used when allocating the arena. */
  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[-3 * SIZE_SZ & MALLOC_ALIGN_MASK];
  64. } heap_info;
  65. /* Get a compile-time error if the heap_info padding is not correct
  66. to make alignment work as expected in sYSMALLOc. */
  67. extern int sanity_check_heap_info_alignment[(sizeof (heap_info)
  68. + 2 * SIZE_SZ) % MALLOC_ALIGNMENT
  69. ? -1 : 1];
  70. /* Thread specific data. */
  71. static __thread mstate thread_arena attribute_tls_model_ie;
  72. /* Arena free list. free_list_lock synchronizes access to the
  73. free_list variable below, and the next_free and attached_threads
  74. members of struct malloc_state objects. No other locks must be
  75. acquired after free_list_lock has been acquired. */
  76. __libc_lock_define_initialized (static, free_list_lock);
  77. #if IS_IN (libc)
  78. static size_t narenas = 1;
  79. #endif
  80. static mstate free_list;
  81. /* list_lock prevents concurrent writes to the next member of struct
  82. malloc_state objects.
  83. Read access to the next member is supposed to synchronize with the
  84. atomic_write_barrier and the write to the next member in
  85. _int_new_arena. This suffers from data races; see the FIXME
  86. comments in _int_new_arena and reused_arena.
  87. list_lock also prevents concurrent forks. At the time list_lock is
  88. acquired, no arena lock must have been acquired, but it is
  89. permitted to acquire arena locks subsequently, while list_lock is
  90. acquired. */
  91. __libc_lock_define_initialized (static, list_lock);
  92. /**************************************************************************/
  93. /* arena_get() acquires an arena and locks the corresponding mutex.
  94. First, try the one last locked successfully by this thread. (This
  95. is the common case and handled with a macro for speed.) Then, loop
  96. once over the circularly linked list of arenas. If no arena is
  97. readily available, create a new one. In this latter case, `size'
  98. is just a hint as to how much memory will be required immediately
  99. in the new arena. */
  100. #define arena_get(ptr, size) do { \
  101. ptr = thread_arena; \
  102. arena_lock (ptr, size); \
  103. } while (0)
  104. #define arena_lock(ptr, size) do { \
  105. if (ptr) \
  106. __libc_lock_lock (ptr->mutex); \
  107. else \
  108. ptr = arena_get2 ((size), NULL); \
  109. } while (0)
  110. /* find the heap and corresponding arena for a given ptr */
  111. static __always_inline heap_info *
  112. heap_for_ptr (void *ptr)
  113. {
  114. size_t max_size = heap_max_size ();
  115. return PTR_ALIGN_DOWN (ptr, max_size);
  116. }
  117. static __always_inline struct malloc_state *
  118. arena_for_chunk (mchunkptr ptr)
  119. {
  120. return chunk_main_arena (ptr) ? &main_arena : heap_for_ptr (ptr)->ar_ptr;
  121. }
  122. /**************************************************************************/
  123. /* atfork support. */
  124. /* The following three functions are called around fork from a
  125. multi-threaded process. We do not use the general fork handler
  126. mechanism to make sure that our handlers are the last ones being
  127. called, so that other fork handlers can use the malloc
  128. subsystem. */
  129. void
  130. __malloc_fork_lock_parent (void)
  131. {
  132. /* We do not acquire free_list_lock here because we completely
  133. reconstruct free_list in __malloc_fork_unlock_child. */
  134. __libc_lock_lock (list_lock);
  135. for (mstate ar_ptr = &main_arena;; )
  136. {
  137. __libc_lock_lock (ar_ptr->mutex);
  138. ar_ptr = ar_ptr->next;
  139. if (ar_ptr == &main_arena)
  140. break;
  141. }
  142. }
  143. void
  144. __malloc_fork_unlock_parent (void)
  145. {
  146. for (mstate ar_ptr = &main_arena;; )
  147. {
  148. __libc_lock_unlock (ar_ptr->mutex);
  149. ar_ptr = ar_ptr->next;
  150. if (ar_ptr == &main_arena)
  151. break;
  152. }
  153. __libc_lock_unlock (list_lock);
  154. }
  155. void
  156. __malloc_fork_unlock_child (void)
  157. {
  158. /* Push all arenas to the free list, except thread_arena, which is
  159. attached to the current thread. */
  160. __libc_lock_init (free_list_lock);
  161. if (thread_arena != NULL)
  162. thread_arena->attached_threads = 1;
  163. free_list = NULL;
  164. for (mstate ar_ptr = &main_arena;; )
  165. {
  166. __libc_lock_init (ar_ptr->mutex);
  167. if (ar_ptr != thread_arena)
  168. {
  169. /* This arena is no longer attached to any thread. */
  170. ar_ptr->attached_threads = 0;
  171. ar_ptr->next_free = free_list;
  172. free_list = ar_ptr;
  173. }
  174. ar_ptr = ar_ptr->next;
  175. if (ar_ptr == &main_arena)
  176. break;
  177. }
  178. __libc_lock_init (list_lock);
  179. }
  180. #define TUNABLE_CALLBACK_FNDECL(__name, __type) \
  181. static __always_inline int do_ ## __name (__type value); \
  182. static void \
  183. TUNABLE_CALLBACK (__name) (tunable_val_t *valp) \
  184. { \
  185. __type value = (__type) (valp)->numval; \
  186. do_ ## __name (value); \
  187. }
  188. TUNABLE_CALLBACK_FNDECL (set_mmap_threshold, size_t)
  189. TUNABLE_CALLBACK_FNDECL (set_mmaps_max, int32_t)
  190. TUNABLE_CALLBACK_FNDECL (set_top_pad, size_t)
  191. TUNABLE_CALLBACK_FNDECL (set_perturb_byte, int32_t)
  192. TUNABLE_CALLBACK_FNDECL (set_trim_threshold, size_t)
  193. TUNABLE_CALLBACK_FNDECL (set_arena_max, size_t)
  194. TUNABLE_CALLBACK_FNDECL (set_arena_test, size_t)
  195. #if USE_TCACHE
  196. TUNABLE_CALLBACK_FNDECL (set_tcache_max, size_t)
  197. TUNABLE_CALLBACK_FNDECL (set_tcache_count, size_t)
  198. TUNABLE_CALLBACK_FNDECL (set_tcache_unsorted_limit, size_t)
  199. #endif
  200. TUNABLE_CALLBACK_FNDECL (set_hugetlb, size_t)
  201. #if USE_TCACHE
  202. static void tcache_key_initialize (void);
  203. #endif
  204. void
  205. __ptmalloc_init (void)
  206. {
  207. #if USE_TCACHE
  208. tcache_key_initialize ();
  209. #endif
  210. #ifdef USE_MTAG
  211. if ((TUNABLE_GET_FULL (glibc, mem, tagging, int32_t, NULL) & 1) != 0)
  212. {
  213. /* If the tunable says that we should be using tagged memory
  214. and that morecore does not support tagged regions, then
  215. disable it. */
  216. if (__MTAG_SBRK_UNTAGGED)
  217. __always_fail_morecore = true;
  218. mtag_enabled = true;
  219. mtag_mmap_flags = __MTAG_MMAP_FLAGS;
  220. }
  221. #endif
  222. #if defined SHARED && IS_IN (libc)
  223. /* In case this libc copy is in a non-default namespace, never use
  224. brk. Likewise if dlopened from statically linked program. The
  225. generic sbrk implementation also enforces this, but it is not
  226. used on Hurd. */
  227. if (!__libc_initial)
  228. __always_fail_morecore = true;
  229. #endif
  230. thread_arena = &main_arena;
  231. malloc_init_state (&main_arena);
  232. TUNABLE_GET (top_pad, size_t, TUNABLE_CALLBACK (set_top_pad));
  233. TUNABLE_GET (perturb, int32_t, TUNABLE_CALLBACK (set_perturb_byte));
  234. TUNABLE_GET (mmap_threshold, size_t, TUNABLE_CALLBACK (set_mmap_threshold));
  235. TUNABLE_GET (trim_threshold, size_t, TUNABLE_CALLBACK (set_trim_threshold));
  236. TUNABLE_GET (mmap_max, int32_t, TUNABLE_CALLBACK (set_mmaps_max));
  237. TUNABLE_GET (arena_max, size_t, TUNABLE_CALLBACK (set_arena_max));
  238. TUNABLE_GET (arena_test, size_t, TUNABLE_CALLBACK (set_arena_test));
  239. # if USE_TCACHE
  240. TUNABLE_GET (tcache_max, size_t, TUNABLE_CALLBACK (set_tcache_max));
  241. TUNABLE_GET (tcache_count, size_t, TUNABLE_CALLBACK (set_tcache_count));
  242. TUNABLE_GET (tcache_unsorted_limit, size_t,
  243. TUNABLE_CALLBACK (set_tcache_unsorted_limit));
  244. # endif
  245. TUNABLE_GET (hugetlb, size_t, TUNABLE_CALLBACK (set_hugetlb));
  246. if (mp_.hp_pagesize > 0 && mp_.hp_pagesize <= heap_max_size ())
  247. {
  248. /* Force mmap for main arena instead of sbrk, so MAP_HUGETLB is always
  249. tried. Also tune the mmap threshold, so allocation smaller than the
  250. large page will also try to use large pages by falling back
  251. to sysmalloc_mmap_fallback on sysmalloc. */
  252. if (!TUNABLE_IS_INITIALIZED (mmap_threshold))
  253. do_set_mmap_threshold (mp_.hp_pagesize);
  254. __always_fail_morecore = true;
  255. }
  256. }
  257. /* Managing heaps and arenas (for concurrent threads) */
  258. #if MALLOC_DEBUG > 1
  259. /* Print the complete contents of a single heap to stderr. */
  260. static void
  261. dump_heap (heap_info *heap)
  262. {
  263. char *ptr;
  264. mchunkptr p;
  265. fprintf (stderr, "Heap %p, size %10lx:\n", heap, (long) heap->size);
  266. ptr = (heap->ar_ptr != (mstate) (heap + 1)) ?
  267. (char *) (heap + 1) : (char *) (heap + 1) + sizeof (struct malloc_state);
  268. p = (mchunkptr) (((uintptr_t) ptr + MALLOC_ALIGN_MASK) &
  269. ~MALLOC_ALIGN_MASK);
  270. for (;; )
  271. {
  272. fprintf (stderr, "chunk %p size %10lx", p, (long) chunksize_nomask(p));
  273. if (p == top (heap->ar_ptr))
  274. {
  275. fprintf (stderr, " (top)\n");
  276. break;
  277. }
  278. else if (chunksize_nomask(p) == (0 | PREV_INUSE))
  279. {
  280. fprintf (stderr, " (fence)\n");
  281. break;
  282. }
  283. fprintf (stderr, "\n");
  284. p = next_chunk (p);
  285. }
  286. }
  287. #endif /* MALLOC_DEBUG > 1 */
  288. /* If consecutive mmap (0, HEAP_MAX_SIZE << 1, ...) calls return decreasing
  289. addresses as opposed to increasing, new_heap would badly fragment the
  290. address space. In that case remember the second HEAP_MAX_SIZE part
  291. aligned to HEAP_MAX_SIZE from last mmap (0, HEAP_MAX_SIZE << 1, ...)
  292. call (if it is already aligned) and try to reuse it next time. We need
  293. no locking for it, as kernel ensures the atomicity for us - worst case
  294. we'll call mmap (addr, HEAP_MAX_SIZE, ...) for some value of addr in
  295. multiple threads, but only one will succeed. */
  296. static char *aligned_heap_area;
  297. /* Create a new heap. size is automatically rounded up to a multiple
  298. of the page size. */
  299. static heap_info *
  300. alloc_new_heap (size_t size, size_t top_pad, size_t pagesize,
  301. int mmap_flags)
  302. {
  303. char *p1, *p2;
  304. unsigned long ul;
  305. heap_info *h;
  306. size_t min_size = heap_min_size ();
  307. size_t max_size = heap_max_size ();
  308. if (size + top_pad < min_size)
  309. size = min_size;
  310. else if (size + top_pad <= max_size)
  311. size += top_pad;
  312. else if (size > max_size)
  313. return NULL;
  314. else
  315. size = max_size;
  316. size = ALIGN_UP (size, pagesize);
  317. /* A memory region aligned to a multiple of max_size is needed.
  318. No swap space needs to be reserved for the following large
  319. mapping (on Linux, this is the case for all non-writable mappings
  320. anyway). */
  321. p2 = MAP_FAILED;
  322. if (aligned_heap_area)
  323. {
  324. p2 = (char *) MMAP (aligned_heap_area, max_size, PROT_NONE, mmap_flags);
  325. aligned_heap_area = NULL;
  326. if (p2 != MAP_FAILED && ((unsigned long) p2 & (max_size - 1)))
  327. {
  328. __munmap (p2, max_size);
  329. p2 = MAP_FAILED;
  330. }
  331. }
  332. if (p2 == MAP_FAILED)
  333. {
  334. p1 = (char *) MMAP (NULL, max_size << 1, PROT_NONE, mmap_flags);
  335. if (p1 != MAP_FAILED)
  336. {
  337. p2 = (char *) (((uintptr_t) p1 + (max_size - 1))
  338. & ~(max_size - 1));
  339. ul = p2 - p1;
  340. if (ul)
  341. __munmap (p1, ul);
  342. else
  343. aligned_heap_area = p2 + max_size;
  344. __munmap (p2 + max_size, max_size - ul);
  345. }
  346. else
  347. {
  348. /* Try to take the chance that an allocation of only max_size
  349. is already aligned. */
  350. p2 = (char *) MMAP (NULL, max_size, PROT_NONE, mmap_flags);
  351. if (p2 == MAP_FAILED)
  352. return NULL;
  353. if ((unsigned long) p2 & (max_size - 1))
  354. {
  355. __munmap (p2, max_size);
  356. return NULL;
  357. }
  358. }
  359. }
  360. if (__mprotect (p2, size, mtag_mmap_flags | PROT_READ | PROT_WRITE) != 0)
  361. {
  362. __munmap (p2, max_size);
  363. return NULL;
  364. }
  365. /* Only considere the actual usable range. */
  366. __set_vma_name (p2, size, " glibc: malloc arena");
  367. madvise_thp (p2, size);
  368. h = (heap_info *) p2;
  369. h->size = size;
  370. h->mprotect_size = size;
  371. h->pagesize = pagesize;
  372. LIBC_PROBE (memory_heap_new, 2, h, h->size);
  373. return h;
  374. }
  375. static heap_info *
  376. new_heap (size_t size, size_t top_pad)
  377. {
  378. bool use_hugepage = mp_.hp_pagesize != 0;
  379. size_t pagesize = use_hugepage ? mp_.hp_pagesize : mp_.thp_pagesize;
  380. if (pagesize != 0 && pagesize <= heap_max_size ())
  381. {
  382. heap_info *h = alloc_new_heap (size, top_pad, pagesize,
  383. use_hugepage ? mp_.hp_flags : 0);
  384. if (h != NULL)
  385. return h;
  386. }
  387. return alloc_new_heap (size, top_pad, GLRO (dl_pagesize), 0);
  388. }
  389. /* Grow a heap. size is automatically rounded up to a
  390. multiple of the page size. */
  391. static int
  392. grow_heap (heap_info *h, long diff)
  393. {
  394. size_t pagesize = h->pagesize;
  395. size_t max_size = heap_max_size ();
  396. long new_size;
  397. diff = ALIGN_UP (diff, pagesize);
  398. new_size = (long) h->size + diff;
  399. if ((unsigned long) new_size > (unsigned long) max_size)
  400. return -1;
  401. if ((unsigned long) new_size > h->mprotect_size)
  402. {
  403. if (__mprotect ((char *) h + h->mprotect_size,
  404. (unsigned long) new_size - h->mprotect_size,
  405. mtag_mmap_flags | PROT_READ | PROT_WRITE) != 0)
  406. return -2;
  407. h->mprotect_size = new_size;
  408. }
  409. /* mprotect preserves MADV_HUGEPAGE semantics - this means that if the old
  410. region was marked with MADV_HUGEPAGE, the new region will retain that. */
  411. if (h->size < mp_.thp_pagesize)
  412. madvise_thp (h, new_size);
  413. h->size = new_size;
  414. LIBC_PROBE (memory_heap_more, 2, h, h->size);
  415. return 0;
  416. }
  417. /* Shrink a heap. */
  418. static int
  419. shrink_heap (heap_info *h, long diff)
  420. {
  421. long new_size;
  422. new_size = (long) h->size - diff;
  423. if (new_size < (long) sizeof (*h))
  424. return -1;
  425. /* Try to re-map the extra heap space freshly to save memory, and make it
  426. inaccessible. See malloc-sysdep.h to know when this is true. */
  427. if (__glibc_unlikely (check_may_shrink_heap ()))
  428. {
  429. if ((char *) MMAP ((char *) h + new_size, diff, PROT_NONE,
  430. MAP_FIXED) == (char *) MAP_FAILED)
  431. return -2;
  432. h->mprotect_size = new_size;
  433. }
  434. else
  435. __madvise ((char *) h + new_size, diff, MADV_DONTNEED);
  436. /*fprintf(stderr, "shrink %p %08lx\n", h, new_size);*/
  437. h->size = new_size;
  438. LIBC_PROBE (memory_heap_less, 2, h, h->size);
  439. return 0;
  440. }
  441. /* Delete a heap. */
  442. static int
  443. heap_trim (heap_info *heap, size_t pad)
  444. {
  445. mstate ar_ptr = heap->ar_ptr;
  446. mchunkptr top_chunk = top (ar_ptr), p;
  447. heap_info *prev_heap;
  448. long new_size, top_size, top_area, extra, prev_size, misalign;
  449. size_t max_size = heap_max_size ();
  450. /* Can this heap go away completely? */
  451. while (top_chunk == chunk_at_offset (heap, sizeof (*heap)))
  452. {
  453. prev_heap = heap->prev;
  454. prev_size = prev_heap->size - (MINSIZE - 2 * SIZE_SZ);
  455. p = chunk_at_offset (prev_heap, prev_size);
  456. /* fencepost must be properly aligned. */
  457. misalign = ((long) p) & MALLOC_ALIGN_MASK;
  458. p = chunk_at_offset (prev_heap, prev_size - misalign);
  459. assert (chunksize_nomask (p) == (0 | PREV_INUSE)); /* must be fencepost */
  460. p = prev_chunk (p);
  461. new_size = chunksize (p) + (MINSIZE - 2 * SIZE_SZ) + misalign;
  462. assert (new_size > 0 && new_size < (long) (2 * MINSIZE));
  463. if (!prev_inuse (p))
  464. new_size += prev_size (p);
  465. assert (new_size > 0 && new_size < max_size);
  466. if (new_size + (max_size - prev_heap->size) < pad + MINSIZE
  467. + heap->pagesize)
  468. break;
  469. ar_ptr->system_mem -= heap->size;
  470. LIBC_PROBE (memory_heap_free, 2, heap, heap->size);
  471. if ((char *) heap + max_size == aligned_heap_area)
  472. aligned_heap_area = NULL;
  473. __munmap (heap, max_size);
  474. heap = prev_heap;
  475. if (!prev_inuse (p)) /* consolidate backward */
  476. {
  477. p = prev_chunk (p);
  478. unlink_chunk (ar_ptr, p);
  479. }
  480. assert (((unsigned long) ((char *) p + new_size) & (heap->pagesize - 1))
  481. == 0);
  482. assert (((char *) p + new_size) == ((char *) heap + heap->size));
  483. top (ar_ptr) = top_chunk = p;
  484. set_head (top_chunk, new_size | PREV_INUSE);
  485. /*check_chunk(ar_ptr, top_chunk);*/
  486. }
  487. /* Uses similar logic for per-thread arenas as the main arena with systrim
  488. and _int_free by preserving the top pad and rounding down to the nearest
  489. page. */
  490. top_size = chunksize (top_chunk);
  491. if ((unsigned long)(top_size) <
  492. (unsigned long)(mp_.trim_threshold))
  493. return 0;
  494. top_area = top_size - MINSIZE - 1;
  495. if (top_area < 0 || (size_t) top_area <= pad)
  496. return 0;
  497. /* Release in pagesize units and round down to the nearest page. */
  498. extra = ALIGN_DOWN(top_area - pad, heap->pagesize);
  499. if (extra == 0)
  500. return 0;
  501. /* Try to shrink. */
  502. if (shrink_heap (heap, extra) != 0)
  503. return 0;
  504. ar_ptr->system_mem -= extra;
  505. /* Success. Adjust top accordingly. */
  506. set_head (top_chunk, (top_size - extra) | PREV_INUSE);
  507. /*check_chunk(ar_ptr, top_chunk);*/
  508. return 1;
  509. }
  510. /* Create a new arena with initial size "size". */
  511. #if IS_IN (libc)
  512. /* If REPLACED_ARENA is not NULL, detach it from this thread. Must be
  513. called while free_list_lock is held. */
  514. static void
  515. detach_arena (mstate replaced_arena)
  516. {
  517. if (replaced_arena != NULL)
  518. {
  519. assert (replaced_arena->attached_threads > 0);
  520. /* The current implementation only detaches from main_arena in
  521. case of allocation failure. This means that it is likely not
  522. beneficial to put the arena on free_list even if the
  523. reference count reaches zero. */
  524. --replaced_arena->attached_threads;
  525. }
  526. }
  527. static mstate
  528. _int_new_arena (size_t size)
  529. {
  530. mstate a;
  531. heap_info *h;
  532. char *ptr;
  533. unsigned long misalign;
  534. h = new_heap (size + (sizeof (*h) + sizeof (*a) + MALLOC_ALIGNMENT),
  535. mp_.top_pad);
  536. if (!h)
  537. {
  538. /* Maybe size is too large to fit in a single heap. So, just try
  539. to create a minimally-sized arena and let _int_malloc() attempt
  540. to deal with the large request via mmap_chunk(). */
  541. h = new_heap (sizeof (*h) + sizeof (*a) + MALLOC_ALIGNMENT, mp_.top_pad);
  542. if (!h)
  543. return NULL;
  544. }
  545. a = h->ar_ptr = (mstate) (h + 1);
  546. malloc_init_state (a);
  547. a->attached_threads = 1;
  548. /*a->next = NULL;*/
  549. a->system_mem = a->max_system_mem = h->size;
  550. /* Set up the top chunk, with proper alignment. */
  551. ptr = (char *) (a + 1);
  552. misalign = (uintptr_t) chunk2mem (ptr) & MALLOC_ALIGN_MASK;
  553. if (misalign > 0)
  554. ptr += MALLOC_ALIGNMENT - misalign;
  555. top (a) = (mchunkptr) ptr;
  556. set_head (top (a), (((char *) h + h->size) - ptr) | PREV_INUSE);
  557. LIBC_PROBE (memory_arena_new, 2, a, size);
  558. mstate replaced_arena = thread_arena;
  559. thread_arena = a;
  560. __libc_lock_init (a->mutex);
  561. __libc_lock_lock (list_lock);
  562. /* Add the new arena to the global list. */
  563. a->next = main_arena.next;
  564. /* FIXME: The barrier is an attempt to synchronize with read access
  565. in reused_arena, which does not acquire list_lock while
  566. traversing the list. */
  567. atomic_write_barrier ();
  568. main_arena.next = a;
  569. __libc_lock_unlock (list_lock);
  570. __libc_lock_lock (free_list_lock);
  571. detach_arena (replaced_arena);
  572. __libc_lock_unlock (free_list_lock);
  573. /* Lock this arena. NB: Another thread may have been attached to
  574. this arena because the arena is now accessible from the
  575. main_arena.next list and could have been picked by reused_arena.
  576. This can only happen for the last arena created (before the arena
  577. limit is reached). At this point, some arena has to be attached
  578. to two threads. We could acquire the arena lock before list_lock
  579. to make it less likely that reused_arena picks this new arena,
  580. but this could result in a deadlock with
  581. __malloc_fork_lock_parent. */
  582. __libc_lock_lock (a->mutex);
  583. return a;
  584. }
  585. /* Remove an arena from free_list. */
  586. static mstate
  587. get_free_list (void)
  588. {
  589. mstate replaced_arena = thread_arena;
  590. mstate result = free_list;
  591. if (result != NULL)
  592. {
  593. __libc_lock_lock (free_list_lock);
  594. result = free_list;
  595. if (result != NULL)
  596. {
  597. free_list = result->next_free;
  598. /* The arena will be attached to this thread. */
  599. assert (result->attached_threads == 0);
  600. result->attached_threads = 1;
  601. detach_arena (replaced_arena);
  602. }
  603. __libc_lock_unlock (free_list_lock);
  604. if (result != NULL)
  605. {
  606. LIBC_PROBE (memory_arena_reuse_free_list, 1, result);
  607. __libc_lock_lock (result->mutex);
  608. thread_arena = result;
  609. }
  610. }
  611. return result;
  612. }
  613. /* Remove the arena from the free list (if it is present).
  614. free_list_lock must have been acquired by the caller. */
  615. static void
  616. remove_from_free_list (mstate arena)
  617. {
  618. mstate *previous = &free_list;
  619. for (mstate p = free_list; p != NULL; p = p->next_free)
  620. {
  621. assert (p->attached_threads == 0);
  622. if (p == arena)
  623. {
  624. /* Remove the requested arena from the list. */
  625. *previous = p->next_free;
  626. break;
  627. }
  628. else
  629. previous = &p->next_free;
  630. }
  631. }
  632. /* Lock and return an arena that can be reused for memory allocation.
  633. Avoid AVOID_ARENA as we have already failed to allocate memory in
  634. it and it is currently locked. */
  635. static mstate
  636. reused_arena (mstate avoid_arena)
  637. {
  638. mstate result;
  639. /* FIXME: Access to next_to_use suffers from data races. */
  640. static mstate next_to_use;
  641. if (next_to_use == NULL)
  642. next_to_use = &main_arena;
  643. /* Iterate over all arenas (including those linked from
  644. free_list). */
  645. result = next_to_use;
  646. do
  647. {
  648. if (!__libc_lock_trylock (result->mutex))
  649. goto out;
  650. /* FIXME: This is a data race, see _int_new_arena. */
  651. result = result->next;
  652. }
  653. while (result != next_to_use);
  654. /* Avoid AVOID_ARENA as we have already failed to allocate memory
  655. in that arena and it is currently locked. */
  656. if (result == avoid_arena)
  657. result = result->next;
  658. /* No arena available without contention. Wait for the next in line. */
  659. LIBC_PROBE (memory_arena_reuse_wait, 3, &result->mutex, result, avoid_arena);
  660. __libc_lock_lock (result->mutex);
  661. out:
  662. /* Attach the arena to the current thread. */
  663. {
  664. /* Update the arena thread attachment counters. */
  665. mstate replaced_arena = thread_arena;
  666. __libc_lock_lock (free_list_lock);
  667. detach_arena (replaced_arena);
  668. /* We may have picked up an arena on the free list. We need to
  669. preserve the invariant that no arena on the free list has a
  670. positive attached_threads counter (otherwise,
  671. arena_thread_freeres cannot use the counter to determine if the
  672. arena needs to be put on the free list). We unconditionally
  673. remove the selected arena from the free list. The caller of
  674. reused_arena checked the free list and observed it to be empty,
  675. so the list is very short. */
  676. remove_from_free_list (result);
  677. ++result->attached_threads;
  678. __libc_lock_unlock (free_list_lock);
  679. }
  680. LIBC_PROBE (memory_arena_reuse, 2, result, avoid_arena);
  681. thread_arena = result;
  682. next_to_use = result->next;
  683. return result;
  684. }
  685. static mstate
  686. arena_get2 (size_t size, mstate avoid_arena)
  687. {
  688. mstate a;
  689. static size_t narenas_limit;
  690. a = get_free_list ();
  691. if (a == NULL)
  692. {
  693. /* Nothing immediately available, so generate a new arena. */
  694. if (narenas_limit == 0)
  695. {
  696. if (mp_.arena_max != 0)
  697. narenas_limit = mp_.arena_max;
  698. else if (narenas > mp_.arena_test)
  699. {
  700. int n = __get_nprocs ();
  701. if (n >= 1)
  702. narenas_limit = NARENAS_FROM_NCORES (n);
  703. else
  704. /* We have no information about the system. Assume two
  705. cores. */
  706. narenas_limit = NARENAS_FROM_NCORES (2);
  707. }
  708. }
  709. repeat:;
  710. size_t n = narenas;
  711. /* NB: the following depends on the fact that (size_t)0 - 1 is a
  712. very large number and that the underflow is OK. If arena_max
  713. is set the value of arena_test is irrelevant. If arena_test
  714. is set but narenas is not yet larger or equal to arena_test
  715. narenas_limit is 0. There is no possibility for narenas to
  716. be too big for the test to always fail since there is not
  717. enough address space to create that many arenas. */
  718. if (__glibc_unlikely (n <= narenas_limit - 1))
  719. {
  720. if (atomic_compare_and_exchange_bool_acq (&narenas, n + 1, n))
  721. goto repeat;
  722. a = _int_new_arena (size);
  723. if (__glibc_unlikely (a == NULL))
  724. atomic_fetch_add_relaxed (&narenas, -1);
  725. }
  726. else
  727. a = reused_arena (avoid_arena);
  728. }
  729. return a;
  730. }
  731. /* If we don't have the main arena, then maybe the failure is due to running
  732. out of mmapped areas, so we can try allocating on the main arena.
  733. Otherwise, it is likely that sbrk() has failed and there is still a chance
  734. to mmap(), so try one of the other arenas. */
  735. static mstate
  736. arena_get_retry (mstate ar_ptr, size_t bytes)
  737. {
  738. LIBC_PROBE (memory_arena_retry, 2, bytes, ar_ptr);
  739. __libc_lock_unlock (ar_ptr->mutex);
  740. if (ar_ptr != &main_arena)
  741. {
  742. ar_ptr = &main_arena;
  743. __libc_lock_lock (ar_ptr->mutex);
  744. }
  745. else
  746. {
  747. ar_ptr = arena_get2 (bytes, ar_ptr);
  748. }
  749. return ar_ptr;
  750. }
  751. #endif
  752. void
  753. __malloc_arena_thread_freeres (void)
  754. {
  755. /* Shut down the thread cache first. This could deallocate data for
  756. the thread arena, so do this before we put the arena on the free
  757. list. */
  758. tcache_thread_shutdown ();
  759. mstate a = thread_arena;
  760. thread_arena = NULL;
  761. if (a != NULL)
  762. {
  763. __libc_lock_lock (free_list_lock);
  764. /* If this was the last attached thread for this arena, put the
  765. arena on the free list. */
  766. assert (a->attached_threads > 0);
  767. if (--a->attached_threads == 0)
  768. {
  769. a->next_free = free_list;
  770. free_list = a;
  771. }
  772. __libc_lock_unlock (free_list_lock);
  773. }
  774. }
  775. /*
  776. * Local variables:
  777. * c-basic-offset: 2
  778. * End:
  779. */