arena.c 29 KB

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