tcache.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. #include "jemalloc/internal/jemalloc_preamble.h"
  2. #include "jemalloc/internal/jemalloc_internal_includes.h"
  3. #include "jemalloc/internal/assert.h"
  4. #include "jemalloc/internal/mutex.h"
  5. #include "jemalloc/internal/safety_check.h"
  6. #include "jemalloc/internal/san.h"
  7. #include "jemalloc/internal/sc.h"
  8. /******************************************************************************/
  9. /* Data. */
  10. bool opt_tcache = true;
  11. /* tcache_maxclass is set to 32KB by default. */
  12. size_t opt_tcache_max = ((size_t)1) << 15;
  13. /* Reasonable defaults for min and max values. */
  14. unsigned opt_tcache_nslots_small_min = 20;
  15. unsigned opt_tcache_nslots_small_max = 200;
  16. unsigned opt_tcache_nslots_large = 20;
  17. /*
  18. * We attempt to make the number of slots in a tcache bin for a given size class
  19. * equal to the number of objects in a slab times some multiplier. By default,
  20. * the multiplier is 2 (i.e. we set the maximum number of objects in the tcache
  21. * to twice the number of objects in a slab).
  22. * This is bounded by some other constraints as well, like the fact that it
  23. * must be even, must be less than opt_tcache_nslots_small_max, etc..
  24. */
  25. ssize_t opt_lg_tcache_nslots_mul = 1;
  26. /*
  27. * Number of allocation bytes between tcache incremental GCs. Again, this
  28. * default just seems to work well; more tuning is possible.
  29. */
  30. size_t opt_tcache_gc_incr_bytes = 65536;
  31. /*
  32. * With default settings, we may end up flushing small bins frequently with
  33. * small flush amounts. To limit this tendency, we can set a number of bytes to
  34. * "delay" by. If we try to flush N M-byte items, we decrease that size-class's
  35. * delay by N * M. So, if delay is 1024 and we're looking at the 64-byte size
  36. * class, we won't do any flushing until we've been asked to flush 1024/64 == 16
  37. * items. This can happen in any configuration (i.e. being asked to flush 16
  38. * items once, or 4 items 4 times).
  39. *
  40. * Practically, this is stored as a count of items in a uint8_t, so the
  41. * effective maximum value for a size class is 255 * sz.
  42. */
  43. size_t opt_tcache_gc_delay_bytes = 0;
  44. /*
  45. * When a cache bin is flushed because it's full, how much of it do we flush?
  46. * By default, we flush half the maximum number of items.
  47. */
  48. unsigned opt_lg_tcache_flush_small_div = 1;
  49. unsigned opt_lg_tcache_flush_large_div = 1;
  50. cache_bin_info_t *tcache_bin_info;
  51. /* Total stack size required (per tcache). Include the padding above. */
  52. static size_t tcache_bin_alloc_size;
  53. static size_t tcache_bin_alloc_alignment;
  54. /* Number of cache bins enabled, including both large and small. */
  55. unsigned nhbins;
  56. /* Max size class to be cached (can be small or large). */
  57. size_t tcache_maxclass;
  58. tcaches_t *tcaches;
  59. /* Index of first element within tcaches that has never been used. */
  60. static unsigned tcaches_past;
  61. /* Head of singly linked list tracking available tcaches elements. */
  62. static tcaches_t *tcaches_avail;
  63. /* Protects tcaches{,_past,_avail}. */
  64. static malloc_mutex_t tcaches_mtx;
  65. /******************************************************************************/
  66. size_t
  67. tcache_salloc(tsdn_t *tsdn, const void *ptr) {
  68. return arena_salloc(tsdn, ptr);
  69. }
  70. uint64_t
  71. tcache_gc_new_event_wait(tsd_t *tsd) {
  72. return opt_tcache_gc_incr_bytes;
  73. }
  74. uint64_t
  75. tcache_gc_postponed_event_wait(tsd_t *tsd) {
  76. return TE_MIN_START_WAIT;
  77. }
  78. uint64_t
  79. tcache_gc_dalloc_new_event_wait(tsd_t *tsd) {
  80. return opt_tcache_gc_incr_bytes;
  81. }
  82. uint64_t
  83. tcache_gc_dalloc_postponed_event_wait(tsd_t *tsd) {
  84. return TE_MIN_START_WAIT;
  85. }
  86. static uint8_t
  87. tcache_gc_item_delay_compute(szind_t szind) {
  88. assert(szind < SC_NBINS);
  89. size_t sz = sz_index2size(szind);
  90. size_t item_delay = opt_tcache_gc_delay_bytes / sz;
  91. size_t delay_max = ZU(1)
  92. << (sizeof(((tcache_slow_t *)NULL)->bin_flush_delay_items[0]) * 8);
  93. if (item_delay >= delay_max) {
  94. item_delay = delay_max - 1;
  95. }
  96. return (uint8_t)item_delay;
  97. }
  98. static void
  99. tcache_gc_small(tsd_t *tsd, tcache_slow_t *tcache_slow, tcache_t *tcache,
  100. szind_t szind) {
  101. /* Aim to flush 3/4 of items below low-water. */
  102. assert(szind < SC_NBINS);
  103. cache_bin_t *cache_bin = &tcache->bins[szind];
  104. cache_bin_sz_t ncached = cache_bin_ncached_get_local(cache_bin,
  105. &tcache_bin_info[szind]);
  106. cache_bin_sz_t low_water = cache_bin_low_water_get(cache_bin,
  107. &tcache_bin_info[szind]);
  108. assert(!tcache_slow->bin_refilled[szind]);
  109. size_t nflush = low_water - (low_water >> 2);
  110. if (nflush < tcache_slow->bin_flush_delay_items[szind]) {
  111. /* Workaround for a conversion warning. */
  112. uint8_t nflush_uint8 = (uint8_t)nflush;
  113. assert(sizeof(tcache_slow->bin_flush_delay_items[0]) ==
  114. sizeof(nflush_uint8));
  115. tcache_slow->bin_flush_delay_items[szind] -= nflush_uint8;
  116. return;
  117. } else {
  118. tcache_slow->bin_flush_delay_items[szind]
  119. = tcache_gc_item_delay_compute(szind);
  120. }
  121. tcache_bin_flush_small(tsd, tcache, cache_bin, szind,
  122. (unsigned)(ncached - nflush));
  123. /*
  124. * Reduce fill count by 2X. Limit lg_fill_div such that
  125. * the fill count is always at least 1.
  126. */
  127. if ((cache_bin_info_ncached_max(&tcache_bin_info[szind])
  128. >> (tcache_slow->lg_fill_div[szind] + 1)) >= 1) {
  129. tcache_slow->lg_fill_div[szind]++;
  130. }
  131. }
  132. static void
  133. tcache_gc_large(tsd_t *tsd, tcache_slow_t *tcache_slow, tcache_t *tcache,
  134. szind_t szind) {
  135. /* Like the small GC; flush 3/4 of untouched items. */
  136. assert(szind >= SC_NBINS);
  137. cache_bin_t *cache_bin = &tcache->bins[szind];
  138. cache_bin_sz_t ncached = cache_bin_ncached_get_local(cache_bin,
  139. &tcache_bin_info[szind]);
  140. cache_bin_sz_t low_water = cache_bin_low_water_get(cache_bin,
  141. &tcache_bin_info[szind]);
  142. tcache_bin_flush_large(tsd, tcache, cache_bin, szind,
  143. (unsigned)(ncached - low_water + (low_water >> 2)));
  144. }
  145. static void
  146. tcache_event(tsd_t *tsd) {
  147. tcache_t *tcache = tcache_get(tsd);
  148. if (tcache == NULL) {
  149. return;
  150. }
  151. tcache_slow_t *tcache_slow = tsd_tcache_slowp_get(tsd);
  152. szind_t szind = tcache_slow->next_gc_bin;
  153. bool is_small = (szind < SC_NBINS);
  154. cache_bin_t *cache_bin = &tcache->bins[szind];
  155. tcache_bin_flush_stashed(tsd, tcache, cache_bin, szind, is_small);
  156. cache_bin_sz_t low_water = cache_bin_low_water_get(cache_bin,
  157. &tcache_bin_info[szind]);
  158. if (low_water > 0) {
  159. if (is_small) {
  160. tcache_gc_small(tsd, tcache_slow, tcache, szind);
  161. } else {
  162. tcache_gc_large(tsd, tcache_slow, tcache, szind);
  163. }
  164. } else if (is_small && tcache_slow->bin_refilled[szind]) {
  165. assert(low_water == 0);
  166. /*
  167. * Increase fill count by 2X for small bins. Make sure
  168. * lg_fill_div stays greater than 0.
  169. */
  170. if (tcache_slow->lg_fill_div[szind] > 1) {
  171. tcache_slow->lg_fill_div[szind]--;
  172. }
  173. tcache_slow->bin_refilled[szind] = false;
  174. }
  175. cache_bin_low_water_set(cache_bin);
  176. tcache_slow->next_gc_bin++;
  177. if (tcache_slow->next_gc_bin == nhbins) {
  178. tcache_slow->next_gc_bin = 0;
  179. }
  180. }
  181. void
  182. tcache_gc_event_handler(tsd_t *tsd, uint64_t elapsed) {
  183. assert(elapsed == TE_INVALID_ELAPSED);
  184. tcache_event(tsd);
  185. }
  186. void
  187. tcache_gc_dalloc_event_handler(tsd_t *tsd, uint64_t elapsed) {
  188. assert(elapsed == TE_INVALID_ELAPSED);
  189. tcache_event(tsd);
  190. }
  191. void *
  192. tcache_alloc_small_hard(tsdn_t *tsdn, arena_t *arena,
  193. tcache_t *tcache, cache_bin_t *cache_bin, szind_t binind,
  194. bool *tcache_success) {
  195. tcache_slow_t *tcache_slow = tcache->tcache_slow;
  196. void *ret;
  197. assert(tcache_slow->arena != NULL);
  198. unsigned nfill = cache_bin_info_ncached_max(&tcache_bin_info[binind])
  199. >> tcache_slow->lg_fill_div[binind];
  200. arena_cache_bin_fill_small(tsdn, arena, cache_bin,
  201. &tcache_bin_info[binind], binind, nfill);
  202. tcache_slow->bin_refilled[binind] = true;
  203. ret = cache_bin_alloc(cache_bin, tcache_success);
  204. return ret;
  205. }
  206. static const void *
  207. tcache_bin_flush_ptr_getter(void *arr_ctx, size_t ind) {
  208. cache_bin_ptr_array_t *arr = (cache_bin_ptr_array_t *)arr_ctx;
  209. return arr->ptr[ind];
  210. }
  211. static void
  212. tcache_bin_flush_metadata_visitor(void *szind_sum_ctx,
  213. emap_full_alloc_ctx_t *alloc_ctx) {
  214. size_t *szind_sum = (size_t *)szind_sum_ctx;
  215. *szind_sum -= alloc_ctx->szind;
  216. util_prefetch_write_range(alloc_ctx->edata, sizeof(edata_t));
  217. }
  218. JEMALLOC_NOINLINE static void
  219. tcache_bin_flush_size_check_fail(cache_bin_ptr_array_t *arr, szind_t szind,
  220. size_t nptrs, emap_batch_lookup_result_t *edatas) {
  221. bool found_mismatch = false;
  222. for (size_t i = 0; i < nptrs; i++) {
  223. szind_t true_szind = edata_szind_get(edatas[i].edata);
  224. if (true_szind != szind) {
  225. found_mismatch = true;
  226. safety_check_fail_sized_dealloc(
  227. /* current_dealloc */ false,
  228. /* ptr */ tcache_bin_flush_ptr_getter(arr, i),
  229. /* true_size */ sz_index2size(true_szind),
  230. /* input_size */ sz_index2size(szind));
  231. }
  232. }
  233. assert(found_mismatch);
  234. }
  235. static void
  236. tcache_bin_flush_edatas_lookup(tsd_t *tsd, cache_bin_ptr_array_t *arr,
  237. szind_t binind, size_t nflush, emap_batch_lookup_result_t *edatas) {
  238. /*
  239. * This gets compiled away when config_opt_safety_checks is false.
  240. * Checks for sized deallocation bugs, failing early rather than
  241. * corrupting metadata.
  242. */
  243. size_t szind_sum = binind * nflush;
  244. emap_edata_lookup_batch(tsd, &arena_emap_global, nflush,
  245. &tcache_bin_flush_ptr_getter, (void *)arr,
  246. &tcache_bin_flush_metadata_visitor, (void *)&szind_sum,
  247. edatas);
  248. if (config_opt_safety_checks && unlikely(szind_sum != 0)) {
  249. tcache_bin_flush_size_check_fail(arr, binind, nflush, edatas);
  250. }
  251. }
  252. JEMALLOC_ALWAYS_INLINE bool
  253. tcache_bin_flush_match(edata_t *edata, unsigned cur_arena_ind,
  254. unsigned cur_binshard, bool small) {
  255. if (small) {
  256. return edata_arena_ind_get(edata) == cur_arena_ind
  257. && edata_binshard_get(edata) == cur_binshard;
  258. } else {
  259. return edata_arena_ind_get(edata) == cur_arena_ind;
  260. }
  261. }
  262. JEMALLOC_ALWAYS_INLINE void
  263. tcache_bin_flush_impl(tsd_t *tsd, tcache_t *tcache, cache_bin_t *cache_bin,
  264. szind_t binind, cache_bin_ptr_array_t *ptrs, unsigned nflush, bool small) {
  265. tcache_slow_t *tcache_slow = tcache->tcache_slow;
  266. /*
  267. * A couple lookup calls take tsdn; declare it once for convenience
  268. * instead of calling tsd_tsdn(tsd) all the time.
  269. */
  270. tsdn_t *tsdn = tsd_tsdn(tsd);
  271. if (small) {
  272. assert(binind < SC_NBINS);
  273. } else {
  274. assert(binind < nhbins);
  275. }
  276. arena_t *tcache_arena = tcache_slow->arena;
  277. assert(tcache_arena != NULL);
  278. /*
  279. * Variable length array must have > 0 length; the last element is never
  280. * touched (it's just included to satisfy the no-zero-length rule).
  281. */
  282. VARIABLE_ARRAY(emap_batch_lookup_result_t, item_edata, nflush + 1);
  283. tcache_bin_flush_edatas_lookup(tsd, ptrs, binind, nflush, item_edata);
  284. /*
  285. * The slabs where we freed the last remaining object in the slab (and
  286. * so need to free the slab itself).
  287. * Used only if small == true.
  288. */
  289. unsigned dalloc_count = 0;
  290. VARIABLE_ARRAY(edata_t *, dalloc_slabs, nflush + 1);
  291. /*
  292. * We're about to grab a bunch of locks. If one of them happens to be
  293. * the one guarding the arena-level stats counters we flush our
  294. * thread-local ones to, we do so under one critical section.
  295. */
  296. bool merged_stats = false;
  297. while (nflush > 0) {
  298. /* Lock the arena, or bin, associated with the first object. */
  299. edata_t *edata = item_edata[0].edata;
  300. unsigned cur_arena_ind = edata_arena_ind_get(edata);
  301. arena_t *cur_arena = arena_get(tsdn, cur_arena_ind, false);
  302. /*
  303. * These assignments are always overwritten when small is true,
  304. * and their values are always ignored when small is false, but
  305. * to avoid the technical UB when we pass them as parameters, we
  306. * need to intialize them.
  307. */
  308. unsigned cur_binshard = 0;
  309. bin_t *cur_bin = NULL;
  310. if (small) {
  311. cur_binshard = edata_binshard_get(edata);
  312. cur_bin = arena_get_bin(cur_arena, binind,
  313. cur_binshard);
  314. assert(cur_binshard < bin_infos[binind].n_shards);
  315. /*
  316. * If you're looking at profiles, you might think this
  317. * is a good place to prefetch the bin stats, which are
  318. * often a cache miss. This turns out not to be
  319. * helpful on the workloads we've looked at, with moving
  320. * the bin stats next to the lock seeming to do better.
  321. */
  322. }
  323. if (small) {
  324. malloc_mutex_lock(tsdn, &cur_bin->lock);
  325. }
  326. if (!small && !arena_is_auto(cur_arena)) {
  327. malloc_mutex_lock(tsdn, &cur_arena->large_mtx);
  328. }
  329. /*
  330. * If we acquired the right lock and have some stats to flush,
  331. * flush them.
  332. */
  333. if (config_stats && tcache_arena == cur_arena
  334. && !merged_stats) {
  335. merged_stats = true;
  336. if (small) {
  337. cur_bin->stats.nflushes++;
  338. cur_bin->stats.nrequests +=
  339. cache_bin->tstats.nrequests;
  340. cache_bin->tstats.nrequests = 0;
  341. } else {
  342. arena_stats_large_flush_nrequests_add(tsdn,
  343. &tcache_arena->stats, binind,
  344. cache_bin->tstats.nrequests);
  345. cache_bin->tstats.nrequests = 0;
  346. }
  347. }
  348. /*
  349. * Large allocations need special prep done. Afterwards, we can
  350. * drop the large lock.
  351. */
  352. if (!small) {
  353. for (unsigned i = 0; i < nflush; i++) {
  354. void *ptr = ptrs->ptr[i];
  355. edata = item_edata[i].edata;
  356. assert(ptr != NULL && edata != NULL);
  357. if (tcache_bin_flush_match(edata, cur_arena_ind,
  358. cur_binshard, small)) {
  359. large_dalloc_prep_locked(tsdn,
  360. edata);
  361. }
  362. }
  363. }
  364. if (!small && !arena_is_auto(cur_arena)) {
  365. malloc_mutex_unlock(tsdn, &cur_arena->large_mtx);
  366. }
  367. /* Deallocate whatever we can. */
  368. unsigned ndeferred = 0;
  369. /* Init only to avoid used-uninitialized warning. */
  370. arena_dalloc_bin_locked_info_t dalloc_bin_info = {0};
  371. if (small) {
  372. arena_dalloc_bin_locked_begin(&dalloc_bin_info, binind);
  373. }
  374. for (unsigned i = 0; i < nflush; i++) {
  375. void *ptr = ptrs->ptr[i];
  376. edata = item_edata[i].edata;
  377. assert(ptr != NULL && edata != NULL);
  378. if (!tcache_bin_flush_match(edata, cur_arena_ind,
  379. cur_binshard, small)) {
  380. /*
  381. * The object was allocated either via a
  382. * different arena, or a different bin in this
  383. * arena. Either way, stash the object so that
  384. * it can be handled in a future pass.
  385. */
  386. ptrs->ptr[ndeferred] = ptr;
  387. item_edata[ndeferred].edata = edata;
  388. ndeferred++;
  389. continue;
  390. }
  391. if (small) {
  392. if (arena_dalloc_bin_locked_step(tsdn,
  393. cur_arena, cur_bin, &dalloc_bin_info,
  394. binind, edata, ptr)) {
  395. dalloc_slabs[dalloc_count] = edata;
  396. dalloc_count++;
  397. }
  398. } else {
  399. if (large_dalloc_safety_checks(edata, ptr,
  400. binind)) {
  401. /* See the comment in isfree. */
  402. continue;
  403. }
  404. large_dalloc_finish(tsdn, edata);
  405. }
  406. }
  407. if (small) {
  408. arena_dalloc_bin_locked_finish(tsdn, cur_arena, cur_bin,
  409. &dalloc_bin_info);
  410. malloc_mutex_unlock(tsdn, &cur_bin->lock);
  411. }
  412. arena_decay_ticks(tsdn, cur_arena, nflush - ndeferred);
  413. nflush = ndeferred;
  414. }
  415. /* Handle all deferred slab dalloc. */
  416. assert(small || dalloc_count == 0);
  417. for (unsigned i = 0; i < dalloc_count; i++) {
  418. edata_t *slab = dalloc_slabs[i];
  419. arena_slab_dalloc(tsdn, arena_get_from_edata(slab), slab);
  420. }
  421. if (config_stats && !merged_stats) {
  422. if (small) {
  423. /*
  424. * The flush loop didn't happen to flush to this
  425. * thread's arena, so the stats didn't get merged.
  426. * Manually do so now.
  427. */
  428. bin_t *bin = arena_bin_choose(tsdn, tcache_arena,
  429. binind, NULL);
  430. malloc_mutex_lock(tsdn, &bin->lock);
  431. bin->stats.nflushes++;
  432. bin->stats.nrequests += cache_bin->tstats.nrequests;
  433. cache_bin->tstats.nrequests = 0;
  434. malloc_mutex_unlock(tsdn, &bin->lock);
  435. } else {
  436. arena_stats_large_flush_nrequests_add(tsdn,
  437. &tcache_arena->stats, binind,
  438. cache_bin->tstats.nrequests);
  439. cache_bin->tstats.nrequests = 0;
  440. }
  441. }
  442. }
  443. JEMALLOC_ALWAYS_INLINE void
  444. tcache_bin_flush_bottom(tsd_t *tsd, tcache_t *tcache, cache_bin_t *cache_bin,
  445. szind_t binind, unsigned rem, bool small) {
  446. tcache_bin_flush_stashed(tsd, tcache, cache_bin, binind, small);
  447. cache_bin_sz_t ncached = cache_bin_ncached_get_local(cache_bin,
  448. &tcache_bin_info[binind]);
  449. assert((cache_bin_sz_t)rem <= ncached);
  450. unsigned nflush = ncached - rem;
  451. CACHE_BIN_PTR_ARRAY_DECLARE(ptrs, nflush);
  452. cache_bin_init_ptr_array_for_flush(cache_bin, &tcache_bin_info[binind],
  453. &ptrs, nflush);
  454. tcache_bin_flush_impl(tsd, tcache, cache_bin, binind, &ptrs, nflush,
  455. small);
  456. cache_bin_finish_flush(cache_bin, &tcache_bin_info[binind], &ptrs,
  457. ncached - rem);
  458. }
  459. void
  460. tcache_bin_flush_small(tsd_t *tsd, tcache_t *tcache, cache_bin_t *cache_bin,
  461. szind_t binind, unsigned rem) {
  462. tcache_bin_flush_bottom(tsd, tcache, cache_bin, binind, rem, true);
  463. }
  464. void
  465. tcache_bin_flush_large(tsd_t *tsd, tcache_t *tcache, cache_bin_t *cache_bin,
  466. szind_t binind, unsigned rem) {
  467. tcache_bin_flush_bottom(tsd, tcache, cache_bin, binind, rem, false);
  468. }
  469. /*
  470. * Flushing stashed happens when 1) tcache fill, 2) tcache flush, or 3) tcache
  471. * GC event. This makes sure that the stashed items do not hold memory for too
  472. * long, and new buffers can only be allocated when nothing is stashed.
  473. *
  474. * The downside is, the time between stash and flush may be relatively short,
  475. * especially when the request rate is high. It lowers the chance of detecting
  476. * write-after-free -- however that is a delayed detection anyway, and is less
  477. * of a focus than the memory overhead.
  478. */
  479. void
  480. tcache_bin_flush_stashed(tsd_t *tsd, tcache_t *tcache, cache_bin_t *cache_bin,
  481. szind_t binind, bool is_small) {
  482. cache_bin_info_t *info = &tcache_bin_info[binind];
  483. /*
  484. * The two below are for assertion only. The content of original cached
  485. * items remain unchanged -- the stashed items reside on the other end
  486. * of the stack. Checking the stack head and ncached to verify.
  487. */
  488. void *head_content = *cache_bin->stack_head;
  489. cache_bin_sz_t orig_cached = cache_bin_ncached_get_local(cache_bin,
  490. info);
  491. cache_bin_sz_t nstashed = cache_bin_nstashed_get_local(cache_bin, info);
  492. assert(orig_cached + nstashed <= cache_bin_info_ncached_max(info));
  493. if (nstashed == 0) {
  494. return;
  495. }
  496. CACHE_BIN_PTR_ARRAY_DECLARE(ptrs, nstashed);
  497. cache_bin_init_ptr_array_for_stashed(cache_bin, binind, info, &ptrs,
  498. nstashed);
  499. san_check_stashed_ptrs(ptrs.ptr, nstashed, sz_index2size(binind));
  500. tcache_bin_flush_impl(tsd, tcache, cache_bin, binind, &ptrs, nstashed,
  501. is_small);
  502. cache_bin_finish_flush_stashed(cache_bin, info);
  503. assert(cache_bin_nstashed_get_local(cache_bin, info) == 0);
  504. assert(cache_bin_ncached_get_local(cache_bin, info) == orig_cached);
  505. assert(head_content == *cache_bin->stack_head);
  506. }
  507. void
  508. tcache_arena_associate(tsdn_t *tsdn, tcache_slow_t *tcache_slow,
  509. tcache_t *tcache, arena_t *arena) {
  510. assert(tcache_slow->arena == NULL);
  511. tcache_slow->arena = arena;
  512. if (config_stats) {
  513. /* Link into list of extant tcaches. */
  514. malloc_mutex_lock(tsdn, &arena->tcache_ql_mtx);
  515. ql_elm_new(tcache_slow, link);
  516. ql_tail_insert(&arena->tcache_ql, tcache_slow, link);
  517. cache_bin_array_descriptor_init(
  518. &tcache_slow->cache_bin_array_descriptor, tcache->bins);
  519. ql_tail_insert(&arena->cache_bin_array_descriptor_ql,
  520. &tcache_slow->cache_bin_array_descriptor, link);
  521. malloc_mutex_unlock(tsdn, &arena->tcache_ql_mtx);
  522. }
  523. }
  524. static void
  525. tcache_arena_dissociate(tsdn_t *tsdn, tcache_slow_t *tcache_slow,
  526. tcache_t *tcache) {
  527. arena_t *arena = tcache_slow->arena;
  528. assert(arena != NULL);
  529. if (config_stats) {
  530. /* Unlink from list of extant tcaches. */
  531. malloc_mutex_lock(tsdn, &arena->tcache_ql_mtx);
  532. if (config_debug) {
  533. bool in_ql = false;
  534. tcache_slow_t *iter;
  535. ql_foreach(iter, &arena->tcache_ql, link) {
  536. if (iter == tcache_slow) {
  537. in_ql = true;
  538. break;
  539. }
  540. }
  541. assert(in_ql);
  542. }
  543. ql_remove(&arena->tcache_ql, tcache_slow, link);
  544. ql_remove(&arena->cache_bin_array_descriptor_ql,
  545. &tcache_slow->cache_bin_array_descriptor, link);
  546. tcache_stats_merge(tsdn, tcache_slow->tcache, arena);
  547. malloc_mutex_unlock(tsdn, &arena->tcache_ql_mtx);
  548. }
  549. tcache_slow->arena = NULL;
  550. }
  551. void
  552. tcache_arena_reassociate(tsdn_t *tsdn, tcache_slow_t *tcache_slow,
  553. tcache_t *tcache, arena_t *arena) {
  554. tcache_arena_dissociate(tsdn, tcache_slow, tcache);
  555. tcache_arena_associate(tsdn, tcache_slow, tcache, arena);
  556. }
  557. bool
  558. tsd_tcache_enabled_data_init(tsd_t *tsd) {
  559. /* Called upon tsd initialization. */
  560. tsd_tcache_enabled_set(tsd, opt_tcache);
  561. tsd_slow_update(tsd);
  562. if (opt_tcache) {
  563. /* Trigger tcache init. */
  564. tsd_tcache_data_init(tsd);
  565. }
  566. return false;
  567. }
  568. static void
  569. tcache_init(tsd_t *tsd, tcache_slow_t *tcache_slow, tcache_t *tcache,
  570. void *mem) {
  571. tcache->tcache_slow = tcache_slow;
  572. tcache_slow->tcache = tcache;
  573. memset(&tcache_slow->link, 0, sizeof(ql_elm(tcache_t)));
  574. tcache_slow->next_gc_bin = 0;
  575. tcache_slow->arena = NULL;
  576. tcache_slow->dyn_alloc = mem;
  577. /*
  578. * We reserve cache bins for all small size classes, even if some may
  579. * not get used (i.e. bins higher than nhbins). This allows the fast
  580. * and common paths to access cache bin metadata safely w/o worrying
  581. * about which ones are disabled.
  582. */
  583. unsigned n_reserved_bins = nhbins < SC_NBINS ? SC_NBINS : nhbins;
  584. memset(tcache->bins, 0, sizeof(cache_bin_t) * n_reserved_bins);
  585. size_t cur_offset = 0;
  586. cache_bin_preincrement(tcache_bin_info, nhbins, mem,
  587. &cur_offset);
  588. for (unsigned i = 0; i < nhbins; i++) {
  589. if (i < SC_NBINS) {
  590. tcache_slow->lg_fill_div[i] = 1;
  591. tcache_slow->bin_refilled[i] = false;
  592. tcache_slow->bin_flush_delay_items[i]
  593. = tcache_gc_item_delay_compute(i);
  594. }
  595. cache_bin_t *cache_bin = &tcache->bins[i];
  596. cache_bin_init(cache_bin, &tcache_bin_info[i], mem,
  597. &cur_offset);
  598. }
  599. /*
  600. * For small size classes beyond tcache_maxclass (i.e. nhbins < NBINS),
  601. * their cache bins are initialized to a state to safely and efficiently
  602. * fail all fastpath alloc / free, so that no additional check around
  603. * nhbins is needed on fastpath.
  604. */
  605. for (unsigned i = nhbins; i < SC_NBINS; i++) {
  606. /* Disabled small bins. */
  607. cache_bin_t *cache_bin = &tcache->bins[i];
  608. void *fake_stack = mem;
  609. size_t fake_offset = 0;
  610. cache_bin_init(cache_bin, &tcache_bin_info[i], fake_stack,
  611. &fake_offset);
  612. assert(tcache_small_bin_disabled(i, cache_bin));
  613. }
  614. cache_bin_postincrement(tcache_bin_info, nhbins, mem,
  615. &cur_offset);
  616. /* Sanity check that the whole stack is used. */
  617. assert(cur_offset == tcache_bin_alloc_size);
  618. }
  619. /* Initialize auto tcache (embedded in TSD). */
  620. bool
  621. tsd_tcache_data_init(tsd_t *tsd) {
  622. tcache_slow_t *tcache_slow = tsd_tcache_slowp_get_unsafe(tsd);
  623. tcache_t *tcache = tsd_tcachep_get_unsafe(tsd);
  624. assert(cache_bin_still_zero_initialized(&tcache->bins[0]));
  625. size_t alignment = tcache_bin_alloc_alignment;
  626. size_t size = sz_sa2u(tcache_bin_alloc_size, alignment);
  627. void *mem = ipallocztm(tsd_tsdn(tsd), size, alignment, true, NULL,
  628. true, arena_get(TSDN_NULL, 0, true));
  629. if (mem == NULL) {
  630. return true;
  631. }
  632. tcache_init(tsd, tcache_slow, tcache, mem);
  633. /*
  634. * Initialization is a bit tricky here. After malloc init is done, all
  635. * threads can rely on arena_choose and associate tcache accordingly.
  636. * However, the thread that does actual malloc bootstrapping relies on
  637. * functional tsd, and it can only rely on a0. In that case, we
  638. * associate its tcache to a0 temporarily, and later on
  639. * arena_choose_hard() will re-associate properly.
  640. */
  641. tcache_slow->arena = NULL;
  642. arena_t *arena;
  643. if (!malloc_initialized()) {
  644. /* If in initialization, assign to a0. */
  645. arena = arena_get(tsd_tsdn(tsd), 0, false);
  646. tcache_arena_associate(tsd_tsdn(tsd), tcache_slow, tcache,
  647. arena);
  648. } else {
  649. arena = arena_choose(tsd, NULL);
  650. /* This may happen if thread.tcache.enabled is used. */
  651. if (tcache_slow->arena == NULL) {
  652. tcache_arena_associate(tsd_tsdn(tsd), tcache_slow,
  653. tcache, arena);
  654. }
  655. }
  656. assert(arena == tcache_slow->arena);
  657. return false;
  658. }
  659. /* Created manual tcache for tcache.create mallctl. */
  660. tcache_t *
  661. tcache_create_explicit(tsd_t *tsd) {
  662. /*
  663. * We place the cache bin stacks, then the tcache_t, then a pointer to
  664. * the beginning of the whole allocation (for freeing). The makes sure
  665. * the cache bins have the requested alignment.
  666. */
  667. size_t size = tcache_bin_alloc_size + sizeof(tcache_t)
  668. + sizeof(tcache_slow_t);
  669. /* Naturally align the pointer stacks. */
  670. size = PTR_CEILING(size);
  671. size = sz_sa2u(size, tcache_bin_alloc_alignment);
  672. void *mem = ipallocztm(tsd_tsdn(tsd), size, tcache_bin_alloc_alignment,
  673. true, NULL, true, arena_get(TSDN_NULL, 0, true));
  674. if (mem == NULL) {
  675. return NULL;
  676. }
  677. tcache_t *tcache = (void *)((uintptr_t)mem + tcache_bin_alloc_size);
  678. tcache_slow_t *tcache_slow =
  679. (void *)((uintptr_t)mem + tcache_bin_alloc_size + sizeof(tcache_t));
  680. tcache_init(tsd, tcache_slow, tcache, mem);
  681. tcache_arena_associate(tsd_tsdn(tsd), tcache_slow, tcache,
  682. arena_ichoose(tsd, NULL));
  683. return tcache;
  684. }
  685. static void
  686. tcache_flush_cache(tsd_t *tsd, tcache_t *tcache) {
  687. tcache_slow_t *tcache_slow = tcache->tcache_slow;
  688. assert(tcache_slow->arena != NULL);
  689. for (unsigned i = 0; i < nhbins; i++) {
  690. cache_bin_t *cache_bin = &tcache->bins[i];
  691. if (i < SC_NBINS) {
  692. tcache_bin_flush_small(tsd, tcache, cache_bin, i, 0);
  693. } else {
  694. tcache_bin_flush_large(tsd, tcache, cache_bin, i, 0);
  695. }
  696. if (config_stats) {
  697. assert(cache_bin->tstats.nrequests == 0);
  698. }
  699. }
  700. }
  701. void
  702. tcache_flush(tsd_t *tsd) {
  703. assert(tcache_available(tsd));
  704. tcache_flush_cache(tsd, tsd_tcachep_get(tsd));
  705. }
  706. static void
  707. tcache_destroy(tsd_t *tsd, tcache_t *tcache, bool tsd_tcache) {
  708. tcache_slow_t *tcache_slow = tcache->tcache_slow;
  709. tcache_flush_cache(tsd, tcache);
  710. arena_t *arena = tcache_slow->arena;
  711. tcache_arena_dissociate(tsd_tsdn(tsd), tcache_slow, tcache);
  712. if (tsd_tcache) {
  713. cache_bin_t *cache_bin = &tcache->bins[0];
  714. cache_bin_assert_empty(cache_bin, &tcache_bin_info[0]);
  715. }
  716. idalloctm(tsd_tsdn(tsd), tcache_slow->dyn_alloc, NULL, NULL, true,
  717. true);
  718. /*
  719. * The deallocation and tcache flush above may not trigger decay since
  720. * we are on the tcache shutdown path (potentially with non-nominal
  721. * tsd). Manually trigger decay to avoid pathological cases. Also
  722. * include arena 0 because the tcache array is allocated from it.
  723. */
  724. arena_decay(tsd_tsdn(tsd), arena_get(tsd_tsdn(tsd), 0, false),
  725. false, false);
  726. if (arena_nthreads_get(arena, false) == 0 &&
  727. !background_thread_enabled()) {
  728. /* Force purging when no threads assigned to the arena anymore. */
  729. arena_decay(tsd_tsdn(tsd), arena,
  730. /* is_background_thread */ false, /* all */ true);
  731. } else {
  732. arena_decay(tsd_tsdn(tsd), arena,
  733. /* is_background_thread */ false, /* all */ false);
  734. }
  735. }
  736. /* For auto tcache (embedded in TSD) only. */
  737. void
  738. tcache_cleanup(tsd_t *tsd) {
  739. tcache_t *tcache = tsd_tcachep_get(tsd);
  740. if (!tcache_available(tsd)) {
  741. assert(tsd_tcache_enabled_get(tsd) == false);
  742. assert(cache_bin_still_zero_initialized(&tcache->bins[0]));
  743. return;
  744. }
  745. assert(tsd_tcache_enabled_get(tsd));
  746. assert(!cache_bin_still_zero_initialized(&tcache->bins[0]));
  747. tcache_destroy(tsd, tcache, true);
  748. if (config_debug) {
  749. /*
  750. * For debug testing only, we want to pretend we're still in the
  751. * zero-initialized state.
  752. */
  753. memset(tcache->bins, 0, sizeof(cache_bin_t) * nhbins);
  754. }
  755. }
  756. void
  757. tcache_stats_merge(tsdn_t *tsdn, tcache_t *tcache, arena_t *arena) {
  758. cassert(config_stats);
  759. /* Merge and reset tcache stats. */
  760. for (unsigned i = 0; i < nhbins; i++) {
  761. cache_bin_t *cache_bin = &tcache->bins[i];
  762. if (i < SC_NBINS) {
  763. bin_t *bin = arena_bin_choose(tsdn, arena, i, NULL);
  764. malloc_mutex_lock(tsdn, &bin->lock);
  765. bin->stats.nrequests += cache_bin->tstats.nrequests;
  766. malloc_mutex_unlock(tsdn, &bin->lock);
  767. } else {
  768. arena_stats_large_flush_nrequests_add(tsdn,
  769. &arena->stats, i, cache_bin->tstats.nrequests);
  770. }
  771. cache_bin->tstats.nrequests = 0;
  772. }
  773. }
  774. static bool
  775. tcaches_create_prep(tsd_t *tsd, base_t *base) {
  776. bool err;
  777. malloc_mutex_assert_owner(tsd_tsdn(tsd), &tcaches_mtx);
  778. if (tcaches == NULL) {
  779. tcaches = base_alloc(tsd_tsdn(tsd), base,
  780. sizeof(tcache_t *) * (MALLOCX_TCACHE_MAX+1), CACHELINE);
  781. if (tcaches == NULL) {
  782. err = true;
  783. goto label_return;
  784. }
  785. }
  786. if (tcaches_avail == NULL && tcaches_past > MALLOCX_TCACHE_MAX) {
  787. err = true;
  788. goto label_return;
  789. }
  790. err = false;
  791. label_return:
  792. return err;
  793. }
  794. bool
  795. tcaches_create(tsd_t *tsd, base_t *base, unsigned *r_ind) {
  796. witness_assert_depth(tsdn_witness_tsdp_get(tsd_tsdn(tsd)), 0);
  797. bool err;
  798. malloc_mutex_lock(tsd_tsdn(tsd), &tcaches_mtx);
  799. if (tcaches_create_prep(tsd, base)) {
  800. err = true;
  801. goto label_return;
  802. }
  803. tcache_t *tcache = tcache_create_explicit(tsd);
  804. if (tcache == NULL) {
  805. err = true;
  806. goto label_return;
  807. }
  808. tcaches_t *elm;
  809. if (tcaches_avail != NULL) {
  810. elm = tcaches_avail;
  811. tcaches_avail = tcaches_avail->next;
  812. elm->tcache = tcache;
  813. *r_ind = (unsigned)(elm - tcaches);
  814. } else {
  815. elm = &tcaches[tcaches_past];
  816. elm->tcache = tcache;
  817. *r_ind = tcaches_past;
  818. tcaches_past++;
  819. }
  820. err = false;
  821. label_return:
  822. malloc_mutex_unlock(tsd_tsdn(tsd), &tcaches_mtx);
  823. witness_assert_depth(tsdn_witness_tsdp_get(tsd_tsdn(tsd)), 0);
  824. return err;
  825. }
  826. static tcache_t *
  827. tcaches_elm_remove(tsd_t *tsd, tcaches_t *elm, bool allow_reinit) {
  828. malloc_mutex_assert_owner(tsd_tsdn(tsd), &tcaches_mtx);
  829. if (elm->tcache == NULL) {
  830. return NULL;
  831. }
  832. tcache_t *tcache = elm->tcache;
  833. if (allow_reinit) {
  834. elm->tcache = TCACHES_ELM_NEED_REINIT;
  835. } else {
  836. elm->tcache = NULL;
  837. }
  838. if (tcache == TCACHES_ELM_NEED_REINIT) {
  839. return NULL;
  840. }
  841. return tcache;
  842. }
  843. void
  844. tcaches_flush(tsd_t *tsd, unsigned ind) {
  845. malloc_mutex_lock(tsd_tsdn(tsd), &tcaches_mtx);
  846. tcache_t *tcache = tcaches_elm_remove(tsd, &tcaches[ind], true);
  847. malloc_mutex_unlock(tsd_tsdn(tsd), &tcaches_mtx);
  848. if (tcache != NULL) {
  849. /* Destroy the tcache; recreate in tcaches_get() if needed. */
  850. tcache_destroy(tsd, tcache, false);
  851. }
  852. }
  853. void
  854. tcaches_destroy(tsd_t *tsd, unsigned ind) {
  855. malloc_mutex_lock(tsd_tsdn(tsd), &tcaches_mtx);
  856. tcaches_t *elm = &tcaches[ind];
  857. tcache_t *tcache = tcaches_elm_remove(tsd, elm, false);
  858. elm->next = tcaches_avail;
  859. tcaches_avail = elm;
  860. malloc_mutex_unlock(tsd_tsdn(tsd), &tcaches_mtx);
  861. if (tcache != NULL) {
  862. tcache_destroy(tsd, tcache, false);
  863. }
  864. }
  865. static unsigned
  866. tcache_ncached_max_compute(szind_t szind) {
  867. if (szind >= SC_NBINS) {
  868. assert(szind < nhbins);
  869. return opt_tcache_nslots_large;
  870. }
  871. unsigned slab_nregs = bin_infos[szind].nregs;
  872. /* We may modify these values; start with the opt versions. */
  873. unsigned nslots_small_min = opt_tcache_nslots_small_min;
  874. unsigned nslots_small_max = opt_tcache_nslots_small_max;
  875. /*
  876. * Clamp values to meet our constraints -- even, nonzero, min < max, and
  877. * suitable for a cache bin size.
  878. */
  879. if (opt_tcache_nslots_small_max > CACHE_BIN_NCACHED_MAX) {
  880. nslots_small_max = CACHE_BIN_NCACHED_MAX;
  881. }
  882. if (nslots_small_min % 2 != 0) {
  883. nslots_small_min++;
  884. }
  885. if (nslots_small_max % 2 != 0) {
  886. nslots_small_max--;
  887. }
  888. if (nslots_small_min < 2) {
  889. nslots_small_min = 2;
  890. }
  891. if (nslots_small_max < 2) {
  892. nslots_small_max = 2;
  893. }
  894. if (nslots_small_min > nslots_small_max) {
  895. nslots_small_min = nslots_small_max;
  896. }
  897. unsigned candidate;
  898. if (opt_lg_tcache_nslots_mul < 0) {
  899. candidate = slab_nregs >> (-opt_lg_tcache_nslots_mul);
  900. } else {
  901. candidate = slab_nregs << opt_lg_tcache_nslots_mul;
  902. }
  903. if (candidate % 2 != 0) {
  904. /*
  905. * We need the candidate size to be even -- we assume that we
  906. * can divide by two and get a positive number (e.g. when
  907. * flushing).
  908. */
  909. ++candidate;
  910. }
  911. if (candidate <= nslots_small_min) {
  912. return nslots_small_min;
  913. } else if (candidate <= nslots_small_max) {
  914. return candidate;
  915. } else {
  916. return nslots_small_max;
  917. }
  918. }
  919. bool
  920. tcache_boot(tsdn_t *tsdn, base_t *base) {
  921. tcache_maxclass = sz_s2u(opt_tcache_max);
  922. assert(tcache_maxclass <= TCACHE_MAXCLASS_LIMIT);
  923. nhbins = sz_size2index(tcache_maxclass) + 1;
  924. if (malloc_mutex_init(&tcaches_mtx, "tcaches", WITNESS_RANK_TCACHES,
  925. malloc_mutex_rank_exclusive)) {
  926. return true;
  927. }
  928. /* Initialize tcache_bin_info. See comments in tcache_init(). */
  929. unsigned n_reserved_bins = nhbins < SC_NBINS ? SC_NBINS : nhbins;
  930. size_t size = n_reserved_bins * sizeof(cache_bin_info_t);
  931. tcache_bin_info = (cache_bin_info_t *)base_alloc(tsdn, base, size,
  932. CACHELINE);
  933. if (tcache_bin_info == NULL) {
  934. return true;
  935. }
  936. for (szind_t i = 0; i < nhbins; i++) {
  937. unsigned ncached_max = tcache_ncached_max_compute(i);
  938. cache_bin_info_init(&tcache_bin_info[i], ncached_max);
  939. }
  940. for (szind_t i = nhbins; i < SC_NBINS; i++) {
  941. /* Disabled small bins. */
  942. cache_bin_info_init(&tcache_bin_info[i], 0);
  943. assert(tcache_small_bin_disabled(i, NULL));
  944. }
  945. cache_bin_info_compute_alloc(tcache_bin_info, nhbins,
  946. &tcache_bin_alloc_size, &tcache_bin_alloc_alignment);
  947. return false;
  948. }
  949. void
  950. tcache_prefork(tsdn_t *tsdn) {
  951. malloc_mutex_prefork(tsdn, &tcaches_mtx);
  952. }
  953. void
  954. tcache_postfork_parent(tsdn_t *tsdn) {
  955. malloc_mutex_postfork_parent(tsdn, &tcaches_mtx);
  956. }
  957. void
  958. tcache_postfork_child(tsdn_t *tsdn) {
  959. malloc_mutex_postfork_child(tsdn, &tcaches_mtx);
  960. }
  961. void tcache_assert_initialized(tcache_t *tcache) {
  962. assert(!cache_bin_still_zero_initialized(&tcache->bins[0]));
  963. }