PageRenderTime 74ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/Source/JavaScriptCore/wtf/FastMalloc.cpp

https://bitbucket.org/slukk/atsmp_4.2-external_webkit
C++ | 4626 lines | 3257 code | 645 blank | 724 comment | 544 complexity | 0acf3c415fe5f364536a7e2c9c2efcf3 MD5 | raw file
Possible License(s): LGPL-2.0, BSD-3-Clause, LGPL-2.1
  1. // Copyright (c) 2005, 2007, Google Inc.
  2. // All rights reserved.
  3. // Copyright (C) 2005, 2006, 2007, 2008, 2009, 2011 Apple Inc. All rights reserved.
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // ---
  31. // Author: Sanjay Ghemawat <opensource@google.com>
  32. //
  33. // A malloc that uses a per-thread cache to satisfy small malloc requests.
  34. // (The time for malloc/free of a small object drops from 300 ns to 50 ns.)
  35. //
  36. // See doc/tcmalloc.html for a high-level
  37. // description of how this malloc works.
  38. //
  39. // SYNCHRONIZATION
  40. // 1. The thread-specific lists are accessed without acquiring any locks.
  41. // This is safe because each such list is only accessed by one thread.
  42. // 2. We have a lock per central free-list, and hold it while manipulating
  43. // the central free list for a particular size.
  44. // 3. The central page allocator is protected by "pageheap_lock".
  45. // 4. The pagemap (which maps from page-number to descriptor),
  46. // can be read without holding any locks, and written while holding
  47. // the "pageheap_lock".
  48. // 5. To improve performance, a subset of the information one can get
  49. // from the pagemap is cached in a data structure, pagemap_cache_,
  50. // that atomically reads and writes its entries. This cache can be
  51. // read and written without locking.
  52. //
  53. // This multi-threaded access to the pagemap is safe for fairly
  54. // subtle reasons. We basically assume that when an object X is
  55. // allocated by thread A and deallocated by thread B, there must
  56. // have been appropriate synchronization in the handoff of object
  57. // X from thread A to thread B. The same logic applies to pagemap_cache_.
  58. //
  59. // THE PAGEID-TO-SIZECLASS CACHE
  60. // Hot PageID-to-sizeclass mappings are held by pagemap_cache_. If this cache
  61. // returns 0 for a particular PageID then that means "no information," not that
  62. // the sizeclass is 0. The cache may have stale information for pages that do
  63. // not hold the beginning of any free()'able object. Staleness is eliminated
  64. // in Populate() for pages with sizeclass > 0 objects, and in do_malloc() and
  65. // do_memalign() for all other relevant pages.
  66. //
  67. // TODO: Bias reclamation to larger addresses
  68. // TODO: implement mallinfo/mallopt
  69. // TODO: Better testing
  70. //
  71. // 9/28/2003 (new page-level allocator replaces ptmalloc2):
  72. // * malloc/free of small objects goes from ~300 ns to ~50 ns.
  73. // * allocation of a reasonably complicated struct
  74. // goes from about 1100 ns to about 300 ns.
  75. #include "config.h"
  76. #include "FastMalloc.h"
  77. #include "Assertions.h"
  78. #include <limits>
  79. #if ENABLE(JSC_MULTIPLE_THREADS)
  80. #include <pthread.h>
  81. #endif
  82. #include <wtf/StdLibExtras.h>
  83. #ifndef NO_TCMALLOC_SAMPLES
  84. #ifdef WTF_CHANGES
  85. #define NO_TCMALLOC_SAMPLES
  86. #endif
  87. #endif
  88. #if !(defined(USE_SYSTEM_MALLOC) && USE_SYSTEM_MALLOC) && defined(NDEBUG)
  89. #define FORCE_SYSTEM_MALLOC 0
  90. #else
  91. #define FORCE_SYSTEM_MALLOC 1
  92. #endif
  93. // Use a background thread to periodically scavenge memory to release back to the system
  94. // https://bugs.webkit.org/show_bug.cgi?id=27900: don't turn this on for Tiger until we have figured out why it caused a crash.
  95. #if defined(BUILDING_ON_TIGER)
  96. #define USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY 0
  97. #else
  98. #define USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY 1
  99. #endif
  100. #ifndef NDEBUG
  101. namespace WTF {
  102. #if ENABLE(JSC_MULTIPLE_THREADS)
  103. static pthread_key_t isForbiddenKey;
  104. static pthread_once_t isForbiddenKeyOnce = PTHREAD_ONCE_INIT;
  105. static void initializeIsForbiddenKey()
  106. {
  107. pthread_key_create(&isForbiddenKey, 0);
  108. }
  109. #if !ASSERT_DISABLED
  110. static bool isForbidden()
  111. {
  112. pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
  113. return !!pthread_getspecific(isForbiddenKey);
  114. }
  115. #endif
  116. void fastMallocForbid()
  117. {
  118. pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
  119. pthread_setspecific(isForbiddenKey, &isForbiddenKey);
  120. }
  121. void fastMallocAllow()
  122. {
  123. pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
  124. pthread_setspecific(isForbiddenKey, 0);
  125. }
  126. #else
  127. static bool staticIsForbidden;
  128. static bool isForbidden()
  129. {
  130. return staticIsForbidden;
  131. }
  132. void fastMallocForbid()
  133. {
  134. staticIsForbidden = true;
  135. }
  136. void fastMallocAllow()
  137. {
  138. staticIsForbidden = false;
  139. }
  140. #endif // ENABLE(JSC_MULTIPLE_THREADS)
  141. } // namespace WTF
  142. #endif // NDEBUG
  143. #include <string.h>
  144. namespace WTF {
  145. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  146. namespace Internal {
  147. void fastMallocMatchFailed(void*)
  148. {
  149. CRASH();
  150. }
  151. } // namespace Internal
  152. #endif
  153. void* fastZeroedMalloc(size_t n)
  154. {
  155. void* result = fastMalloc(n);
  156. memset(result, 0, n);
  157. return result;
  158. }
  159. char* fastStrDup(const char* src)
  160. {
  161. size_t len = strlen(src) + 1;
  162. char* dup = static_cast<char*>(fastMalloc(len));
  163. memcpy(dup, src, len);
  164. return dup;
  165. }
  166. TryMallocReturnValue tryFastZeroedMalloc(size_t n)
  167. {
  168. void* result;
  169. if (!tryFastMalloc(n).getValue(result))
  170. return 0;
  171. memset(result, 0, n);
  172. return result;
  173. }
  174. } // namespace WTF
  175. #if FORCE_SYSTEM_MALLOC
  176. #if PLATFORM(BREWMP)
  177. #include "brew/SystemMallocBrew.h"
  178. #endif
  179. #if OS(DARWIN)
  180. #include <malloc/malloc.h>
  181. #elif OS(WINDOWS)
  182. #include <malloc.h>
  183. #endif
  184. namespace WTF {
  185. TryMallocReturnValue tryFastMalloc(size_t n)
  186. {
  187. ASSERT(!isForbidden());
  188. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  189. if (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= n) // If overflow would occur...
  190. return 0;
  191. void* result = malloc(n + sizeof(AllocAlignmentInteger));
  192. if (!result)
  193. return 0;
  194. *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
  195. result = static_cast<AllocAlignmentInteger*>(result) + 1;
  196. return result;
  197. #else
  198. return malloc(n);
  199. #endif
  200. }
  201. void* fastMalloc(size_t n)
  202. {
  203. ASSERT(!isForbidden());
  204. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  205. TryMallocReturnValue returnValue = tryFastMalloc(n);
  206. void* result;
  207. if (!returnValue.getValue(result))
  208. CRASH();
  209. #else
  210. void* result = malloc(n);
  211. #endif
  212. if (!result) {
  213. #if PLATFORM(BREWMP)
  214. // The behavior of malloc(0) is implementation defined.
  215. // To make sure that fastMalloc never returns 0, retry with fastMalloc(1).
  216. if (!n)
  217. return fastMalloc(1);
  218. #endif
  219. CRASH();
  220. }
  221. return result;
  222. }
  223. TryMallocReturnValue tryFastCalloc(size_t n_elements, size_t element_size)
  224. {
  225. ASSERT(!isForbidden());
  226. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  227. size_t totalBytes = n_elements * element_size;
  228. if (n_elements > 1 && element_size && (totalBytes / element_size) != n_elements || (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= totalBytes))
  229. return 0;
  230. totalBytes += sizeof(AllocAlignmentInteger);
  231. void* result = malloc(totalBytes);
  232. if (!result)
  233. return 0;
  234. memset(result, 0, totalBytes);
  235. *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
  236. result = static_cast<AllocAlignmentInteger*>(result) + 1;
  237. return result;
  238. #else
  239. return calloc(n_elements, element_size);
  240. #endif
  241. }
  242. void* fastCalloc(size_t n_elements, size_t element_size)
  243. {
  244. ASSERT(!isForbidden());
  245. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  246. TryMallocReturnValue returnValue = tryFastCalloc(n_elements, element_size);
  247. void* result;
  248. if (!returnValue.getValue(result))
  249. CRASH();
  250. #else
  251. void* result = calloc(n_elements, element_size);
  252. #endif
  253. if (!result) {
  254. #if PLATFORM(BREWMP)
  255. // If either n_elements or element_size is 0, the behavior of calloc is implementation defined.
  256. // To make sure that fastCalloc never returns 0, retry with fastCalloc(1, 1).
  257. if (!n_elements || !element_size)
  258. return fastCalloc(1, 1);
  259. #endif
  260. CRASH();
  261. }
  262. return result;
  263. }
  264. void fastFree(void* p)
  265. {
  266. ASSERT(!isForbidden());
  267. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  268. if (!p)
  269. return;
  270. AllocAlignmentInteger* header = Internal::fastMallocMatchValidationValue(p);
  271. if (*header != Internal::AllocTypeMalloc)
  272. Internal::fastMallocMatchFailed(p);
  273. free(header);
  274. #else
  275. free(p);
  276. #endif
  277. }
  278. TryMallocReturnValue tryFastRealloc(void* p, size_t n)
  279. {
  280. ASSERT(!isForbidden());
  281. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  282. if (p) {
  283. if (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= n) // If overflow would occur...
  284. return 0;
  285. AllocAlignmentInteger* header = Internal::fastMallocMatchValidationValue(p);
  286. if (*header != Internal::AllocTypeMalloc)
  287. Internal::fastMallocMatchFailed(p);
  288. void* result = realloc(header, n + sizeof(AllocAlignmentInteger));
  289. if (!result)
  290. return 0;
  291. // This should not be needed because the value is already there:
  292. // *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
  293. result = static_cast<AllocAlignmentInteger*>(result) + 1;
  294. return result;
  295. } else {
  296. return fastMalloc(n);
  297. }
  298. #else
  299. return realloc(p, n);
  300. #endif
  301. }
  302. void* fastRealloc(void* p, size_t n)
  303. {
  304. ASSERT(!isForbidden());
  305. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  306. TryMallocReturnValue returnValue = tryFastRealloc(p, n);
  307. void* result;
  308. if (!returnValue.getValue(result))
  309. CRASH();
  310. #else
  311. void* result = realloc(p, n);
  312. #endif
  313. if (!result)
  314. CRASH();
  315. return result;
  316. }
  317. void releaseFastMallocFreeMemory() { }
  318. FastMallocStatistics fastMallocStatistics()
  319. {
  320. FastMallocStatistics statistics = { 0, 0, 0 };
  321. return statistics;
  322. }
  323. size_t fastMallocSize(const void* p)
  324. {
  325. #if OS(DARWIN)
  326. return malloc_size(p);
  327. #elif OS(WINDOWS) && !PLATFORM(BREWMP)
  328. // Brew MP uses its own memory allocator, so _msize does not work on the Brew MP simulator.
  329. return _msize(const_cast<void*>(p));
  330. #else
  331. return 1;
  332. #endif
  333. }
  334. } // namespace WTF
  335. #if OS(DARWIN)
  336. // This symbol is present in the JavaScriptCore exports file even when FastMalloc is disabled.
  337. // It will never be used in this case, so it's type and value are less interesting than its presence.
  338. extern "C" const int jscore_fastmalloc_introspection = 0;
  339. #endif
  340. #else // FORCE_SYSTEM_MALLOC
  341. #if HAVE(STDINT_H)
  342. #include <stdint.h>
  343. #elif HAVE(INTTYPES_H)
  344. #include <inttypes.h>
  345. #else
  346. #include <sys/types.h>
  347. #endif
  348. #include "AlwaysInline.h"
  349. #include "Assertions.h"
  350. #include "TCPackedCache.h"
  351. #include "TCPageMap.h"
  352. #include "TCSpinLock.h"
  353. #include "TCSystemAlloc.h"
  354. #include <algorithm>
  355. #include <limits>
  356. #include <pthread.h>
  357. #include <stdarg.h>
  358. #include <stddef.h>
  359. #include <stdio.h>
  360. #if HAVE(ERRNO_H)
  361. #include <errno.h>
  362. #endif
  363. #if OS(UNIX)
  364. #include <unistd.h>
  365. #endif
  366. #if OS(WINDOWS)
  367. #ifndef WIN32_LEAN_AND_MEAN
  368. #define WIN32_LEAN_AND_MEAN
  369. #endif
  370. #include <windows.h>
  371. #endif
  372. #ifdef WTF_CHANGES
  373. #if OS(DARWIN)
  374. #include "MallocZoneSupport.h"
  375. #include <wtf/HashSet.h>
  376. #include <wtf/Vector.h>
  377. #endif
  378. #if HAVE(HEADER_DETECTION_H)
  379. #include "HeaderDetection.h"
  380. #endif
  381. #if HAVE(DISPATCH_H)
  382. #include <dispatch/dispatch.h>
  383. #endif
  384. #if HAVE(PTHREAD_MACHDEP_H)
  385. #include <System/pthread_machdep.h>
  386. #if defined(__PTK_FRAMEWORK_JAVASCRIPTCORE_KEY0)
  387. #define WTF_USE_PTHREAD_GETSPECIFIC_DIRECT 1
  388. #endif
  389. #endif
  390. #ifndef PRIuS
  391. #define PRIuS "zu"
  392. #endif
  393. // Calling pthread_getspecific through a global function pointer is faster than a normal
  394. // call to the function on Mac OS X, and it's used in performance-critical code. So we
  395. // use a function pointer. But that's not necessarily faster on other platforms, and we had
  396. // problems with this technique on Windows, so we'll do this only on Mac OS X.
  397. #if OS(DARWIN)
  398. #if !USE(PTHREAD_GETSPECIFIC_DIRECT)
  399. static void* (*pthread_getspecific_function_pointer)(pthread_key_t) = pthread_getspecific;
  400. #define pthread_getspecific(key) pthread_getspecific_function_pointer(key)
  401. #else
  402. #define pthread_getspecific(key) _pthread_getspecific_direct(key)
  403. #define pthread_setspecific(key, val) _pthread_setspecific_direct(key, (val))
  404. #endif
  405. #endif
  406. #define DEFINE_VARIABLE(type, name, value, meaning) \
  407. namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead { \
  408. type FLAGS_##name(value); \
  409. char FLAGS_no##name; \
  410. } \
  411. using FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead::FLAGS_##name
  412. #define DEFINE_int64(name, value, meaning) \
  413. DEFINE_VARIABLE(int64_t, name, value, meaning)
  414. #define DEFINE_double(name, value, meaning) \
  415. DEFINE_VARIABLE(double, name, value, meaning)
  416. namespace WTF {
  417. #define malloc fastMalloc
  418. #define calloc fastCalloc
  419. #define free fastFree
  420. #define realloc fastRealloc
  421. #define MESSAGE LOG_ERROR
  422. #define CHECK_CONDITION ASSERT
  423. #if OS(DARWIN)
  424. struct Span;
  425. class TCMalloc_Central_FreeListPadded;
  426. class TCMalloc_PageHeap;
  427. class TCMalloc_ThreadCache;
  428. template <typename T> class PageHeapAllocator;
  429. class FastMallocZone {
  430. public:
  431. static void init();
  432. static kern_return_t enumerate(task_t, void*, unsigned typeMmask, vm_address_t zoneAddress, memory_reader_t, vm_range_recorder_t);
  433. static size_t goodSize(malloc_zone_t*, size_t size) { return size; }
  434. static boolean_t check(malloc_zone_t*) { return true; }
  435. static void print(malloc_zone_t*, boolean_t) { }
  436. static void log(malloc_zone_t*, void*) { }
  437. static void forceLock(malloc_zone_t*) { }
  438. static void forceUnlock(malloc_zone_t*) { }
  439. static void statistics(malloc_zone_t*, malloc_statistics_t* stats) { memset(stats, 0, sizeof(malloc_statistics_t)); }
  440. private:
  441. FastMallocZone(TCMalloc_PageHeap*, TCMalloc_ThreadCache**, TCMalloc_Central_FreeListPadded*, PageHeapAllocator<Span>*, PageHeapAllocator<TCMalloc_ThreadCache>*);
  442. static size_t size(malloc_zone_t*, const void*);
  443. static void* zoneMalloc(malloc_zone_t*, size_t);
  444. static void* zoneCalloc(malloc_zone_t*, size_t numItems, size_t size);
  445. static void zoneFree(malloc_zone_t*, void*);
  446. static void* zoneRealloc(malloc_zone_t*, void*, size_t);
  447. static void* zoneValloc(malloc_zone_t*, size_t) { LOG_ERROR("valloc is not supported"); return 0; }
  448. static void zoneDestroy(malloc_zone_t*) { }
  449. malloc_zone_t m_zone;
  450. TCMalloc_PageHeap* m_pageHeap;
  451. TCMalloc_ThreadCache** m_threadHeaps;
  452. TCMalloc_Central_FreeListPadded* m_centralCaches;
  453. PageHeapAllocator<Span>* m_spanAllocator;
  454. PageHeapAllocator<TCMalloc_ThreadCache>* m_pageHeapAllocator;
  455. };
  456. #endif
  457. #endif
  458. #ifndef WTF_CHANGES
  459. // This #ifdef should almost never be set. Set NO_TCMALLOC_SAMPLES if
  460. // you're porting to a system where you really can't get a stacktrace.
  461. #ifdef NO_TCMALLOC_SAMPLES
  462. // We use #define so code compiles even if you #include stacktrace.h somehow.
  463. # define GetStackTrace(stack, depth, skip) (0)
  464. #else
  465. # include <google/stacktrace.h>
  466. #endif
  467. #endif
  468. // Even if we have support for thread-local storage in the compiler
  469. // and linker, the OS may not support it. We need to check that at
  470. // runtime. Right now, we have to keep a manual set of "bad" OSes.
  471. #if defined(HAVE_TLS)
  472. static bool kernel_supports_tls = false; // be conservative
  473. static inline bool KernelSupportsTLS() {
  474. return kernel_supports_tls;
  475. }
  476. # if !HAVE_DECL_UNAME // if too old for uname, probably too old for TLS
  477. static void CheckIfKernelSupportsTLS() {
  478. kernel_supports_tls = false;
  479. }
  480. # else
  481. # include <sys/utsname.h> // DECL_UNAME checked for <sys/utsname.h> too
  482. static void CheckIfKernelSupportsTLS() {
  483. struct utsname buf;
  484. if (uname(&buf) != 0) { // should be impossible
  485. MESSAGE("uname failed assuming no TLS support (errno=%d)\n", errno);
  486. kernel_supports_tls = false;
  487. } else if (strcasecmp(buf.sysname, "linux") == 0) {
  488. // The linux case: the first kernel to support TLS was 2.6.0
  489. if (buf.release[0] < '2' && buf.release[1] == '.') // 0.x or 1.x
  490. kernel_supports_tls = false;
  491. else if (buf.release[0] == '2' && buf.release[1] == '.' &&
  492. buf.release[2] >= '0' && buf.release[2] < '6' &&
  493. buf.release[3] == '.') // 2.0 - 2.5
  494. kernel_supports_tls = false;
  495. else
  496. kernel_supports_tls = true;
  497. } else { // some other kernel, we'll be optimisitic
  498. kernel_supports_tls = true;
  499. }
  500. // TODO(csilvers): VLOG(1) the tls status once we support RAW_VLOG
  501. }
  502. # endif // HAVE_DECL_UNAME
  503. #endif // HAVE_TLS
  504. // __THROW is defined in glibc systems. It means, counter-intuitively,
  505. // "This function will never throw an exception." It's an optional
  506. // optimization tool, but we may need to use it to match glibc prototypes.
  507. #ifndef __THROW // I guess we're not on a glibc system
  508. # define __THROW // __THROW is just an optimization, so ok to make it ""
  509. #endif
  510. //-------------------------------------------------------------------
  511. // Configuration
  512. //-------------------------------------------------------------------
  513. // Not all possible combinations of the following parameters make
  514. // sense. In particular, if kMaxSize increases, you may have to
  515. // increase kNumClasses as well.
  516. static const size_t kPageShift = 12;
  517. static const size_t kPageSize = 1 << kPageShift;
  518. static const size_t kMaxSize = 8u * kPageSize;
  519. static const size_t kAlignShift = 3;
  520. static const size_t kAlignment = 1 << kAlignShift;
  521. static const size_t kNumClasses = 68;
  522. // Allocates a big block of memory for the pagemap once we reach more than
  523. // 128MB
  524. static const size_t kPageMapBigAllocationThreshold = 128 << 20;
  525. // Minimum number of pages to fetch from system at a time. Must be
  526. // significantly bigger than kPageSize to amortize system-call
  527. // overhead, and also to reduce external fragementation. Also, we
  528. // should keep this value big because various incarnations of Linux
  529. // have small limits on the number of mmap() regions per
  530. // address-space.
  531. static const size_t kMinSystemAlloc = 1 << (20 - kPageShift);
  532. // Number of objects to move between a per-thread list and a central
  533. // list in one shot. We want this to be not too small so we can
  534. // amortize the lock overhead for accessing the central list. Making
  535. // it too big may temporarily cause unnecessary memory wastage in the
  536. // per-thread free list until the scavenger cleans up the list.
  537. static int num_objects_to_move[kNumClasses];
  538. // Maximum length we allow a per-thread free-list to have before we
  539. // move objects from it into the corresponding central free-list. We
  540. // want this big to avoid locking the central free-list too often. It
  541. // should not hurt to make this list somewhat big because the
  542. // scavenging code will shrink it down when its contents are not in use.
  543. static const int kMaxFreeListLength = 256;
  544. // Lower and upper bounds on the per-thread cache sizes
  545. static const size_t kMinThreadCacheSize = kMaxSize * 2;
  546. static const size_t kMaxThreadCacheSize = 2 << 20;
  547. // Default bound on the total amount of thread caches
  548. static const size_t kDefaultOverallThreadCacheSize = 16 << 20;
  549. // For all span-lengths < kMaxPages we keep an exact-size list.
  550. // REQUIRED: kMaxPages >= kMinSystemAlloc;
  551. static const size_t kMaxPages = kMinSystemAlloc;
  552. /* The smallest prime > 2^n */
  553. static int primes_list[] = {
  554. // Small values might cause high rates of sampling
  555. // and hence commented out.
  556. // 2, 5, 11, 17, 37, 67, 131, 257,
  557. // 521, 1031, 2053, 4099, 8209, 16411,
  558. 32771, 65537, 131101, 262147, 524309, 1048583,
  559. 2097169, 4194319, 8388617, 16777259, 33554467 };
  560. // Twice the approximate gap between sampling actions.
  561. // I.e., we take one sample approximately once every
  562. // tcmalloc_sample_parameter/2
  563. // bytes of allocation, i.e., ~ once every 128KB.
  564. // Must be a prime number.
  565. #ifdef NO_TCMALLOC_SAMPLES
  566. DEFINE_int64(tcmalloc_sample_parameter, 0,
  567. "Unused: code is compiled with NO_TCMALLOC_SAMPLES");
  568. static size_t sample_period = 0;
  569. #else
  570. DEFINE_int64(tcmalloc_sample_parameter, 262147,
  571. "Twice the approximate gap between sampling actions."
  572. " Must be a prime number. Otherwise will be rounded up to a "
  573. " larger prime number");
  574. static size_t sample_period = 262147;
  575. #endif
  576. // Protects sample_period above
  577. static SpinLock sample_period_lock = SPINLOCK_INITIALIZER;
  578. // Parameters for controlling how fast memory is returned to the OS.
  579. DEFINE_double(tcmalloc_release_rate, 1,
  580. "Rate at which we release unused memory to the system. "
  581. "Zero means we never release memory back to the system. "
  582. "Increase this flag to return memory faster; decrease it "
  583. "to return memory slower. Reasonable rates are in the "
  584. "range [0,10]");
  585. //-------------------------------------------------------------------
  586. // Mapping from size to size_class and vice versa
  587. //-------------------------------------------------------------------
  588. // Sizes <= 1024 have an alignment >= 8. So for such sizes we have an
  589. // array indexed by ceil(size/8). Sizes > 1024 have an alignment >= 128.
  590. // So for these larger sizes we have an array indexed by ceil(size/128).
  591. //
  592. // We flatten both logical arrays into one physical array and use
  593. // arithmetic to compute an appropriate index. The constants used by
  594. // ClassIndex() were selected to make the flattening work.
  595. //
  596. // Examples:
  597. // Size Expression Index
  598. // -------------------------------------------------------
  599. // 0 (0 + 7) / 8 0
  600. // 1 (1 + 7) / 8 1
  601. // ...
  602. // 1024 (1024 + 7) / 8 128
  603. // 1025 (1025 + 127 + (120<<7)) / 128 129
  604. // ...
  605. // 32768 (32768 + 127 + (120<<7)) / 128 376
  606. static const size_t kMaxSmallSize = 1024;
  607. static const int shift_amount[2] = { 3, 7 }; // For divides by 8 or 128
  608. static const int add_amount[2] = { 7, 127 + (120 << 7) };
  609. static unsigned char class_array[377];
  610. // Compute index of the class_array[] entry for a given size
  611. static inline int ClassIndex(size_t s) {
  612. const int i = (s > kMaxSmallSize);
  613. return static_cast<int>((s + add_amount[i]) >> shift_amount[i]);
  614. }
  615. // Mapping from size class to max size storable in that class
  616. static size_t class_to_size[kNumClasses];
  617. // Mapping from size class to number of pages to allocate at a time
  618. static size_t class_to_pages[kNumClasses];
  619. // TransferCache is used to cache transfers of num_objects_to_move[size_class]
  620. // back and forth between thread caches and the central cache for a given size
  621. // class.
  622. struct TCEntry {
  623. void *head; // Head of chain of objects.
  624. void *tail; // Tail of chain of objects.
  625. };
  626. // A central cache freelist can have anywhere from 0 to kNumTransferEntries
  627. // slots to put link list chains into. To keep memory usage bounded the total
  628. // number of TCEntries across size classes is fixed. Currently each size
  629. // class is initially given one TCEntry which also means that the maximum any
  630. // one class can have is kNumClasses.
  631. static const int kNumTransferEntries = kNumClasses;
  632. // Note: the following only works for "n"s that fit in 32-bits, but
  633. // that is fine since we only use it for small sizes.
  634. static inline int LgFloor(size_t n) {
  635. int log = 0;
  636. for (int i = 4; i >= 0; --i) {
  637. int shift = (1 << i);
  638. size_t x = n >> shift;
  639. if (x != 0) {
  640. n = x;
  641. log += shift;
  642. }
  643. }
  644. ASSERT(n == 1);
  645. return log;
  646. }
  647. // Some very basic linked list functions for dealing with using void * as
  648. // storage.
  649. static inline void *SLL_Next(void *t) {
  650. return *(reinterpret_cast<void**>(t));
  651. }
  652. static inline void SLL_SetNext(void *t, void *n) {
  653. *(reinterpret_cast<void**>(t)) = n;
  654. }
  655. static inline void SLL_Push(void **list, void *element) {
  656. SLL_SetNext(element, *list);
  657. *list = element;
  658. }
  659. static inline void *SLL_Pop(void **list) {
  660. void *result = *list;
  661. *list = SLL_Next(*list);
  662. return result;
  663. }
  664. // Remove N elements from a linked list to which head points. head will be
  665. // modified to point to the new head. start and end will point to the first
  666. // and last nodes of the range. Note that end will point to NULL after this
  667. // function is called.
  668. static inline void SLL_PopRange(void **head, int N, void **start, void **end) {
  669. if (N == 0) {
  670. *start = NULL;
  671. *end = NULL;
  672. return;
  673. }
  674. void *tmp = *head;
  675. for (int i = 1; i < N; ++i) {
  676. tmp = SLL_Next(tmp);
  677. }
  678. *start = *head;
  679. *end = tmp;
  680. *head = SLL_Next(tmp);
  681. // Unlink range from list.
  682. SLL_SetNext(tmp, NULL);
  683. }
  684. static inline void SLL_PushRange(void **head, void *start, void *end) {
  685. if (!start) return;
  686. SLL_SetNext(end, *head);
  687. *head = start;
  688. }
  689. static inline size_t SLL_Size(void *head) {
  690. int count = 0;
  691. while (head) {
  692. count++;
  693. head = SLL_Next(head);
  694. }
  695. return count;
  696. }
  697. // Setup helper functions.
  698. static ALWAYS_INLINE size_t SizeClass(size_t size) {
  699. return class_array[ClassIndex(size)];
  700. }
  701. // Get the byte-size for a specified class
  702. static ALWAYS_INLINE size_t ByteSizeForClass(size_t cl) {
  703. return class_to_size[cl];
  704. }
  705. static int NumMoveSize(size_t size) {
  706. if (size == 0) return 0;
  707. // Use approx 64k transfers between thread and central caches.
  708. int num = static_cast<int>(64.0 * 1024.0 / size);
  709. if (num < 2) num = 2;
  710. // Clamp well below kMaxFreeListLength to avoid ping pong between central
  711. // and thread caches.
  712. if (num > static_cast<int>(0.8 * kMaxFreeListLength))
  713. num = static_cast<int>(0.8 * kMaxFreeListLength);
  714. // Also, avoid bringing in too many objects into small object free
  715. // lists. There are lots of such lists, and if we allow each one to
  716. // fetch too many at a time, we end up having to scavenge too often
  717. // (especially when there are lots of threads and each thread gets a
  718. // small allowance for its thread cache).
  719. //
  720. // TODO: Make thread cache free list sizes dynamic so that we do not
  721. // have to equally divide a fixed resource amongst lots of threads.
  722. if (num > 32) num = 32;
  723. return num;
  724. }
  725. // Initialize the mapping arrays
  726. static void InitSizeClasses() {
  727. // Do some sanity checking on add_amount[]/shift_amount[]/class_array[]
  728. if (ClassIndex(0) < 0) {
  729. MESSAGE("Invalid class index %d for size 0\n", ClassIndex(0));
  730. CRASH();
  731. }
  732. if (static_cast<size_t>(ClassIndex(kMaxSize)) >= sizeof(class_array)) {
  733. MESSAGE("Invalid class index %d for kMaxSize\n", ClassIndex(kMaxSize));
  734. CRASH();
  735. }
  736. // Compute the size classes we want to use
  737. size_t sc = 1; // Next size class to assign
  738. unsigned char alignshift = kAlignShift;
  739. int last_lg = -1;
  740. for (size_t size = kAlignment; size <= kMaxSize; size += (1 << alignshift)) {
  741. int lg = LgFloor(size);
  742. if (lg > last_lg) {
  743. // Increase alignment every so often.
  744. //
  745. // Since we double the alignment every time size doubles and
  746. // size >= 128, this means that space wasted due to alignment is
  747. // at most 16/128 i.e., 12.5%. Plus we cap the alignment at 256
  748. // bytes, so the space wasted as a percentage starts falling for
  749. // sizes > 2K.
  750. if ((lg >= 7) && (alignshift < 8)) {
  751. alignshift++;
  752. }
  753. last_lg = lg;
  754. }
  755. // Allocate enough pages so leftover is less than 1/8 of total.
  756. // This bounds wasted space to at most 12.5%.
  757. size_t psize = kPageSize;
  758. while ((psize % size) > (psize >> 3)) {
  759. psize += kPageSize;
  760. }
  761. const size_t my_pages = psize >> kPageShift;
  762. if (sc > 1 && my_pages == class_to_pages[sc-1]) {
  763. // See if we can merge this into the previous class without
  764. // increasing the fragmentation of the previous class.
  765. const size_t my_objects = (my_pages << kPageShift) / size;
  766. const size_t prev_objects = (class_to_pages[sc-1] << kPageShift)
  767. / class_to_size[sc-1];
  768. if (my_objects == prev_objects) {
  769. // Adjust last class to include this size
  770. class_to_size[sc-1] = size;
  771. continue;
  772. }
  773. }
  774. // Add new class
  775. class_to_pages[sc] = my_pages;
  776. class_to_size[sc] = size;
  777. sc++;
  778. }
  779. if (sc != kNumClasses) {
  780. MESSAGE("wrong number of size classes: found %" PRIuS " instead of %d\n",
  781. sc, int(kNumClasses));
  782. CRASH();
  783. }
  784. // Initialize the mapping arrays
  785. int next_size = 0;
  786. for (unsigned char c = 1; c < kNumClasses; c++) {
  787. const size_t max_size_in_class = class_to_size[c];
  788. for (size_t s = next_size; s <= max_size_in_class; s += kAlignment) {
  789. class_array[ClassIndex(s)] = c;
  790. }
  791. next_size = static_cast<int>(max_size_in_class + kAlignment);
  792. }
  793. // Double-check sizes just to be safe
  794. for (size_t size = 0; size <= kMaxSize; size++) {
  795. const size_t sc = SizeClass(size);
  796. if (sc == 0) {
  797. MESSAGE("Bad size class %" PRIuS " for %" PRIuS "\n", sc, size);
  798. CRASH();
  799. }
  800. if (sc > 1 && size <= class_to_size[sc-1]) {
  801. MESSAGE("Allocating unnecessarily large class %" PRIuS " for %" PRIuS
  802. "\n", sc, size);
  803. CRASH();
  804. }
  805. if (sc >= kNumClasses) {
  806. MESSAGE("Bad size class %" PRIuS " for %" PRIuS "\n", sc, size);
  807. CRASH();
  808. }
  809. const size_t s = class_to_size[sc];
  810. if (size > s) {
  811. MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %" PRIuS ")\n", s, size, sc);
  812. CRASH();
  813. }
  814. if (s == 0) {
  815. MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %" PRIuS ")\n", s, size, sc);
  816. CRASH();
  817. }
  818. }
  819. // Initialize the num_objects_to_move array.
  820. for (size_t cl = 1; cl < kNumClasses; ++cl) {
  821. num_objects_to_move[cl] = NumMoveSize(ByteSizeForClass(cl));
  822. }
  823. #ifndef WTF_CHANGES
  824. if (false) {
  825. // Dump class sizes and maximum external wastage per size class
  826. for (size_t cl = 1; cl < kNumClasses; ++cl) {
  827. const int alloc_size = class_to_pages[cl] << kPageShift;
  828. const int alloc_objs = alloc_size / class_to_size[cl];
  829. const int min_used = (class_to_size[cl-1] + 1) * alloc_objs;
  830. const int max_waste = alloc_size - min_used;
  831. MESSAGE("SC %3d [ %8d .. %8d ] from %8d ; %2.0f%% maxwaste\n",
  832. int(cl),
  833. int(class_to_size[cl-1] + 1),
  834. int(class_to_size[cl]),
  835. int(class_to_pages[cl] << kPageShift),
  836. max_waste * 100.0 / alloc_size
  837. );
  838. }
  839. }
  840. #endif
  841. }
  842. // -------------------------------------------------------------------------
  843. // Simple allocator for objects of a specified type. External locking
  844. // is required before accessing one of these objects.
  845. // -------------------------------------------------------------------------
  846. // Metadata allocator -- keeps stats about how many bytes allocated
  847. static uint64_t metadata_system_bytes = 0;
  848. static void* MetaDataAlloc(size_t bytes) {
  849. void* result = TCMalloc_SystemAlloc(bytes, 0);
  850. if (result != NULL) {
  851. metadata_system_bytes += bytes;
  852. }
  853. return result;
  854. }
  855. template <class T>
  856. class PageHeapAllocator {
  857. private:
  858. // How much to allocate from system at a time
  859. static const size_t kAllocIncrement = 32 << 10;
  860. // Aligned size of T
  861. static const size_t kAlignedSize
  862. = (((sizeof(T) + kAlignment - 1) / kAlignment) * kAlignment);
  863. // Free area from which to carve new objects
  864. char* free_area_;
  865. size_t free_avail_;
  866. // Linked list of all regions allocated by this allocator
  867. void* allocated_regions_;
  868. // Free list of already carved objects
  869. void* free_list_;
  870. // Number of allocated but unfreed objects
  871. int inuse_;
  872. public:
  873. void Init() {
  874. ASSERT(kAlignedSize <= kAllocIncrement);
  875. inuse_ = 0;
  876. allocated_regions_ = 0;
  877. free_area_ = NULL;
  878. free_avail_ = 0;
  879. free_list_ = NULL;
  880. }
  881. T* New() {
  882. // Consult free list
  883. void* result;
  884. if (free_list_ != NULL) {
  885. result = free_list_;
  886. free_list_ = *(reinterpret_cast<void**>(result));
  887. } else {
  888. if (free_avail_ < kAlignedSize) {
  889. // Need more room
  890. char* new_allocation = reinterpret_cast<char*>(MetaDataAlloc(kAllocIncrement));
  891. if (!new_allocation)
  892. CRASH();
  893. *reinterpret_cast_ptr<void**>(new_allocation) = allocated_regions_;
  894. allocated_regions_ = new_allocation;
  895. free_area_ = new_allocation + kAlignedSize;
  896. free_avail_ = kAllocIncrement - kAlignedSize;
  897. }
  898. result = free_area_;
  899. free_area_ += kAlignedSize;
  900. free_avail_ -= kAlignedSize;
  901. }
  902. inuse_++;
  903. return reinterpret_cast<T*>(result);
  904. }
  905. void Delete(T* p) {
  906. *(reinterpret_cast<void**>(p)) = free_list_;
  907. free_list_ = p;
  908. inuse_--;
  909. }
  910. int inuse() const { return inuse_; }
  911. #if defined(WTF_CHANGES) && OS(DARWIN)
  912. template <class Recorder>
  913. void recordAdministrativeRegions(Recorder& recorder, const RemoteMemoryReader& reader)
  914. {
  915. for (void* adminAllocation = allocated_regions_; adminAllocation; adminAllocation = reader.nextEntryInLinkedList(reinterpret_cast<void**>(adminAllocation)))
  916. recorder.recordRegion(reinterpret_cast<vm_address_t>(adminAllocation), kAllocIncrement);
  917. }
  918. #endif
  919. };
  920. // -------------------------------------------------------------------------
  921. // Span - a contiguous run of pages
  922. // -------------------------------------------------------------------------
  923. // Type that can hold a page number
  924. typedef uintptr_t PageID;
  925. // Type that can hold the length of a run of pages
  926. typedef uintptr_t Length;
  927. static const Length kMaxValidPages = (~static_cast<Length>(0)) >> kPageShift;
  928. // Convert byte size into pages. This won't overflow, but may return
  929. // an unreasonably large value if bytes is huge enough.
  930. static inline Length pages(size_t bytes) {
  931. return (bytes >> kPageShift) +
  932. ((bytes & (kPageSize - 1)) > 0 ? 1 : 0);
  933. }
  934. // Convert a user size into the number of bytes that will actually be
  935. // allocated
  936. static size_t AllocationSize(size_t bytes) {
  937. if (bytes > kMaxSize) {
  938. // Large object: we allocate an integral number of pages
  939. ASSERT(bytes <= (kMaxValidPages << kPageShift));
  940. return pages(bytes) << kPageShift;
  941. } else {
  942. // Small object: find the size class to which it belongs
  943. return ByteSizeForClass(SizeClass(bytes));
  944. }
  945. }
  946. // Information kept for a span (a contiguous run of pages).
  947. struct Span {
  948. PageID start; // Starting page number
  949. Length length; // Number of pages in span
  950. Span* next; // Used when in link list
  951. Span* prev; // Used when in link list
  952. void* objects; // Linked list of free objects
  953. unsigned int free : 1; // Is the span free
  954. #ifndef NO_TCMALLOC_SAMPLES
  955. unsigned int sample : 1; // Sampled object?
  956. #endif
  957. unsigned int sizeclass : 8; // Size-class for small objects (or 0)
  958. unsigned int refcount : 11; // Number of non-free objects
  959. bool decommitted : 1;
  960. #undef SPAN_HISTORY
  961. #ifdef SPAN_HISTORY
  962. // For debugging, we can keep a log events per span
  963. int nexthistory;
  964. char history[64];
  965. int value[64];
  966. #endif
  967. };
  968. #define ASSERT_SPAN_COMMITTED(span) ASSERT(!span->decommitted)
  969. #ifdef SPAN_HISTORY
  970. void Event(Span* span, char op, int v = 0) {
  971. span->history[span->nexthistory] = op;
  972. span->value[span->nexthistory] = v;
  973. span->nexthistory++;
  974. if (span->nexthistory == sizeof(span->history)) span->nexthistory = 0;
  975. }
  976. #else
  977. #define Event(s,o,v) ((void) 0)
  978. #endif
  979. // Allocator/deallocator for spans
  980. static PageHeapAllocator<Span> span_allocator;
  981. static Span* NewSpan(PageID p, Length len) {
  982. Span* result = span_allocator.New();
  983. memset(result, 0, sizeof(*result));
  984. result->start = p;
  985. result->length = len;
  986. #ifdef SPAN_HISTORY
  987. result->nexthistory = 0;
  988. #endif
  989. return result;
  990. }
  991. static inline void DeleteSpan(Span* span) {
  992. #ifndef NDEBUG
  993. // In debug mode, trash the contents of deleted Spans
  994. memset(span, 0x3f, sizeof(*span));
  995. #endif
  996. span_allocator.Delete(span);
  997. }
  998. // -------------------------------------------------------------------------
  999. // Doubly linked list of spans.
  1000. // -------------------------------------------------------------------------
  1001. static inline void DLL_Init(Span* list) {
  1002. list->next = list;
  1003. list->prev = list;
  1004. }
  1005. static inline void DLL_Remove(Span* span) {
  1006. span->prev->next = span->next;
  1007. span->next->prev = span->prev;
  1008. span->prev = NULL;
  1009. span->next = NULL;
  1010. }
  1011. static ALWAYS_INLINE bool DLL_IsEmpty(const Span* list) {
  1012. return list->next == list;
  1013. }
  1014. static int DLL_Length(const Span* list) {
  1015. int result = 0;
  1016. for (Span* s = list->next; s != list; s = s->next) {
  1017. result++;
  1018. }
  1019. return result;
  1020. }
  1021. #if 0 /* Not needed at the moment -- causes compiler warnings if not used */
  1022. static void DLL_Print(const char* label, const Span* list) {
  1023. MESSAGE("%-10s %p:", label, list);
  1024. for (const Span* s = list->next; s != list; s = s->next) {
  1025. MESSAGE(" <%p,%u,%u>", s, s->start, s->length);
  1026. }
  1027. MESSAGE("\n");
  1028. }
  1029. #endif
  1030. static inline void DLL_Prepend(Span* list, Span* span) {
  1031. ASSERT(span->next == NULL);
  1032. ASSERT(span->prev == NULL);
  1033. span->next = list->next;
  1034. span->prev = list;
  1035. list->next->prev = span;
  1036. list->next = span;
  1037. }
  1038. // -------------------------------------------------------------------------
  1039. // Stack traces kept for sampled allocations
  1040. // The following state is protected by pageheap_lock_.
  1041. // -------------------------------------------------------------------------
  1042. // size/depth are made the same size as a pointer so that some generic
  1043. // code below can conveniently cast them back and forth to void*.
  1044. static const int kMaxStackDepth = 31;
  1045. struct StackTrace {
  1046. uintptr_t size; // Size of object
  1047. uintptr_t depth; // Number of PC values stored in array below
  1048. void* stack[kMaxStackDepth];
  1049. };
  1050. static PageHeapAllocator<StackTrace> stacktrace_allocator;
  1051. static Span sampled_objects;
  1052. // -------------------------------------------------------------------------
  1053. // Map from page-id to per-page data
  1054. // -------------------------------------------------------------------------
  1055. // We use PageMap2<> for 32-bit and PageMap3<> for 64-bit machines.
  1056. // We also use a simple one-level cache for hot PageID-to-sizeclass mappings,
  1057. // because sometimes the sizeclass is all the information we need.
  1058. // Selector class -- general selector uses 3-level map
  1059. template <int BITS> class MapSelector {
  1060. public:
  1061. typedef TCMalloc_PageMap3<BITS-kPageShift> Type;
  1062. typedef PackedCache<BITS, uint64_t> CacheType;
  1063. };
  1064. #if defined(WTF_CHANGES)
  1065. #if CPU(X86_64)
  1066. // On all known X86-64 platforms, the upper 16 bits are always unused and therefore
  1067. // can be excluded from the PageMap key.
  1068. // See http://en.wikipedia.org/wiki/X86-64#Virtual_address_space_details
  1069. static const size_t kBitsUnusedOn64Bit = 16;
  1070. #else
  1071. static const size_t kBitsUnusedOn64Bit = 0;
  1072. #endif
  1073. // A three-level map for 64-bit machines
  1074. template <> class MapSelector<64> {
  1075. public:
  1076. typedef TCMalloc_PageMap3<64 - kPageShift - kBitsUnusedOn64Bit> Type;
  1077. typedef PackedCache<64, uint64_t> CacheType;
  1078. };
  1079. #endif
  1080. // A two-level map for 32-bit machines
  1081. template <> class MapSelector<32> {
  1082. public:
  1083. typedef TCMalloc_PageMap2<32 - kPageShift> Type;
  1084. typedef PackedCache<32 - kPageShift, uint16_t> CacheType;
  1085. };
  1086. // -------------------------------------------------------------------------
  1087. // Page-level allocator
  1088. // * Eager coalescing
  1089. //
  1090. // Heap for page-level allocation. We allow allocating and freeing a
  1091. // contiguous runs of pages (called a "span").
  1092. // -------------------------------------------------------------------------
  1093. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1094. // The page heap maintains a free list for spans that are no longer in use by
  1095. // the central cache or any thread caches. We use a background thread to
  1096. // periodically scan the free list and release a percentage of it back to the OS.
  1097. // If free_committed_pages_ exceeds kMinimumFreeCommittedPageCount, the
  1098. // background thread:
  1099. // - wakes up
  1100. // - pauses for kScavengeDelayInSeconds
  1101. // - returns to the OS a percentage of the memory that remained unused during
  1102. // that pause (kScavengePercentage * min_free_committed_pages_since_last_scavenge_)
  1103. // The goal of this strategy is to reduce memory pressure in a timely fashion
  1104. // while avoiding thrashing the OS allocator.
  1105. // Time delay before the page heap scavenger will consider returning pages to
  1106. // the OS.
  1107. static const int kScavengeDelayInSeconds = 2;
  1108. // Approximate percentage of free committed pages to return to the OS in one
  1109. // scavenge.
  1110. static const float kScavengePercentage = .5f;
  1111. // number of span lists to keep spans in when memory is returned.
  1112. static const int kMinSpanListsWithSpans = 32;
  1113. // Number of free committed pages that we want to keep around. The minimum number of pages used when there
  1114. // is 1 span in each of the first kMinSpanListsWithSpans spanlists. Currently 528 pages.
  1115. static const size_t kMinimumFreeCommittedPageCount = kMinSpanListsWithSpans * ((1.0f+kMinSpanListsWithSpans) / 2.0f);
  1116. #endif
  1117. class TCMalloc_PageHeap {
  1118. public:
  1119. void init();
  1120. // Allocate a run of "n" pages. Returns zero if out of memory.
  1121. Span* New(Length n);
  1122. // Delete the span "[p, p+n-1]".
  1123. // REQUIRES: span was returned by earlier call to New() and
  1124. // has not yet been deleted.
  1125. void Delete(Span* span);
  1126. // Mark an allocated span as being used for small objects of the
  1127. // specified size-class.
  1128. // REQUIRES: span was returned by an earlier call to New()
  1129. // and has not yet been deleted.
  1130. void RegisterSizeClass(Span* span, size_t sc);
  1131. // Split an allocated span into two spans: one of length "n" pages
  1132. // followed by another span of length "span->length - n" pages.
  1133. // Modifies "*span" to point to the first span of length "n" pages.
  1134. // Returns a pointer to the second span.
  1135. //
  1136. // REQUIRES: "0 < n < span->length"
  1137. // REQUIRES: !span->free
  1138. // REQUIRES: span->sizeclass == 0
  1139. Span* Split(Span* span, Length n);
  1140. // Return the descriptor for the specified page.
  1141. inline Span* GetDescriptor(PageID p) const {
  1142. return reinterpret_cast<Span*>(pagemap_.get(p));
  1143. }
  1144. #ifdef WTF_CHANGES
  1145. inline Span* GetDescriptorEnsureSafe(PageID p)
  1146. {
  1147. pagemap_.Ensure(p, 1);
  1148. return GetDescriptor(p);
  1149. }
  1150. size_t ReturnedBytes() const;
  1151. #endif
  1152. // Dump state to stderr
  1153. #ifndef WTF_CHANGES
  1154. void Dump(TCMalloc_Printer* out);
  1155. #endif
  1156. // Return number of bytes allocated from system
  1157. inline uint64_t SystemBytes() const { return system_bytes_; }
  1158. // Return number of free bytes in heap
  1159. uint64_t FreeBytes() const {
  1160. return (static_cast<uint64_t>(free_pages_) << kPageShift);
  1161. }
  1162. bool Check();
  1163. bool CheckList(Span* list, Length min_pages, Length max_pages);
  1164. // Release all pages on the free list for reuse by the OS:
  1165. void ReleaseFreePages();
  1166. // Return 0 if we have no information, or else the correct sizeclass for p.
  1167. // Reads and writes to pagemap_cache_ do not require locking.
  1168. // The entries are 64 bits on 64-bit hardware and 16 bits on
  1169. // 32-bit hardware, and we don't mind raciness as long as each read of
  1170. // an entry yields a valid entry, not a partially updated entry.
  1171. size_t GetSizeClassIfCached(PageID p) const {
  1172. return pagemap_cache_.GetOrDefault(p, 0);
  1173. }
  1174. void CacheSizeClass(PageID p, size_t cl) const { pagemap_cache_.Put(p, cl); }
  1175. private:
  1176. // Pick the appropriate map and cache types based on pointer size
  1177. typedef MapSelector<8*sizeof(uintptr_t)>::Type PageMap;
  1178. typedef MapSelector<8*sizeof(uintptr_t)>::CacheType PageMapCache;
  1179. PageMap pagemap_;
  1180. mutable PageMapCache pagemap_cache_;
  1181. // We segregate spans of a given size into two circular linked
  1182. // lists: one for normal spans, and one for spans whose memory
  1183. // has been returned to the system.
  1184. struct SpanList {
  1185. Span normal;
  1186. Span returned;
  1187. };
  1188. // List of free spans of length >= kMaxPages
  1189. SpanList large_;
  1190. // Array mapping from span length to a doubly linked list of free spans
  1191. SpanList free_[kMaxPages];
  1192. // Number of pages kept in free lists
  1193. uintptr_t free_pages_;
  1194. // Bytes allocated from system
  1195. uint64_t system_bytes_;
  1196. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1197. // Number of pages kept in free lists that are still committed.
  1198. Length free_committed_pages_;
  1199. // Minimum number of free committed pages since last scavenge. (Can be 0 if
  1200. // we've committed new pages since the last scavenge.)
  1201. Length min_free_committed_pages_since_last_scavenge_;
  1202. #endif
  1203. bool GrowHeap(Length n);
  1204. // REQUIRES span->length >= n
  1205. // Remove span from its free list, and move any leftover part of
  1206. // span into appropriate free lists. Also update "span" to have
  1207. // length exactly "n" and mark it as non-free so it can be returned
  1208. // to the client.
  1209. //
  1210. // "released" is true iff "span" was found on a "returned" list.
  1211. void Carve(Span* span, Length n, bool released);
  1212. void RecordSpan(Span* span) {
  1213. pagemap_.set(span->start, span);
  1214. if (span->length > 1) {
  1215. pagemap_.set(span->start + span->length - 1, span);
  1216. }
  1217. }
  1218. // Allocate a large span of length == n. If successful, returns a
  1219. // span of exactly the specified length. Else, returns NULL.
  1220. Span* AllocLarge(Length n);
  1221. #if !USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1222. // Incrementally release some memory to the system.
  1223. // IncrementalScavenge(n) is called whenever n pages are freed.
  1224. void IncrementalScavenge(Length n);
  1225. #endif
  1226. // Number of pages to deallocate before doing more scavenging
  1227. int64_t scavenge_counter_;
  1228. // Index of last free list we scavenged
  1229. size_t scavenge_index_;
  1230. #if defined(WTF_CHANGES) && OS(DARWIN)
  1231. friend class FastMallocZone;
  1232. #endif
  1233. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1234. void initializeScavenger();
  1235. ALWAYS_INLINE void signalScavenger();
  1236. void scavenge();
  1237. ALWAYS_INLINE bool shouldScavenge() const;
  1238. #if HAVE(DISPATCH_H) || OS(WINDOWS)
  1239. void periodicScavenge();
  1240. ALWAYS_INLINE bool isScavengerSuspended();
  1241. ALWAYS_INLINE void scheduleScavenger();
  1242. ALWAYS_INLINE void rescheduleScavenger();
  1243. ALWAYS_INLINE void suspendScavenger();
  1244. #endif
  1245. #if HAVE(DISPATCH_H)
  1246. dispatch_queue_t m_scavengeQueue;
  1247. dispatch_source_t m_scavengeTimer;
  1248. bool m_scavengingSuspended;
  1249. #elif OS(WINDOWS)
  1250. static void CALLBACK scavengerTimerFired(void*, BOOLEAN);
  1251. HANDLE m_scavengeQueueTimer;
  1252. #else
  1253. static NO_RETURN_WITH_VALUE void* runScavengerThread(void*);
  1254. NO_RETURN void scavengerThread();
  1255. // Keeps track of whether the background thread is actively scavenging memory every kScavengeDelayInSeconds, or
  1256. // it's blocked waiting for more pages to be deleted.
  1257. bool m_scavengeThreadActive;
  1258. pthread_mutex_t m_scavengeMutex;
  1259. pthread_cond_t m_scavengeCondition;
  1260. #endif
  1261. #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1262. };
  1263. void TCMalloc_PageHeap::init()
  1264. {
  1265. pagemap_.init(MetaDataAlloc);
  1266. pagemap_cache_ = PageMapCache(0);
  1267. free_pages_ = 0;
  1268. system_bytes_ = 0;
  1269. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1270. free_committed_pages_ = 0;
  1271. min_free_committed_pages_since_last_scavenge_ = 0;
  1272. #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1273. scavenge_counter_ = 0;
  1274. // Start scavenging at kMaxPages list
  1275. scavenge_index_ = kMaxPages-1;
  1276. COMPILE_ASSERT(kNumClasses <= (1 << PageMapCache::kValuebits), valuebits);
  1277. DLL_Init(&large_.normal);
  1278. DLL_Init(&large_.returned);
  1279. for (size_t i = 0; i < kMaxPages; i++) {
  1280. DLL_Init(&free_[i].normal);
  1281. DLL_Init(&free_[i].returned);
  1282. }
  1283. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1284. initializeScavenger();
  1285. #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1286. }
  1287. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1288. #if HAVE(DISPATCH_H)
  1289. void TCMalloc_PageHeap::initializeScavenger()
  1290. {
  1291. m_scavengeQueue = dispatch_queue_create("com.apple.JavaScriptCore.FastMallocSavenger", NULL);
  1292. m_scavengeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, m_scavengeQueue);
  1293. dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, kScavengeDelayInSeconds * NSEC_PER_SEC);
  1294. dispatch_source_set_timer(m_scavengeTimer, startTime, kScavengeDelayInSeconds * NSEC_PER_SEC, 1000 * NSEC_PER_USEC);
  1295. dispatch_source_set_event_handler(m_scavengeTimer, ^{ periodicScavenge(); });
  1296. m_scavengingSuspended = true;
  1297. }
  1298. ALWAYS_INLINE bool TCMalloc_PageHeap::isScavengerSuspended()
  1299. {
  1300. ASSERT(IsHeld(pageheap_lock));
  1301. return m_scavengingSuspended;
  1302. }
  1303. ALWAYS_INLINE void TCMalloc_PageHeap::scheduleScavenger()
  1304. {
  1305. ASSERT(IsHeld(pageheap_lock));
  1306. m_scavengingSuspended = false;
  1307. dispatch_resume(m_scavengeTimer);
  1308. }
  1309. ALWAYS_INLINE void TCMalloc_PageHeap::rescheduleScavenger()
  1310. {
  1311. // Nothing to do here for libdispatch.
  1312. }
  1313. ALWAYS_INLINE void TCMalloc_PageHeap::suspendScavenger()
  1314. {
  1315. ASSERT(IsHeld(pageheap_lock));
  1316. m_scavengingSuspended = true;
  1317. dispatch_suspend(m_scavengeTimer);
  1318. }
  1319. #elif OS(WINDOWS)
  1320. void TCMalloc_PageHeap::scavengerTimerFired(void* context, BOOLEAN)
  1321. {
  1322. static_cast<TCMalloc_PageHeap*>(context)->periodicScavenge();
  1323. }
  1324. void TCMalloc_PageHeap::initializeScavenger()
  1325. {
  1326. m_scavengeQueueTimer = 0;
  1327. }
  1328. ALWAYS_INLINE bool TCMalloc_PageHeap::isScavengerSuspended()
  1329. {
  1330. ASSERT(IsHeld(pageheap_lock));
  1331. return !m_scavengeQueueTimer;
  1332. }
  1333. ALWAYS_INLINE void TCMalloc_PageHeap::scheduleScavenger()
  1334. {
  1335. // We need to use WT_EXECUTEONLYONCE here and reschedule the timer, because
  1336. // Windows will fire the timer event even when the function is already running.
  1337. ASSERT(IsHeld(pageheap_lock));
  1338. CreateTimerQueueTimer(&m_scavengeQueueTimer, 0, scavengerTimerFired, this, kScavengeDelayInSeconds * 1000, 0, WT_EXECUTEONLYONCE);
  1339. }
  1340. ALWAYS_INLINE void TCMalloc_PageHeap::rescheduleScavenger()
  1341. {
  1342. // We must delete the timer and create it again, because it is not possible to retrigger a timer on Windows.
  1343. suspendScavenger();
  1344. scheduleScavenger();
  1345. }
  1346. ALWAYS_INLINE void TCMalloc_PageHeap::suspendScavenger()
  1347. {
  1348. ASSERT(IsHeld(pageheap_lock));
  1349. HANDLE scavengeQueueTimer = m_scavengeQueueTimer;
  1350. m_scavengeQueueTimer = 0;
  1351. DeleteTimerQueueTimer(0, scavengeQueueTimer, 0);
  1352. }
  1353. #else
  1354. void TCMalloc_PageHeap::initializeScavenger()
  1355. {
  1356. // Create a non-recursive mutex.
  1357. #if !defined(PTHREAD_MUTEX_NORMAL) || PTHREAD_MUTEX_NORMAL == PTHREAD_MUTEX_DEFAULT
  1358. pthread_mutex_init(&m_scavengeMutex, 0);
  1359. #else
  1360. pthread_mutexattr_t attr;
  1361. pthread_mutexattr_init(&attr);
  1362. pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
  1363. pthread_mutex_init(&m_scavengeMutex, &attr);
  1364. pthread_mutexattr_destroy(&attr);
  1365. #endif
  1366. pthread_cond_init(&m_scavengeCondition, 0);
  1367. m_scavengeThreadActive = true;
  1368. pthread_t thread;
  1369. pthread_create(&thread, 0, runScavengerThread, this);
  1370. }
  1371. void* TCMalloc_PageHeap::runScavengerThread(void* context)
  1372. {
  1373. static_cast<TCMalloc_PageHeap*>(context)->scavengerThread();
  1374. #if (COMPILER(MSVC) || COMPILER(SUNCC))
  1375. // Without this, Visual Studio and Sun Studio will complain that this method does not return a value.
  1376. return 0;
  1377. #endif
  1378. }
  1379. ALWAYS_INLINE void TCMalloc_PageHeap::signalScavenger()
  1380. {
  1381. // m_scavengeMutex should be held before accessing m_scavengeThreadActive.
  1382. ASSERT(pthread_mutex_trylock(m_scavengeMutex));
  1383. if (!m_scavengeThreadActive && shouldScavenge())
  1384. pthread_cond_signal(&m_scavengeCondition);
  1385. }
  1386. #endif
  1387. void TCMalloc_PageHeap::scavenge()
  1388. {
  1389. size_t pagesToRelease = min_free_committed_pages_since_last_scavenge_ * kScavengePercentage;
  1390. size_t targetPageCount = std::max<size_t>(kMinimumFreeCommittedPageCount, free_committed_pages_ - pagesToRelease);
  1391. while (free_committed_pages_ > targetPageCount) {
  1392. for (int i = kMaxPages; i > 0 && free_committed_pages_ >= targetPageCount; i--) {
  1393. SpanList* slist = (static_cast<size_t>(i) == kMaxPages) ? &large_ : &free_[i];
  1394. // If the span size is bigger than kMinSpanListsWithSpans pages return all the spans in the list, else return all but 1 span.
  1395. // Return only 50% of a spanlist at a time so spans of size 1 are not the only ones left.
  1396. size_t length = DLL_Length(&slist->normal);
  1397. size_t numSpansToReturn = (i > kMinSpanListsWithSpans) ? length : length / 2;
  1398. for (int j = 0; static_cast<size_t>(j) < numSpansToReturn && !DLL_IsEmpty(&slist->normal) && free_committed_pages_ > targetPageCount; j++) {
  1399. Span* s = slist->normal.prev;
  1400. DLL_Remove(s);
  1401. ASSERT(!s->decommitted);
  1402. if (!s->decommitted) {
  1403. TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
  1404. static_cast<size_t>(s->length << kPageShift));
  1405. ASSERT(free_committed_pages_ >= s->length);
  1406. free_committed_pages_ -= s->length;
  1407. s->decommitted = true;
  1408. }
  1409. DLL_Prepend(&slist->returned, s);
  1410. }
  1411. }
  1412. }
  1413. min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
  1414. }
  1415. ALWAYS_INLINE bool TCMalloc_PageHeap::shouldScavenge() const
  1416. {
  1417. return free_committed_pages_ > kMinimumFreeCommittedPageCount;
  1418. }
  1419. #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1420. inline Span* TCMalloc_PageHeap::New(Length n) {
  1421. ASSERT(Check());
  1422. ASSERT(n > 0);
  1423. // Find first size >= n that has a non-empty list
  1424. for (Length s = n; s < kMaxPages; s++) {
  1425. Span* ll = NULL;
  1426. bool released = false;
  1427. if (!DLL_IsEmpty(&free_[s].normal)) {
  1428. // Found normal span
  1429. ll = &free_[s].normal;
  1430. } else if (!DLL_IsEmpty(&free_[s].returned)) {
  1431. // Found returned span; reallocate it
  1432. ll = &free_[s].returned;
  1433. released = true;
  1434. } else {
  1435. // Keep looking in larger classes
  1436. continue;
  1437. }
  1438. Span* result = ll->next;
  1439. Carve(result, n, released);
  1440. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1441. // The newly allocated memory is from a span that's in the normal span list (already committed). Update the
  1442. // free committed pages count.
  1443. ASSERT(free_committed_pages_ >= n);
  1444. free_committed_pages_ -= n;
  1445. if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
  1446. min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
  1447. #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1448. ASSERT(Check());
  1449. free_pages_ -= n;
  1450. return result;
  1451. }
  1452. Span* result = AllocLarge(n);
  1453. if (result != NULL) {
  1454. ASSERT_SPAN_COMMITTED(result);
  1455. return result;
  1456. }
  1457. // Grow the heap and try again
  1458. if (!GrowHeap(n)) {
  1459. ASSERT(Check());
  1460. return NULL;
  1461. }
  1462. return AllocLarge(n);
  1463. }
  1464. Span* TCMalloc_PageHeap::AllocLarge(Length n) {
  1465. // find the best span (closest to n in size).
  1466. // The following loops implements address-ordered best-fit.
  1467. bool from_released = false;
  1468. Span *best = NULL;
  1469. // Search through normal list
  1470. for (Span* span = large_.normal.next;
  1471. span != &large_.normal;
  1472. span = span->next) {
  1473. if (span->length >= n) {
  1474. if ((best == NULL)
  1475. || (span->length < best->length)
  1476. || ((span->length == best->length) && (span->start < best->start))) {
  1477. best = span;
  1478. from_released = false;
  1479. }
  1480. }
  1481. }
  1482. // Search through released list in case it has a better fit
  1483. for (Span* span = large_.returned.next;
  1484. span != &large_.returned;
  1485. span = span->next) {
  1486. if (span->length >= n) {
  1487. if ((best == NULL)
  1488. || (span->length < best->length)
  1489. || ((span->length == best->length) && (span->start < best->start))) {
  1490. best = span;
  1491. from_released = true;
  1492. }
  1493. }
  1494. }
  1495. if (best != NULL) {
  1496. Carve(best, n, from_released);
  1497. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1498. // The newly allocated memory is from a span that's in the normal span list (already committed). Update the
  1499. // free committed pages count.
  1500. ASSERT(free_committed_pages_ >= n);
  1501. free_committed_pages_ -= n;
  1502. if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
  1503. min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
  1504. #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1505. ASSERT(Check());
  1506. free_pages_ -= n;
  1507. return best;
  1508. }
  1509. return NULL;
  1510. }
  1511. Span* TCMalloc_PageHeap::Split(Span* span, Length n) {
  1512. ASSERT(0 < n);
  1513. ASSERT(n < span->length);
  1514. ASSERT(!span->free);
  1515. ASSERT(span->sizeclass == 0);
  1516. Event(span, 'T', n);
  1517. const Length extra = span->length - n;
  1518. Span* leftover = NewSpan(span->start + n, extra);
  1519. Event(leftover, 'U', extra);
  1520. RecordSpan(leftover);
  1521. pagemap_.set(span->start + n - 1, span); // Update map from pageid to span
  1522. span->length = n;
  1523. return leftover;
  1524. }
  1525. inline void TCMalloc_PageHeap::Carve(Span* span, Length n, bool released) {
  1526. ASSERT(n > 0);
  1527. DLL_Remove(span);
  1528. span->free = 0;
  1529. Event(span, 'A', n);
  1530. if (released) {
  1531. // If the span chosen to carve from is decommited, commit the entire span at once to avoid committing spans 1 page at a time.
  1532. ASSERT(span->decommitted);
  1533. TCMalloc_SystemCommit(reinterpret_cast<void*>(span->start << kPageShift), static_cast<size_t>(span->length << kPageShift));
  1534. span->decommitted = false;
  1535. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1536. free_committed_pages_ += span->length;
  1537. #endif
  1538. }
  1539. const int extra = static_cast<int>(span->length - n);
  1540. ASSERT(extra >= 0);
  1541. if (extra > 0) {
  1542. Span* leftover = NewSpan(span->start + n, extra);
  1543. leftover->free = 1;
  1544. leftover->decommitted = false;
  1545. Event(leftover, 'S', extra);
  1546. RecordSpan(leftover);
  1547. // Place leftover span on appropriate free list
  1548. SpanList* listpair = (static_cast<size_t>(extra) < kMaxPages) ? &free_[extra] : &large_;
  1549. Span* dst = &listpair->normal;
  1550. DLL_Prepend(dst, leftover);
  1551. span->length = n;
  1552. pagemap_.set(span->start + n - 1, span);
  1553. }
  1554. }
  1555. static ALWAYS_INLINE void mergeDecommittedStates(Span* destination, Span* other)
  1556. {
  1557. if (destination->decommitted && !other->decommitted) {
  1558. TCMalloc_SystemRelease(reinterpret_cast<void*>(other->start << kPageShift),
  1559. static_cast<size_t>(other->length << kPageShift));
  1560. } else if (other->decommitted && !destination->decommitted) {
  1561. TCMalloc_SystemRelease(reinterpret_cast<void*>(destination->start << kPageShift),
  1562. static_cast<size_t>(destination->length << kPageShift));
  1563. destination->decommitted = true;
  1564. }
  1565. }
  1566. inline void TCMalloc_PageHeap::Delete(Span* span) {
  1567. ASSERT(Check());
  1568. ASSERT(!span->free);
  1569. ASSERT(span->length > 0);
  1570. ASSERT(GetDescriptor(span->start) == span);
  1571. ASSERT(GetDescriptor(span->start + span->length - 1) == span);
  1572. span->sizeclass = 0;
  1573. #ifndef NO_TCMALLOC_SAMPLES
  1574. span->sample = 0;
  1575. #endif
  1576. // Coalesce -- we guarantee that "p" != 0, so no bounds checking
  1577. // necessary. We do not bother resetting the stale pagemap
  1578. // entries for the pieces we are merging together because we only
  1579. // care about the pagemap entries for the boundaries.
  1580. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1581. // Track the total size of the neighboring free spans that are committed.
  1582. Length neighboringCommittedSpansLength = 0;
  1583. #endif
  1584. const PageID p = span->start;
  1585. const Length n = span->length;
  1586. Span* prev = GetDescriptor(p-1);
  1587. if (prev != NULL && prev->free) {
  1588. // Merge preceding span into this span
  1589. ASSERT(prev->start + prev->length == p);
  1590. const Length len = prev->length;
  1591. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1592. if (!prev->decommitted)
  1593. neighboringCommittedSpansLength += len;
  1594. #endif
  1595. mergeDecommittedStates(span, prev);
  1596. DLL_Remove(prev);
  1597. DeleteSpan(prev);
  1598. span->start -= len;
  1599. span->length += len;
  1600. pagemap_.set(span->start, span);
  1601. Event(span, 'L', len);
  1602. }
  1603. Span* next = GetDescriptor(p+n);
  1604. if (next != NULL && next->free) {
  1605. // Merge next span into this span
  1606. ASSERT(next->start == p+n);
  1607. const Length len = next->length;
  1608. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1609. if (!next->decommitted)
  1610. neighboringCommittedSpansLength += len;
  1611. #endif
  1612. mergeDecommittedStates(span, next);
  1613. DLL_Remove(next);
  1614. DeleteSpan(next);
  1615. span->length += len;
  1616. pagemap_.set(span->start + span->length - 1, span);
  1617. Event(span, 'R', len);
  1618. }
  1619. Event(span, 'D', span->length);
  1620. span->free = 1;
  1621. if (span->decommitted) {
  1622. if (span->length < kMaxPages)
  1623. DLL_Prepend(&free_[span->length].returned, span);
  1624. else
  1625. DLL_Prepend(&large_.returned, span);
  1626. } else {
  1627. if (span->length < kMaxPages)
  1628. DLL_Prepend(&free_[span->length].normal, span);
  1629. else
  1630. DLL_Prepend(&large_.normal, span);
  1631. }
  1632. free_pages_ += n;
  1633. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1634. if (span->decommitted) {
  1635. // If the merged span is decommitted, that means we decommitted any neighboring spans that were
  1636. // committed. Update the free committed pages count.
  1637. free_committed_pages_ -= neighboringCommittedSpansLength;
  1638. if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
  1639. min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
  1640. } else {
  1641. // If the merged span remains committed, add the deleted span's size to the free committed pages count.
  1642. free_committed_pages_ += n;
  1643. }
  1644. // Make sure the scavenge thread becomes active if we have enough freed pages to release some back to the system.
  1645. signalScavenger();
  1646. #else
  1647. IncrementalScavenge(n);
  1648. #endif
  1649. ASSERT(Check());
  1650. }
  1651. #if !USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1652. void TCMalloc_PageHeap::IncrementalScavenge(Length n) {
  1653. // Fast path; not yet time to release memory
  1654. scavenge_counter_ -= n;
  1655. if (scavenge_counter_ >= 0) return; // Not yet time to scavenge
  1656. // If there is nothing to release, wait for so many pages before
  1657. // scavenging again. With 4K pages, this comes to 16MB of memory.
  1658. static const size_t kDefaultReleaseDelay = 1 << 8;
  1659. // Find index of free list to scavenge
  1660. size_t index = scavenge_index_ + 1;
  1661. for (size_t i = 0; i < kMaxPages+1; i++) {
  1662. if (index > kMaxPages) index = 0;
  1663. SpanList* slist = (index == kMaxPages) ? &large_ : &free_[index];
  1664. if (!DLL_IsEmpty(&slist->normal)) {
  1665. // Release the last span on the normal portion of this list
  1666. Span* s = slist->normal.prev;
  1667. DLL_Remove(s);
  1668. TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
  1669. static_cast<size_t>(s->length << kPageShift));
  1670. s->decommitted = true;
  1671. DLL_Prepend(&slist->returned, s);
  1672. scavenge_counter_ = std::max<size_t>(64UL, std::min<size_t>(kDefaultReleaseDelay, kDefaultReleaseDelay - (free_pages_ / kDefaultReleaseDelay)));
  1673. if (index == kMaxPages && !DLL_IsEmpty(&slist->normal))
  1674. scavenge_index_ = index - 1;
  1675. else
  1676. scavenge_index_ = index;
  1677. return;
  1678. }
  1679. index++;
  1680. }
  1681. // Nothing to scavenge, delay for a while
  1682. scavenge_counter_ = kDefaultReleaseDelay;
  1683. }
  1684. #endif
  1685. void TCMalloc_PageHeap::RegisterSizeClass(Span* span, size_t sc) {
  1686. // Associate span object with all interior pages as well
  1687. ASSERT(!span->free);
  1688. ASSERT(GetDescriptor(span->start) == span);
  1689. ASSERT(GetDescriptor(span->start+span->length-1) == span);
  1690. Event(span, 'C', sc);
  1691. span->sizeclass = static_cast<unsigned int>(sc);
  1692. for (Length i = 1; i < span->length-1; i++) {
  1693. pagemap_.set(span->start+i, span);
  1694. }
  1695. }
  1696. #ifdef WTF_CHANGES
  1697. size_t TCMalloc_PageHeap::ReturnedBytes() const {
  1698. size_t result = 0;
  1699. for (unsigned s = 0; s < kMaxPages; s++) {
  1700. const int r_length = DLL_Length(&free_[s].returned);
  1701. unsigned r_pages = s * r_length;
  1702. result += r_pages << kPageShift;
  1703. }
  1704. for (Span* s = large_.returned.next; s != &large_.returned; s = s->next)
  1705. result += s->length << kPageShift;
  1706. return result;
  1707. }
  1708. #endif
  1709. #ifndef WTF_CHANGES
  1710. static double PagesToMB(uint64_t pages) {
  1711. return (pages << kPageShift) / 1048576.0;
  1712. }
  1713. void TCMalloc_PageHeap::Dump(TCMalloc_Printer* out) {
  1714. int nonempty_sizes = 0;
  1715. for (int s = 0; s < kMaxPages; s++) {
  1716. if (!DLL_IsEmpty(&free_[s].normal) || !DLL_IsEmpty(&free_[s].returned)) {
  1717. nonempty_sizes++;
  1718. }
  1719. }
  1720. out->printf("------------------------------------------------\n");
  1721. out->printf("PageHeap: %d sizes; %6.1f MB free\n",
  1722. nonempty_sizes, PagesToMB(free_pages_));
  1723. out->printf("------------------------------------------------\n");
  1724. uint64_t total_normal = 0;
  1725. uint64_t total_returned = 0;
  1726. for (int s = 0; s < kMaxPages; s++) {
  1727. const int n_length = DLL_Length(&free_[s].normal);
  1728. const int r_length = DLL_Length(&free_[s].returned);
  1729. if (n_length + r_length > 0) {
  1730. uint64_t n_pages = s * n_length;
  1731. uint64_t r_pages = s * r_length;
  1732. total_normal += n_pages;
  1733. total_returned += r_pages;
  1734. out->printf("%6u pages * %6u spans ~ %6.1f MB; %6.1f MB cum"
  1735. "; unmapped: %6.1f MB; %6.1f MB cum\n",
  1736. s,
  1737. (n_length + r_length),
  1738. PagesToMB(n_pages + r_pages),
  1739. PagesToMB(total_normal + total_returned),
  1740. PagesToMB(r_pages),
  1741. PagesToMB(total_returned));
  1742. }
  1743. }
  1744. uint64_t n_pages = 0;
  1745. uint64_t r_pages = 0;
  1746. int n_spans = 0;
  1747. int r_spans = 0;
  1748. out->printf("Normal large spans:\n");
  1749. for (Span* s = large_.normal.next; s != &large_.normal; s = s->next) {
  1750. out->printf(" [ %6" PRIuS " pages ] %6.1f MB\n",
  1751. s->length, PagesToMB(s->length));
  1752. n_pages += s->length;
  1753. n_spans++;
  1754. }
  1755. out->printf("Unmapped large spans:\n");
  1756. for (Span* s = large_.returned.next; s != &large_.returned; s = s->next) {
  1757. out->printf(" [ %6" PRIuS " pages ] %6.1f MB\n",
  1758. s->length, PagesToMB(s->length));
  1759. r_pages += s->length;
  1760. r_spans++;
  1761. }
  1762. total_normal += n_pages;
  1763. total_returned += r_pages;
  1764. out->printf(">255 large * %6u spans ~ %6.1f MB; %6.1f MB cum"
  1765. "; unmapped: %6.1f MB; %6.1f MB cum\n",
  1766. (n_spans + r_spans),
  1767. PagesToMB(n_pages + r_pages),
  1768. PagesToMB(total_normal + total_returned),
  1769. PagesToMB(r_pages),
  1770. PagesToMB(total_returned));
  1771. }
  1772. #endif
  1773. bool TCMalloc_PageHeap::GrowHeap(Length n) {
  1774. ASSERT(kMaxPages >= kMinSystemAlloc);
  1775. if (n > kMaxValidPages) return false;
  1776. Length ask = (n>kMinSystemAlloc) ? n : static_cast<Length>(kMinSystemAlloc);
  1777. size_t actual_size;
  1778. void* ptr = TCMalloc_SystemAlloc(ask << kPageShift, &actual_size, kPageSize);
  1779. if (ptr == NULL) {
  1780. if (n < ask) {
  1781. // Try growing just "n" pages
  1782. ask = n;
  1783. ptr = TCMalloc_SystemAlloc(ask << kPageShift, &actual_size, kPageSize);
  1784. }
  1785. if (ptr == NULL) return false;
  1786. }
  1787. ask = actual_size >> kPageShift;
  1788. uint64_t old_system_bytes = system_bytes_;
  1789. system_bytes_ += (ask << kPageShift);
  1790. const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
  1791. ASSERT(p > 0);
  1792. // If we have already a lot of pages allocated, just pre allocate a bunch of
  1793. // memory for the page map. This prevents fragmentation by pagemap metadata
  1794. // when a program keeps allocating and freeing large blocks.
  1795. if (old_system_bytes < kPageMapBigAllocationThreshold
  1796. && system_bytes_ >= kPageMapBigAllocationThreshold) {
  1797. pagemap_.PreallocateMoreMemory();
  1798. }
  1799. // Make sure pagemap_ has entries for all of the new pages.
  1800. // Plus ensure one before and one after so coalescing code
  1801. // does not need bounds-checking.
  1802. if (pagemap_.Ensure(p-1, ask+2)) {
  1803. // Pretend the new area is allocated and then Delete() it to
  1804. // cause any necessary coalescing to occur.
  1805. //
  1806. // We do not adjust free_pages_ here since Delete() will do it for us.
  1807. Span* span = NewSpan(p, ask);
  1808. RecordSpan(span);
  1809. Delete(span);
  1810. ASSERT(Check());
  1811. return true;
  1812. } else {
  1813. // We could not allocate memory within "pagemap_"
  1814. // TODO: Once we can return memory to the system, return the new span
  1815. return false;
  1816. }
  1817. }
  1818. bool TCMalloc_PageHeap::Check() {
  1819. ASSERT(free_[0].normal.next == &free_[0].normal);
  1820. ASSERT(free_[0].returned.next == &free_[0].returned);
  1821. CheckList(&large_.normal, kMaxPages, 1000000000);
  1822. CheckList(&large_.returned, kMaxPages, 1000000000);
  1823. for (Length s = 1; s < kMaxPages; s++) {
  1824. CheckList(&free_[s].normal, s, s);
  1825. CheckList(&free_[s].returned, s, s);
  1826. }
  1827. return true;
  1828. }
  1829. #if ASSERT_DISABLED
  1830. bool TCMalloc_PageHeap::CheckList(Span*, Length, Length) {
  1831. return true;
  1832. }
  1833. #else
  1834. bool TCMalloc_PageHeap::CheckList(Span* list, Length min_pages, Length max_pages) {
  1835. for (Span* s = list->next; s != list; s = s->next) {
  1836. CHECK_CONDITION(s->free);
  1837. CHECK_CONDITION(s->length >= min_pages);
  1838. CHECK_CONDITION(s->length <= max_pages);
  1839. CHECK_CONDITION(GetDescriptor(s->start) == s);
  1840. CHECK_CONDITION(GetDescriptor(s->start+s->length-1) == s);
  1841. }
  1842. return true;
  1843. }
  1844. #endif
  1845. static void ReleaseFreeList(Span* list, Span* returned) {
  1846. // Walk backwards through list so that when we push these
  1847. // spans on the "returned" list, we preserve the order.
  1848. while (!DLL_IsEmpty(list)) {
  1849. Span* s = list->prev;
  1850. DLL_Remove(s);
  1851. DLL_Prepend(returned, s);
  1852. TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
  1853. static_cast<size_t>(s->length << kPageShift));
  1854. }
  1855. }
  1856. void TCMalloc_PageHeap::ReleaseFreePages() {
  1857. for (Length s = 0; s < kMaxPages; s++) {
  1858. ReleaseFreeList(&free_[s].normal, &free_[s].returned);
  1859. }
  1860. ReleaseFreeList(&large_.normal, &large_.returned);
  1861. ASSERT(Check());
  1862. }
  1863. //-------------------------------------------------------------------
  1864. // Free list
  1865. //-------------------------------------------------------------------
  1866. class TCMalloc_ThreadCache_FreeList {
  1867. private:
  1868. void* list_; // Linked list of nodes
  1869. uint16_t length_; // Current length
  1870. uint16_t lowater_; // Low water mark for list length
  1871. public:
  1872. void Init() {
  1873. list_ = NULL;
  1874. length_ = 0;
  1875. lowater_ = 0;
  1876. }
  1877. // Return current length of list
  1878. int length() const {
  1879. return length_;
  1880. }
  1881. // Is list empty?
  1882. bool empty() const {
  1883. return list_ == NULL;
  1884. }
  1885. // Low-water mark management
  1886. int lowwatermark() const { return lowater_; }
  1887. void clear_lowwatermark() { lowater_ = length_; }
  1888. ALWAYS_INLINE void Push(void* ptr) {
  1889. SLL_Push(&list_, ptr);
  1890. length_++;
  1891. }
  1892. void PushRange(int N, void *start, void *end) {
  1893. SLL_PushRange(&list_, start, end);
  1894. length_ = length_ + static_cast<uint16_t>(N);
  1895. }
  1896. void PopRange(int N, void **start, void **end) {
  1897. SLL_PopRange(&list_, N, start, end);
  1898. ASSERT(length_ >= N);
  1899. length_ = length_ - static_cast<uint16_t>(N);
  1900. if (length_ < lowater_) lowater_ = length_;
  1901. }
  1902. ALWAYS_INLINE void* Pop() {
  1903. ASSERT(list_ != NULL);
  1904. length_--;
  1905. if (length_ < lowater_) lowater_ = length_;
  1906. return SLL_Pop(&list_);
  1907. }
  1908. #ifdef WTF_CHANGES
  1909. template <class Finder, class Reader>
  1910. void enumerateFreeObjects(Finder& finder, const Reader& reader)
  1911. {
  1912. for (void* nextObject = list_; nextObject; nextObject = reader.nextEntryInLinkedList(reinterpret_cast<void**>(nextObject)))
  1913. finder.visit(nextObject);
  1914. }
  1915. #endif
  1916. };
  1917. //-------------------------------------------------------------------
  1918. // Data kept per thread
  1919. //-------------------------------------------------------------------
  1920. class TCMalloc_ThreadCache {
  1921. private:
  1922. typedef TCMalloc_ThreadCache_FreeList FreeList;
  1923. #if OS(WINDOWS)
  1924. typedef DWORD ThreadIdentifier;
  1925. #else
  1926. typedef pthread_t ThreadIdentifier;
  1927. #endif
  1928. size_t size_; // Combined size of data
  1929. ThreadIdentifier tid_; // Which thread owns it
  1930. bool in_setspecific_; // Called pthread_setspecific?
  1931. FreeList list_[kNumClasses]; // Array indexed by size-class
  1932. // We sample allocations, biased by the size of the allocation
  1933. uint32_t rnd_; // Cheap random number generator
  1934. size_t bytes_until_sample_; // Bytes until we sample next
  1935. // Allocate a new heap. REQUIRES: pageheap_lock is held.
  1936. static inline TCMalloc_ThreadCache* NewHeap(ThreadIdentifier tid);
  1937. // Use only as pthread thread-specific destructor function.
  1938. static void DestroyThreadCache(void* ptr);
  1939. public:
  1940. // All ThreadCache objects are kept in a linked list (for stats collection)
  1941. TCMalloc_ThreadCache* next_;
  1942. TCMalloc_ThreadCache* prev_;
  1943. void Init(ThreadIdentifier tid);
  1944. void Cleanup();
  1945. // Accessors (mostly just for printing stats)
  1946. int freelist_length(size_t cl) const { return list_[cl].length(); }
  1947. // Total byte size in cache
  1948. size_t Size() const { return size_; }
  1949. ALWAYS_INLINE void* Allocate(size_t size);
  1950. void Deallocate(void* ptr, size_t size_class);
  1951. ALWAYS_INLINE void FetchFromCentralCache(size_t cl, size_t allocationSize);
  1952. void ReleaseToCentralCache(size_t cl, int N);
  1953. void Scavenge();
  1954. void Print() const;
  1955. // Record allocation of "k" bytes. Return true iff allocation
  1956. // should be sampled
  1957. bool SampleAllocation(size_t k);
  1958. // Pick next sampling point
  1959. void PickNextSample(size_t k);
  1960. static void InitModule();
  1961. static void InitTSD();
  1962. static TCMalloc_ThreadCache* GetThreadHeap();
  1963. static TCMalloc_ThreadCache* GetCache();
  1964. static TCMalloc_ThreadCache* GetCacheIfPresent();
  1965. static TCMalloc_ThreadCache* CreateCacheIfNecessary();
  1966. static void DeleteCache(TCMalloc_ThreadCache* heap);
  1967. static void BecomeIdle();
  1968. static void RecomputeThreadCacheSize();
  1969. #ifdef WTF_CHANGES
  1970. template <class Finder, class Reader>
  1971. void enumerateFreeObjects(Finder& finder, const Reader& reader)
  1972. {
  1973. for (unsigned sizeClass = 0; sizeClass < kNumClasses; sizeClass++)
  1974. list_[sizeClass].enumerateFreeObjects(finder, reader);
  1975. }
  1976. #endif
  1977. };
  1978. //-------------------------------------------------------------------
  1979. // Data kept per size-class in central cache
  1980. //-------------------------------------------------------------------
  1981. class TCMalloc_Central_FreeList {
  1982. public:
  1983. void Init(size_t cl);
  1984. // These methods all do internal locking.
  1985. // Insert the specified range into the central freelist. N is the number of
  1986. // elements in the range.
  1987. void InsertRange(void *start, void *end, int N);
  1988. // Returns the actual number of fetched elements into N.
  1989. void RemoveRange(void **start, void **end, int *N);
  1990. // Returns the number of free objects in cache.
  1991. size_t length() {
  1992. SpinLockHolder h(&lock_);
  1993. return counter_;
  1994. }
  1995. // Returns the number of free objects in the transfer cache.
  1996. int tc_length() {
  1997. SpinLockHolder h(&lock_);
  1998. return used_slots_ * num_objects_to_move[size_class_];
  1999. }
  2000. #ifdef WTF_CHANGES
  2001. template <class Finder, class Reader>
  2002. void enumerateFreeObjects(Finder& finder, const Reader& reader, TCMalloc_Central_FreeList* remoteCentralFreeList)
  2003. {
  2004. for (Span* span = &empty_; span && span != &empty_; span = (span->next ? reader(span->next) : 0))
  2005. ASSERT(!span->objects);
  2006. ASSERT(!nonempty_.objects);
  2007. static const ptrdiff_t nonemptyOffset = reinterpret_cast<const char*>(&nonempty_) - reinterpret_cast<const char*>(this);
  2008. Span* remoteNonempty = reinterpret_cast<Span*>(reinterpret_cast<char*>(remoteCentralFreeList) + nonemptyOffset);
  2009. Span* remoteSpan = nonempty_.next;
  2010. for (Span* span = reader(remoteSpan); span && remoteSpan != remoteNonempty; remoteSpan = span->next, span = (span->next ? reader(span->next) : 0)) {
  2011. for (void* nextObject = span->objects; nextObject; nextObject = reader.nextEntryInLinkedList(reinterpret_cast<void**>(nextObject)))
  2012. finder.visit(nextObject);
  2013. }
  2014. }
  2015. #endif
  2016. private:
  2017. // REQUIRES: lock_ is held
  2018. // Remove object from cache and return.
  2019. // Return NULL if no free entries in cache.
  2020. void* FetchFromSpans();
  2021. // REQUIRES: lock_ is held
  2022. // Remove object from cache and return. Fetches
  2023. // from pageheap if cache is empty. Only returns
  2024. // NULL on allocation failure.
  2025. void* FetchFromSpansSafe();
  2026. // REQUIRES: lock_ is held
  2027. // Release a linked list of objects to spans.
  2028. // May temporarily release lock_.
  2029. void ReleaseListToSpans(void *start);
  2030. // REQUIRES: lock_ is held
  2031. // Release an object to spans.
  2032. // May temporarily release lock_.
  2033. ALWAYS_INLINE void ReleaseToSpans(void* object);
  2034. // REQUIRES: lock_ is held
  2035. // Populate cache by fetching from the page heap.
  2036. // May temporarily release lock_.
  2037. ALWAYS_INLINE void Populate();
  2038. // REQUIRES: lock is held.
  2039. // Tries to make room for a TCEntry. If the cache is full it will try to
  2040. // expand it at the cost of some other cache size. Return false if there is
  2041. // no space.
  2042. bool MakeCacheSpace();
  2043. // REQUIRES: lock_ for locked_size_class is held.
  2044. // Picks a "random" size class to steal TCEntry slot from. In reality it
  2045. // just iterates over the sizeclasses but does so without taking a lock.
  2046. // Returns true on success.
  2047. // May temporarily lock a "random" size class.
  2048. static ALWAYS_INLINE bool EvictRandomSizeClass(size_t locked_size_class, bool force);
  2049. // REQUIRES: lock_ is *not* held.
  2050. // Tries to shrink the Cache. If force is true it will relase objects to
  2051. // spans if it allows it to shrink the cache. Return false if it failed to
  2052. // shrink the cache. Decrements cache_size_ on succeess.
  2053. // May temporarily take lock_. If it takes lock_, the locked_size_class
  2054. // lock is released to the thread from holding two size class locks
  2055. // concurrently which could lead to a deadlock.
  2056. bool ShrinkCache(int locked_size_class, bool force);
  2057. // This lock protects all the data members. cached_entries and cache_size_
  2058. // may be looked at without holding the lock.
  2059. SpinLock lock_;
  2060. // We keep linked lists of empty and non-empty spans.
  2061. size_t size_class_; // My size class
  2062. Span empty_; // Dummy header for list of empty spans
  2063. Span nonempty_; // Dummy header for list of non-empty spans
  2064. size_t counter_; // Number of free objects in cache entry
  2065. // Here we reserve space for TCEntry cache slots. Since one size class can
  2066. // end up getting all the TCEntries quota in the system we just preallocate
  2067. // sufficient number of entries here.
  2068. TCEntry tc_slots_[kNumTransferEntries];
  2069. // Number of currently used cached entries in tc_slots_. This variable is
  2070. // updated under a lock but can be read without one.
  2071. int32_t used_slots_;
  2072. // The current number of slots for this size class. This is an
  2073. // adaptive value that is increased if there is lots of traffic
  2074. // on a given size class.
  2075. int32_t cache_size_;
  2076. };
  2077. // Pad each CentralCache object to multiple of 64 bytes
  2078. class TCMalloc_Central_FreeListPadded : public TCMalloc_Central_FreeList {
  2079. private:
  2080. char pad_[(64 - (sizeof(TCMalloc_Central_FreeList) % 64)) % 64];
  2081. };
  2082. //-------------------------------------------------------------------
  2083. // Global variables
  2084. //-------------------------------------------------------------------
  2085. // Central cache -- a collection of free-lists, one per size-class.
  2086. // We have a separate lock per free-list to reduce contention.
  2087. static TCMalloc_Central_FreeListPadded central_cache[kNumClasses];
  2088. // Page-level allocator
  2089. static SpinLock pageheap_lock = SPINLOCK_INITIALIZER;
  2090. static AllocAlignmentInteger pageheap_memory[(sizeof(TCMalloc_PageHeap) + sizeof(AllocAlignmentInteger) - 1) / sizeof(AllocAlignmentInteger)];
  2091. static bool phinited = false;
  2092. // Avoid extra level of indirection by making "pageheap" be just an alias
  2093. // of pageheap_memory.
  2094. typedef union {
  2095. void* m_memory;
  2096. TCMalloc_PageHeap* m_pageHeap;
  2097. } PageHeapUnion;
  2098. static inline TCMalloc_PageHeap* getPageHeap()
  2099. {
  2100. PageHeapUnion u = { &pageheap_memory[0] };
  2101. return u.m_pageHeap;
  2102. }
  2103. #define pageheap getPageHeap()
  2104. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  2105. #if HAVE(DISPATCH_H) || OS(WINDOWS)
  2106. void TCMalloc_PageHeap::periodicScavenge()
  2107. {
  2108. SpinLockHolder h(&pageheap_lock);
  2109. pageheap->scavenge();
  2110. if (shouldScavenge()) {
  2111. rescheduleScavenger();
  2112. return;
  2113. }
  2114. suspendScavenger();
  2115. }
  2116. ALWAYS_INLINE void TCMalloc_PageHeap::signalScavenger()
  2117. {
  2118. ASSERT(IsHeld(pageheap_lock));
  2119. if (isScavengerSuspended() && shouldScavenge())
  2120. scheduleScavenger();
  2121. }
  2122. #else
  2123. void TCMalloc_PageHeap::scavengerThread()
  2124. {
  2125. #if HAVE(PTHREAD_SETNAME_NP)
  2126. pthread_setname_np("JavaScriptCore: FastMalloc scavenger");
  2127. #endif
  2128. while (1) {
  2129. if (!shouldScavenge()) {
  2130. pthread_mutex_lock(&m_scavengeMutex);
  2131. m_scavengeThreadActive = false;
  2132. // Block until there are enough free committed pages to release back to the system.
  2133. pthread_cond_wait(&m_scavengeCondition, &m_scavengeMutex);
  2134. m_scavengeThreadActive = true;
  2135. pthread_mutex_unlock(&m_scavengeMutex);
  2136. }
  2137. sleep(kScavengeDelayInSeconds);
  2138. {
  2139. SpinLockHolder h(&pageheap_lock);
  2140. pageheap->scavenge();
  2141. }
  2142. }
  2143. }
  2144. #endif
  2145. #endif
  2146. // If TLS is available, we also store a copy
  2147. // of the per-thread object in a __thread variable
  2148. // since __thread variables are faster to read
  2149. // than pthread_getspecific(). We still need
  2150. // pthread_setspecific() because __thread
  2151. // variables provide no way to run cleanup
  2152. // code when a thread is destroyed.
  2153. #ifdef HAVE_TLS
  2154. static __thread TCMalloc_ThreadCache *threadlocal_heap;
  2155. #endif
  2156. // Thread-specific key. Initialization here is somewhat tricky
  2157. // because some Linux startup code invokes malloc() before it
  2158. // is in a good enough state to handle pthread_keycreate().
  2159. // Therefore, we use TSD keys only after tsd_inited is set to true.
  2160. // Until then, we use a slow path to get the heap object.
  2161. static bool tsd_inited = false;
  2162. #if USE(PTHREAD_GETSPECIFIC_DIRECT)
  2163. static const pthread_key_t heap_key = __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY0;
  2164. #else
  2165. static pthread_key_t heap_key;
  2166. #endif
  2167. #if OS(WINDOWS)
  2168. DWORD tlsIndex = TLS_OUT_OF_INDEXES;
  2169. #endif
  2170. static ALWAYS_INLINE void setThreadHeap(TCMalloc_ThreadCache* heap)
  2171. {
  2172. #if USE(PTHREAD_GETSPECIFIC_DIRECT)
  2173. // Can't have two libraries both doing this in the same process,
  2174. // so check and make this crash right away.
  2175. if (pthread_getspecific(heap_key))
  2176. CRASH();
  2177. #endif
  2178. // Still do pthread_setspecific even if there's an alternate form
  2179. // of thread-local storage in use, to benefit from the delete callback.
  2180. pthread_setspecific(heap_key, heap);
  2181. #if OS(WINDOWS)
  2182. TlsSetValue(tlsIndex, heap);
  2183. #endif
  2184. }
  2185. // Allocator for thread heaps
  2186. static PageHeapAllocator<TCMalloc_ThreadCache> threadheap_allocator;
  2187. // Linked list of heap objects. Protected by pageheap_lock.
  2188. static TCMalloc_ThreadCache* thread_heaps = NULL;
  2189. static int thread_heap_count = 0;
  2190. // Overall thread cache size. Protected by pageheap_lock.
  2191. static size_t overall_thread_cache_size = kDefaultOverallThreadCacheSize;
  2192. // Global per-thread cache size. Writes are protected by
  2193. // pageheap_lock. Reads are done without any locking, which should be
  2194. // fine as long as size_t can be written atomically and we don't place
  2195. // invariants between this variable and other pieces of state.
  2196. static volatile size_t per_thread_cache_size = kMaxThreadCacheSize;
  2197. //-------------------------------------------------------------------
  2198. // Central cache implementation
  2199. //-------------------------------------------------------------------
  2200. void TCMalloc_Central_FreeList::Init(size_t cl) {
  2201. lock_.Init();
  2202. size_class_ = cl;
  2203. DLL_Init(&empty_);
  2204. DLL_Init(&nonempty_);
  2205. counter_ = 0;
  2206. cache_size_ = 1;
  2207. used_slots_ = 0;
  2208. ASSERT(cache_size_ <= kNumTransferEntries);
  2209. }
  2210. void TCMalloc_Central_FreeList::ReleaseListToSpans(void* start) {
  2211. while (start) {
  2212. void *next = SLL_Next(start);
  2213. ReleaseToSpans(start);
  2214. start = next;
  2215. }
  2216. }
  2217. ALWAYS_INLINE void TCMalloc_Central_FreeList::ReleaseToSpans(void* object) {
  2218. const PageID p = reinterpret_cast<uintptr_t>(object) >> kPageShift;
  2219. Span* span = pageheap->GetDescriptor(p);
  2220. ASSERT(span != NULL);
  2221. ASSERT(span->refcount > 0);
  2222. // If span is empty, move it to non-empty list
  2223. if (span->objects == NULL) {
  2224. DLL_Remove(span);
  2225. DLL_Prepend(&nonempty_, span);
  2226. Event(span, 'N', 0);
  2227. }
  2228. // The following check is expensive, so it is disabled by default
  2229. if (false) {
  2230. // Check that object does not occur in list
  2231. unsigned got = 0;
  2232. for (void* p = span->objects; p != NULL; p = *((void**) p)) {
  2233. ASSERT(p != object);
  2234. got++;
  2235. }
  2236. ASSERT(got + span->refcount ==
  2237. (span->length<<kPageShift)/ByteSizeForClass(span->sizeclass));
  2238. }
  2239. counter_++;
  2240. span->refcount--;
  2241. if (span->refcount == 0) {
  2242. Event(span, '#', 0);
  2243. counter_ -= (span->length<<kPageShift) / ByteSizeForClass(span->sizeclass);
  2244. DLL_Remove(span);
  2245. // Release central list lock while operating on pageheap
  2246. lock_.Unlock();
  2247. {
  2248. SpinLockHolder h(&pageheap_lock);
  2249. pageheap->Delete(span);
  2250. }
  2251. lock_.Lock();
  2252. } else {
  2253. *(reinterpret_cast<void**>(object)) = span->objects;
  2254. span->objects = object;
  2255. }
  2256. }
  2257. ALWAYS_INLINE bool TCMalloc_Central_FreeList::EvictRandomSizeClass(
  2258. size_t locked_size_class, bool force) {
  2259. static int race_counter = 0;
  2260. int t = race_counter++; // Updated without a lock, but who cares.
  2261. if (t >= static_cast<int>(kNumClasses)) {
  2262. while (t >= static_cast<int>(kNumClasses)) {
  2263. t -= kNumClasses;
  2264. }
  2265. race_counter = t;
  2266. }
  2267. ASSERT(t >= 0);
  2268. ASSERT(t < static_cast<int>(kNumClasses));
  2269. if (t == static_cast<int>(locked_size_class)) return false;
  2270. return central_cache[t].ShrinkCache(static_cast<int>(locked_size_class), force);
  2271. }
  2272. bool TCMalloc_Central_FreeList::MakeCacheSpace() {
  2273. // Is there room in the cache?
  2274. if (used_slots_ < cache_size_) return true;
  2275. // Check if we can expand this cache?
  2276. if (cache_size_ == kNumTransferEntries) return false;
  2277. // Ok, we'll try to grab an entry from some other size class.
  2278. if (EvictRandomSizeClass(size_class_, false) ||
  2279. EvictRandomSizeClass(size_class_, true)) {
  2280. // Succeeded in evicting, we're going to make our cache larger.
  2281. cache_size_++;
  2282. return true;
  2283. }
  2284. return false;
  2285. }
  2286. namespace {
  2287. class LockInverter {
  2288. private:
  2289. SpinLock *held_, *temp_;
  2290. public:
  2291. inline explicit LockInverter(SpinLock* held, SpinLock *temp)
  2292. : held_(held), temp_(temp) { held_->Unlock(); temp_->Lock(); }
  2293. inline ~LockInverter() { temp_->Unlock(); held_->Lock(); }
  2294. };
  2295. }
  2296. bool TCMalloc_Central_FreeList::ShrinkCache(int locked_size_class, bool force) {
  2297. // Start with a quick check without taking a lock.
  2298. if (cache_size_ == 0) return false;
  2299. // We don't evict from a full cache unless we are 'forcing'.
  2300. if (force == false && used_slots_ == cache_size_) return false;
  2301. // Grab lock, but first release the other lock held by this thread. We use
  2302. // the lock inverter to ensure that we never hold two size class locks
  2303. // concurrently. That can create a deadlock because there is no well
  2304. // defined nesting order.
  2305. LockInverter li(&central_cache[locked_size_class].lock_, &lock_);
  2306. ASSERT(used_slots_ <= cache_size_);
  2307. ASSERT(0 <= cache_size_);
  2308. if (cache_size_ == 0) return false;
  2309. if (used_slots_ == cache_size_) {
  2310. if (force == false) return false;
  2311. // ReleaseListToSpans releases the lock, so we have to make all the
  2312. // updates to the central list before calling it.
  2313. cache_size_--;
  2314. used_slots_--;
  2315. ReleaseListToSpans(tc_slots_[used_slots_].head);
  2316. return true;
  2317. }
  2318. cache_size_--;
  2319. return true;
  2320. }
  2321. void TCMalloc_Central_FreeList::InsertRange(void *start, void *end, int N) {
  2322. SpinLockHolder h(&lock_);
  2323. if (N == num_objects_to_move[size_class_] &&
  2324. MakeCacheSpace()) {
  2325. int slot = used_slots_++;
  2326. ASSERT(slot >=0);
  2327. ASSERT(slot < kNumTransferEntries);
  2328. TCEntry *entry = &tc_slots_[slot];
  2329. entry->head = start;
  2330. entry->tail = end;
  2331. return;
  2332. }
  2333. ReleaseListToSpans(start);
  2334. }
  2335. void TCMalloc_Central_FreeList::RemoveRange(void **start, void **end, int *N) {
  2336. int num = *N;
  2337. ASSERT(num > 0);
  2338. SpinLockHolder h(&lock_);
  2339. if (num == num_objects_to_move[size_class_] && used_slots_ > 0) {
  2340. int slot = --used_slots_;
  2341. ASSERT(slot >= 0);
  2342. TCEntry *entry = &tc_slots_[slot];
  2343. *start = entry->head;
  2344. *end = entry->tail;
  2345. return;
  2346. }
  2347. // TODO: Prefetch multiple TCEntries?
  2348. void *tail = FetchFromSpansSafe();
  2349. if (!tail) {
  2350. // We are completely out of memory.
  2351. *start = *end = NULL;
  2352. *N = 0;
  2353. return;
  2354. }
  2355. SLL_SetNext(tail, NULL);
  2356. void *head = tail;
  2357. int count = 1;
  2358. while (count < num) {
  2359. void *t = FetchFromSpans();
  2360. if (!t) break;
  2361. SLL_Push(&head, t);
  2362. count++;
  2363. }
  2364. *start = head;
  2365. *end = tail;
  2366. *N = count;
  2367. }
  2368. void* TCMalloc_Central_FreeList::FetchFromSpansSafe() {
  2369. void *t = FetchFromSpans();
  2370. if (!t) {
  2371. Populate();
  2372. t = FetchFromSpans();
  2373. }
  2374. return t;
  2375. }
  2376. void* TCMalloc_Central_FreeList::FetchFromSpans() {
  2377. if (DLL_IsEmpty(&nonempty_)) return NULL;
  2378. Span* span = nonempty_.next;
  2379. ASSERT(span->objects != NULL);
  2380. ASSERT_SPAN_COMMITTED(span);
  2381. span->refcount++;
  2382. void* result = span->objects;
  2383. span->objects = *(reinterpret_cast<void**>(result));
  2384. if (span->objects == NULL) {
  2385. // Move to empty list
  2386. DLL_Remove(span);
  2387. DLL_Prepend(&empty_, span);
  2388. Event(span, 'E', 0);
  2389. }
  2390. counter_--;
  2391. return result;
  2392. }
  2393. // Fetch memory from the system and add to the central cache freelist.
  2394. ALWAYS_INLINE void TCMalloc_Central_FreeList::Populate() {
  2395. // Release central list lock while operating on pageheap
  2396. lock_.Unlock();
  2397. const size_t npages = class_to_pages[size_class_];
  2398. Span* span;
  2399. {
  2400. SpinLockHolder h(&pageheap_lock);
  2401. span = pageheap->New(npages);
  2402. if (span) pageheap->RegisterSizeClass(span, size_class_);
  2403. }
  2404. if (span == NULL) {
  2405. #if HAVE(ERRNO_H)
  2406. MESSAGE("allocation failed: %d\n", errno);
  2407. #elif OS(WINDOWS)
  2408. MESSAGE("allocation failed: %d\n", ::GetLastError());
  2409. #else
  2410. MESSAGE("allocation failed\n");
  2411. #endif
  2412. lock_.Lock();
  2413. return;
  2414. }
  2415. ASSERT_SPAN_COMMITTED(span);
  2416. ASSERT(span->length == npages);
  2417. // Cache sizeclass info eagerly. Locking is not necessary.
  2418. // (Instead of being eager, we could just replace any stale info
  2419. // about this span, but that seems to be no better in practice.)
  2420. for (size_t i = 0; i < npages; i++) {
  2421. pageheap->CacheSizeClass(span->start + i, size_class_);
  2422. }
  2423. // Split the block into pieces and add to the free-list
  2424. // TODO: coloring of objects to avoid cache conflicts?
  2425. void** tail = &span->objects;
  2426. char* ptr = reinterpret_cast<char*>(span->start << kPageShift);
  2427. char* limit = ptr + (npages << kPageShift);
  2428. const size_t size = ByteSizeForClass(size_class_);
  2429. int num = 0;
  2430. char* nptr;
  2431. while ((nptr = ptr + size) <= limit) {
  2432. *tail = ptr;
  2433. tail = reinterpret_cast_ptr<void**>(ptr);
  2434. ptr = nptr;
  2435. num++;
  2436. }
  2437. ASSERT(ptr <= limit);
  2438. *tail = NULL;
  2439. span->refcount = 0; // No sub-object in use yet
  2440. // Add span to list of non-empty spans
  2441. lock_.Lock();
  2442. DLL_Prepend(&nonempty_, span);
  2443. counter_ += num;
  2444. }
  2445. //-------------------------------------------------------------------
  2446. // TCMalloc_ThreadCache implementation
  2447. //-------------------------------------------------------------------
  2448. inline bool TCMalloc_ThreadCache::SampleAllocation(size_t k) {
  2449. if (bytes_until_sample_ < k) {
  2450. PickNextSample(k);
  2451. return true;
  2452. } else {
  2453. bytes_until_sample_ -= k;
  2454. return false;
  2455. }
  2456. }
  2457. void TCMalloc_ThreadCache::Init(ThreadIdentifier tid) {
  2458. size_ = 0;
  2459. next_ = NULL;
  2460. prev_ = NULL;
  2461. tid_ = tid;
  2462. in_setspecific_ = false;
  2463. for (size_t cl = 0; cl < kNumClasses; ++cl) {
  2464. list_[cl].Init();
  2465. }
  2466. // Initialize RNG -- run it for a bit to get to good values
  2467. bytes_until_sample_ = 0;
  2468. rnd_ = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(this));
  2469. for (int i = 0; i < 100; i++) {
  2470. PickNextSample(static_cast<size_t>(FLAGS_tcmalloc_sample_parameter * 2));
  2471. }
  2472. }
  2473. void TCMalloc_ThreadCache::Cleanup() {
  2474. // Put unused memory back into central cache
  2475. for (size_t cl = 0; cl < kNumClasses; ++cl) {
  2476. if (list_[cl].length() > 0) {
  2477. ReleaseToCentralCache(cl, list_[cl].length());
  2478. }
  2479. }
  2480. }
  2481. ALWAYS_INLINE void* TCMalloc_ThreadCache::Allocate(size_t size) {
  2482. ASSERT(size <= kMaxSize);
  2483. const size_t cl = SizeClass(size);
  2484. FreeList* list = &list_[cl];
  2485. size_t allocationSize = ByteSizeForClass(cl);
  2486. if (list->empty()) {
  2487. FetchFromCentralCache(cl, allocationSize);
  2488. if (list->empty()) return NULL;
  2489. }
  2490. size_ -= allocationSize;
  2491. return list->Pop();
  2492. }
  2493. inline void TCMalloc_ThreadCache::Deallocate(void* ptr, size_t cl) {
  2494. size_ += ByteSizeForClass(cl);
  2495. FreeList* list = &list_[cl];
  2496. list->Push(ptr);
  2497. // If enough data is free, put back into central cache
  2498. if (list->length() > kMaxFreeListLength) {
  2499. ReleaseToCentralCache(cl, num_objects_to_move[cl]);
  2500. }
  2501. if (size_ >= per_thread_cache_size) Scavenge();
  2502. }
  2503. // Remove some objects of class "cl" from central cache and add to thread heap
  2504. ALWAYS_INLINE void TCMalloc_ThreadCache::FetchFromCentralCache(size_t cl, size_t allocationSize) {
  2505. int fetch_count = num_objects_to_move[cl];
  2506. void *start, *end;
  2507. central_cache[cl].RemoveRange(&start, &end, &fetch_count);
  2508. list_[cl].PushRange(fetch_count, start, end);
  2509. size_ += allocationSize * fetch_count;
  2510. }
  2511. // Remove some objects of class "cl" from thread heap and add to central cache
  2512. inline void TCMalloc_ThreadCache::ReleaseToCentralCache(size_t cl, int N) {
  2513. ASSERT(N > 0);
  2514. FreeList* src = &list_[cl];
  2515. if (N > src->length()) N = src->length();
  2516. size_ -= N*ByteSizeForClass(cl);
  2517. // We return prepackaged chains of the correct size to the central cache.
  2518. // TODO: Use the same format internally in the thread caches?
  2519. int batch_size = num_objects_to_move[cl];
  2520. while (N > batch_size) {
  2521. void *tail, *head;
  2522. src->PopRange(batch_size, &head, &tail);
  2523. central_cache[cl].InsertRange(head, tail, batch_size);
  2524. N -= batch_size;
  2525. }
  2526. void *tail, *head;
  2527. src->PopRange(N, &head, &tail);
  2528. central_cache[cl].InsertRange(head, tail, N);
  2529. }
  2530. // Release idle memory to the central cache
  2531. inline void TCMalloc_ThreadCache::Scavenge() {
  2532. // If the low-water mark for the free list is L, it means we would
  2533. // not have had to allocate anything from the central cache even if
  2534. // we had reduced the free list size by L. We aim to get closer to
  2535. // that situation by dropping L/2 nodes from the free list. This
  2536. // may not release much memory, but if so we will call scavenge again
  2537. // pretty soon and the low-water marks will be high on that call.
  2538. //int64 start = CycleClock::Now();
  2539. for (size_t cl = 0; cl < kNumClasses; cl++) {
  2540. FreeList* list = &list_[cl];
  2541. const int lowmark = list->lowwatermark();
  2542. if (lowmark > 0) {
  2543. const int drop = (lowmark > 1) ? lowmark/2 : 1;
  2544. ReleaseToCentralCache(cl, drop);
  2545. }
  2546. list->clear_lowwatermark();
  2547. }
  2548. //int64 finish = CycleClock::Now();
  2549. //CycleTimer ct;
  2550. //MESSAGE("GC: %.0f ns\n", ct.CyclesToUsec(finish-start)*1000.0);
  2551. }
  2552. void TCMalloc_ThreadCache::PickNextSample(size_t k) {
  2553. // Make next "random" number
  2554. // x^32+x^22+x^2+x^1+1 is a primitive polynomial for random numbers
  2555. static const uint32_t kPoly = (1 << 22) | (1 << 2) | (1 << 1) | (1 << 0);
  2556. uint32_t r = rnd_;
  2557. rnd_ = (r << 1) ^ ((static_cast<int32_t>(r) >> 31) & kPoly);
  2558. // Next point is "rnd_ % (sample_period)". I.e., average
  2559. // increment is "sample_period/2".
  2560. const int flag_value = static_cast<int>(FLAGS_tcmalloc_sample_parameter);
  2561. static int last_flag_value = -1;
  2562. if (flag_value != last_flag_value) {
  2563. SpinLockHolder h(&sample_period_lock);
  2564. int i;
  2565. for (i = 0; i < (static_cast<int>(sizeof(primes_list)/sizeof(primes_list[0])) - 1); i++) {
  2566. if (primes_list[i] >= flag_value) {
  2567. break;
  2568. }
  2569. }
  2570. sample_period = primes_list[i];
  2571. last_flag_value = flag_value;
  2572. }
  2573. bytes_until_sample_ += rnd_ % sample_period;
  2574. if (k > (static_cast<size_t>(-1) >> 2)) {
  2575. // If the user has asked for a huge allocation then it is possible
  2576. // for the code below to loop infinitely. Just return (note that
  2577. // this throws off the sampling accuracy somewhat, but a user who
  2578. // is allocating more than 1G of memory at a time can live with a
  2579. // minor inaccuracy in profiling of small allocations, and also
  2580. // would rather not wait for the loop below to terminate).
  2581. return;
  2582. }
  2583. while (bytes_until_sample_ < k) {
  2584. // Increase bytes_until_sample_ by enough average sampling periods
  2585. // (sample_period >> 1) to allow us to sample past the current
  2586. // allocation.
  2587. bytes_until_sample_ += (sample_period >> 1);
  2588. }
  2589. bytes_until_sample_ -= k;
  2590. }
  2591. void TCMalloc_ThreadCache::InitModule() {
  2592. // There is a slight potential race here because of double-checked
  2593. // locking idiom. However, as long as the program does a small
  2594. // allocation before switching to multi-threaded mode, we will be
  2595. // fine. We increase the chances of doing such a small allocation
  2596. // by doing one in the constructor of the module_enter_exit_hook
  2597. // object declared below.
  2598. SpinLockHolder h(&pageheap_lock);
  2599. if (!phinited) {
  2600. #ifdef WTF_CHANGES
  2601. InitTSD();
  2602. #endif
  2603. InitSizeClasses();
  2604. threadheap_allocator.Init();
  2605. span_allocator.Init();
  2606. span_allocator.New(); // Reduce cache conflicts
  2607. span_allocator.New(); // Reduce cache conflicts
  2608. stacktrace_allocator.Init();
  2609. DLL_Init(&sampled_objects);
  2610. for (size_t i = 0; i < kNumClasses; ++i) {
  2611. central_cache[i].Init(i);
  2612. }
  2613. pageheap->init();
  2614. phinited = 1;
  2615. #if defined(WTF_CHANGES) && OS(DARWIN)
  2616. FastMallocZone::init();
  2617. #endif
  2618. }
  2619. }
  2620. inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::NewHeap(ThreadIdentifier tid) {
  2621. // Create the heap and add it to the linked list
  2622. TCMalloc_ThreadCache *heap = threadheap_allocator.New();
  2623. heap->Init(tid);
  2624. heap->next_ = thread_heaps;
  2625. heap->prev_ = NULL;
  2626. if (thread_heaps != NULL) thread_heaps->prev_ = heap;
  2627. thread_heaps = heap;
  2628. thread_heap_count++;
  2629. RecomputeThreadCacheSize();
  2630. return heap;
  2631. }
  2632. inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetThreadHeap() {
  2633. #ifdef HAVE_TLS
  2634. // __thread is faster, but only when the kernel supports it
  2635. if (KernelSupportsTLS())
  2636. return threadlocal_heap;
  2637. #elif OS(WINDOWS)
  2638. return static_cast<TCMalloc_ThreadCache*>(TlsGetValue(tlsIndex));
  2639. #else
  2640. return static_cast<TCMalloc_ThreadCache*>(pthread_getspecific(heap_key));
  2641. #endif
  2642. }
  2643. inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetCache() {
  2644. TCMalloc_ThreadCache* ptr = NULL;
  2645. if (!tsd_inited) {
  2646. InitModule();
  2647. } else {
  2648. ptr = GetThreadHeap();
  2649. }
  2650. if (ptr == NULL) ptr = CreateCacheIfNecessary();
  2651. return ptr;
  2652. }
  2653. // In deletion paths, we do not try to create a thread-cache. This is
  2654. // because we may be in the thread destruction code and may have
  2655. // already cleaned up the cache for this thread.
  2656. inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetCacheIfPresent() {
  2657. if (!tsd_inited) return NULL;
  2658. void* const p = GetThreadHeap();
  2659. return reinterpret_cast<TCMalloc_ThreadCache*>(p);
  2660. }
  2661. void TCMalloc_ThreadCache::InitTSD() {
  2662. ASSERT(!tsd_inited);
  2663. #if USE(PTHREAD_GETSPECIFIC_DIRECT)
  2664. pthread_key_init_np(heap_key, DestroyThreadCache);
  2665. #else
  2666. pthread_key_create(&heap_key, DestroyThreadCache);
  2667. #endif
  2668. #if OS(WINDOWS)
  2669. tlsIndex = TlsAlloc();
  2670. #endif
  2671. tsd_inited = true;
  2672. #if !OS(WINDOWS)
  2673. // We may have used a fake pthread_t for the main thread. Fix it.
  2674. pthread_t zero;
  2675. memset(&zero, 0, sizeof(zero));
  2676. #endif
  2677. #ifndef WTF_CHANGES
  2678. SpinLockHolder h(&pageheap_lock);
  2679. #else
  2680. ASSERT(pageheap_lock.IsHeld());
  2681. #endif
  2682. for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
  2683. #if OS(WINDOWS)
  2684. if (h->tid_ == 0) {
  2685. h->tid_ = GetCurrentThreadId();
  2686. }
  2687. #else
  2688. if (pthread_equal(h->tid_, zero)) {
  2689. h->tid_ = pthread_self();
  2690. }
  2691. #endif
  2692. }
  2693. }
  2694. TCMalloc_ThreadCache* TCMalloc_ThreadCache::CreateCacheIfNecessary() {
  2695. // Initialize per-thread data if necessary
  2696. TCMalloc_ThreadCache* heap = NULL;
  2697. {
  2698. SpinLockHolder h(&pageheap_lock);
  2699. #if OS(WINDOWS)
  2700. DWORD me;
  2701. if (!tsd_inited) {
  2702. me = 0;
  2703. } else {
  2704. me = GetCurrentThreadId();
  2705. }
  2706. #else
  2707. // Early on in glibc's life, we cannot even call pthread_self()
  2708. pthread_t me;
  2709. if (!tsd_inited) {
  2710. memset(&me, 0, sizeof(me));
  2711. } else {
  2712. me = pthread_self();
  2713. }
  2714. #endif
  2715. // This may be a recursive malloc call from pthread_setspecific()
  2716. // In that case, the heap for this thread has already been created
  2717. // and added to the linked list. So we search for that first.
  2718. for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
  2719. #if OS(WINDOWS)
  2720. if (h->tid_ == me) {
  2721. #else
  2722. if (pthread_equal(h->tid_, me)) {
  2723. #endif
  2724. heap = h;
  2725. break;
  2726. }
  2727. }
  2728. if (heap == NULL) heap = NewHeap(me);
  2729. }
  2730. // We call pthread_setspecific() outside the lock because it may
  2731. // call malloc() recursively. The recursive call will never get
  2732. // here again because it will find the already allocated heap in the
  2733. // linked list of heaps.
  2734. if (!heap->in_setspecific_ && tsd_inited) {
  2735. heap->in_setspecific_ = true;
  2736. setThreadHeap(heap);
  2737. }
  2738. return heap;
  2739. }
  2740. void TCMalloc_ThreadCache::BecomeIdle() {
  2741. if (!tsd_inited) return; // No caches yet
  2742. TCMalloc_ThreadCache* heap = GetThreadHeap();
  2743. if (heap == NULL) return; // No thread cache to remove
  2744. if (heap->in_setspecific_) return; // Do not disturb the active caller
  2745. heap->in_setspecific_ = true;
  2746. setThreadHeap(NULL);
  2747. #ifdef HAVE_TLS
  2748. // Also update the copy in __thread
  2749. threadlocal_heap = NULL;
  2750. #endif
  2751. heap->in_setspecific_ = false;
  2752. if (GetThreadHeap() == heap) {
  2753. // Somehow heap got reinstated by a recursive call to malloc
  2754. // from pthread_setspecific. We give up in this case.
  2755. return;
  2756. }
  2757. // We can now get rid of the heap
  2758. DeleteCache(heap);
  2759. }
  2760. void TCMalloc_ThreadCache::DestroyThreadCache(void* ptr) {
  2761. // Note that "ptr" cannot be NULL since pthread promises not
  2762. // to invoke the destructor on NULL values, but for safety,
  2763. // we check anyway.
  2764. if (ptr == NULL) return;
  2765. #ifdef HAVE_TLS
  2766. // Prevent fast path of GetThreadHeap() from returning heap.
  2767. threadlocal_heap = NULL;
  2768. #endif
  2769. DeleteCache(reinterpret_cast<TCMalloc_ThreadCache*>(ptr));
  2770. }
  2771. void TCMalloc_ThreadCache::DeleteCache(TCMalloc_ThreadCache* heap) {
  2772. // Remove all memory from heap
  2773. heap->Cleanup();
  2774. // Remove from linked list
  2775. SpinLockHolder h(&pageheap_lock);
  2776. if (heap->next_ != NULL) heap->next_->prev_ = heap->prev_;
  2777. if (heap->prev_ != NULL) heap->prev_->next_ = heap->next_;
  2778. if (thread_heaps == heap) thread_heaps = heap->next_;
  2779. thread_heap_count--;
  2780. RecomputeThreadCacheSize();
  2781. threadheap_allocator.Delete(heap);
  2782. }
  2783. void TCMalloc_ThreadCache::RecomputeThreadCacheSize() {
  2784. // Divide available space across threads
  2785. int n = thread_heap_count > 0 ? thread_heap_count : 1;
  2786. size_t space = overall_thread_cache_size / n;
  2787. // Limit to allowed range
  2788. if (space < kMinThreadCacheSize) space = kMinThreadCacheSize;
  2789. if (space > kMaxThreadCacheSize) space = kMaxThreadCacheSize;
  2790. per_thread_cache_size = space;
  2791. }
  2792. void TCMalloc_ThreadCache::Print() const {
  2793. for (size_t cl = 0; cl < kNumClasses; ++cl) {
  2794. MESSAGE(" %5" PRIuS " : %4d len; %4d lo\n",
  2795. ByteSizeForClass(cl),
  2796. list_[cl].length(),
  2797. list_[cl].lowwatermark());
  2798. }
  2799. }
  2800. // Extract interesting stats
  2801. struct TCMallocStats {
  2802. uint64_t system_bytes; // Bytes alloced from system
  2803. uint64_t thread_bytes; // Bytes in thread caches
  2804. uint64_t central_bytes; // Bytes in central cache
  2805. uint64_t transfer_bytes; // Bytes in central transfer cache
  2806. uint64_t pageheap_bytes; // Bytes in page heap
  2807. uint64_t metadata_bytes; // Bytes alloced for metadata
  2808. };
  2809. #ifndef WTF_CHANGES
  2810. // Get stats into "r". Also get per-size-class counts if class_count != NULL
  2811. static void ExtractStats(TCMallocStats* r, uint64_t* class_count) {
  2812. r->central_bytes = 0;
  2813. r->transfer_bytes = 0;
  2814. for (int cl = 0; cl < kNumClasses; ++cl) {
  2815. const int length = central_cache[cl].length();
  2816. const int tc_length = central_cache[cl].tc_length();
  2817. r->central_bytes += static_cast<uint64_t>(ByteSizeForClass(cl)) * length;
  2818. r->transfer_bytes +=
  2819. static_cast<uint64_t>(ByteSizeForClass(cl)) * tc_length;
  2820. if (class_count) class_count[cl] = length + tc_length;
  2821. }
  2822. // Add stats from per-thread heaps
  2823. r->thread_bytes = 0;
  2824. { // scope
  2825. SpinLockHolder h(&pageheap_lock);
  2826. for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
  2827. r->thread_bytes += h->Size();
  2828. if (class_count) {
  2829. for (size_t cl = 0; cl < kNumClasses; ++cl) {
  2830. class_count[cl] += h->freelist_length(cl);
  2831. }
  2832. }
  2833. }
  2834. }
  2835. { //scope
  2836. SpinLockHolder h(&pageheap_lock);
  2837. r->system_bytes = pageheap->SystemBytes();
  2838. r->metadata_bytes = metadata_system_bytes;
  2839. r->pageheap_bytes = pageheap->FreeBytes();
  2840. }
  2841. }
  2842. #endif
  2843. #ifndef WTF_CHANGES
  2844. // WRITE stats to "out"
  2845. static void DumpStats(TCMalloc_Printer* out, int level) {
  2846. TCMallocStats stats;
  2847. uint64_t class_count[kNumClasses];
  2848. ExtractStats(&stats, (level >= 2 ? class_count : NULL));
  2849. if (level >= 2) {
  2850. out->printf("------------------------------------------------\n");
  2851. uint64_t cumulative = 0;
  2852. for (int cl = 0; cl < kNumClasses; ++cl) {
  2853. if (class_count[cl] > 0) {
  2854. uint64_t class_bytes = class_count[cl] * ByteSizeForClass(cl);
  2855. cumulative += class_bytes;
  2856. out->printf("class %3d [ %8" PRIuS " bytes ] : "
  2857. "%8" PRIu64 " objs; %5.1f MB; %5.1f cum MB\n",
  2858. cl, ByteSizeForClass(cl),
  2859. class_count[cl],
  2860. class_bytes / 1048576.0,
  2861. cumulative / 1048576.0);
  2862. }
  2863. }
  2864. SpinLockHolder h(&pageheap_lock);
  2865. pageheap->Dump(out);
  2866. }
  2867. const uint64_t bytes_in_use = stats.system_bytes
  2868. - stats.pageheap_bytes
  2869. - stats.central_bytes
  2870. - stats.transfer_bytes
  2871. - stats.thread_bytes;
  2872. out->printf("------------------------------------------------\n"
  2873. "MALLOC: %12" PRIu64 " Heap size\n"
  2874. "MALLOC: %12" PRIu64 " Bytes in use by application\n"
  2875. "MALLOC: %12" PRIu64 " Bytes free in page heap\n"
  2876. "MALLOC: %12" PRIu64 " Bytes free in central cache\n"
  2877. "MALLOC: %12" PRIu64 " Bytes free in transfer cache\n"
  2878. "MALLOC: %12" PRIu64 " Bytes free in thread caches\n"
  2879. "MALLOC: %12" PRIu64 " Spans in use\n"
  2880. "MALLOC: %12" PRIu64 " Thread heaps in use\n"
  2881. "MALLOC: %12" PRIu64 " Metadata allocated\n"
  2882. "------------------------------------------------\n",
  2883. stats.system_bytes,
  2884. bytes_in_use,
  2885. stats.pageheap_bytes,
  2886. stats.central_bytes,
  2887. stats.transfer_bytes,
  2888. stats.thread_bytes,
  2889. uint64_t(span_allocator.inuse()),
  2890. uint64_t(threadheap_allocator.inuse()),
  2891. stats.metadata_bytes);
  2892. }
  2893. static void PrintStats(int level) {
  2894. const int kBufferSize = 16 << 10;
  2895. char* buffer = new char[kBufferSize];
  2896. TCMalloc_Printer printer(buffer, kBufferSize);
  2897. DumpStats(&printer, level);
  2898. write(STDERR_FILENO, buffer, strlen(buffer));
  2899. delete[] buffer;
  2900. }
  2901. static void** DumpStackTraces() {
  2902. // Count how much space we need
  2903. int needed_slots = 0;
  2904. {
  2905. SpinLockHolder h(&pageheap_lock);
  2906. for (Span* s = sampled_objects.next; s != &sampled_objects; s = s->next) {
  2907. StackTrace* stack = reinterpret_cast<StackTrace*>(s->objects);
  2908. needed_slots += 3 + stack->depth;
  2909. }
  2910. needed_slots += 100; // Slop in case sample grows
  2911. needed_slots += needed_slots/8; // An extra 12.5% slop
  2912. }
  2913. void** result = new void*[needed_slots];
  2914. if (result == NULL) {
  2915. MESSAGE("tcmalloc: could not allocate %d slots for stack traces\n",
  2916. needed_slots);
  2917. return NULL;
  2918. }
  2919. SpinLockHolder h(&pageheap_lock);
  2920. int used_slots = 0;
  2921. for (Span* s = sampled_objects.next; s != &sampled_objects; s = s->next) {
  2922. ASSERT(used_slots < needed_slots); // Need to leave room for terminator
  2923. StackTrace* stack = reinterpret_cast<StackTrace*>(s->objects);
  2924. if (used_slots + 3 + stack->depth >= needed_slots) {
  2925. // No more room
  2926. break;
  2927. }
  2928. result[used_slots+0] = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
  2929. result[used_slots+1] = reinterpret_cast<void*>(stack->size);
  2930. result[used_slots+2] = reinterpret_cast<void*>(stack->depth);
  2931. for (int d = 0; d < stack->depth; d++) {
  2932. result[used_slots+3+d] = stack->stack[d];
  2933. }
  2934. used_slots += 3 + stack->depth;
  2935. }
  2936. result[used_slots] = reinterpret_cast<void*>(static_cast<uintptr_t>(0));
  2937. return result;
  2938. }
  2939. #endif
  2940. #ifndef WTF_CHANGES
  2941. // TCMalloc's support for extra malloc interfaces
  2942. class TCMallocImplementation : public MallocExtension {
  2943. public:
  2944. virtual void GetStats(char* buffer, int buffer_length) {
  2945. ASSERT(buffer_length > 0);
  2946. TCMalloc_Printer printer(buffer, buffer_length);
  2947. // Print level one stats unless lots of space is available
  2948. if (buffer_length < 10000) {
  2949. DumpStats(&printer, 1);
  2950. } else {
  2951. DumpStats(&printer, 2);
  2952. }
  2953. }
  2954. virtual void** ReadStackTraces() {
  2955. return DumpStackTraces();
  2956. }
  2957. virtual bool GetNumericProperty(const char* name, size_t* value) {
  2958. ASSERT(name != NULL);
  2959. if (strcmp(name, "generic.current_allocated_bytes") == 0) {
  2960. TCMallocStats stats;
  2961. ExtractStats(&stats, NULL);
  2962. *value = stats.system_bytes
  2963. - stats.thread_bytes
  2964. - stats.central_bytes
  2965. - stats.pageheap_bytes;
  2966. return true;
  2967. }
  2968. if (strcmp(name, "generic.heap_size") == 0) {
  2969. TCMallocStats stats;
  2970. ExtractStats(&stats, NULL);
  2971. *value = stats.system_bytes;
  2972. return true;
  2973. }
  2974. if (strcmp(name, "tcmalloc.slack_bytes") == 0) {
  2975. // We assume that bytes in the page heap are not fragmented too
  2976. // badly, and are therefore available for allocation.
  2977. SpinLockHolder l(&pageheap_lock);
  2978. *value = pageheap->FreeBytes();
  2979. return true;
  2980. }
  2981. if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
  2982. SpinLockHolder l(&pageheap_lock);
  2983. *value = overall_thread_cache_size;
  2984. return true;
  2985. }
  2986. if (strcmp(name, "tcmalloc.current_total_thread_cache_bytes") == 0) {
  2987. TCMallocStats stats;
  2988. ExtractStats(&stats, NULL);
  2989. *value = stats.thread_bytes;
  2990. return true;
  2991. }
  2992. return false;
  2993. }
  2994. virtual bool SetNumericProperty(const char* name, size_t value) {
  2995. ASSERT(name != NULL);
  2996. if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
  2997. // Clip the value to a reasonable range
  2998. if (value < kMinThreadCacheSize) value = kMinThreadCacheSize;
  2999. if (value > (1<<30)) value = (1<<30); // Limit to 1GB
  3000. SpinLockHolder l(&pageheap_lock);
  3001. overall_thread_cache_size = static_cast<size_t>(value);
  3002. TCMalloc_ThreadCache::RecomputeThreadCacheSize();
  3003. return true;
  3004. }
  3005. return false;
  3006. }
  3007. virtual void MarkThreadIdle() {
  3008. TCMalloc_ThreadCache::BecomeIdle();
  3009. }
  3010. virtual void ReleaseFreeMemory() {
  3011. SpinLockHolder h(&pageheap_lock);
  3012. pageheap->ReleaseFreePages();
  3013. }
  3014. };
  3015. #endif
  3016. // The constructor allocates an object to ensure that initialization
  3017. // runs before main(), and therefore we do not have a chance to become
  3018. // multi-threaded before initialization. We also create the TSD key
  3019. // here. Presumably by the time this constructor runs, glibc is in
  3020. // good enough shape to handle pthread_key_create().
  3021. //
  3022. // The constructor also takes the opportunity to tell STL to use
  3023. // tcmalloc. We want to do this early, before construct time, so
  3024. // all user STL allocations go through tcmalloc (which works really
  3025. // well for STL).
  3026. //
  3027. // The destructor prints stats when the program exits.
  3028. class TCMallocGuard {
  3029. public:
  3030. TCMallocGuard() {
  3031. #ifdef HAVE_TLS // this is true if the cc/ld/libc combo support TLS
  3032. // Check whether the kernel also supports TLS (needs to happen at runtime)
  3033. CheckIfKernelSupportsTLS();
  3034. #endif
  3035. #ifndef WTF_CHANGES
  3036. #ifdef WIN32 // patch the windows VirtualAlloc, etc.
  3037. PatchWindowsFunctions(); // defined in windows/patch_functions.cc
  3038. #endif
  3039. #endif
  3040. free(malloc(1));
  3041. TCMalloc_ThreadCache::InitTSD();
  3042. free(malloc(1));
  3043. #ifndef WTF_CHANGES
  3044. MallocExtension::Register(new TCMallocImplementation);
  3045. #endif
  3046. }
  3047. #ifndef WTF_CHANGES
  3048. ~TCMallocGuard() {
  3049. const char* env = getenv("MALLOCSTATS");
  3050. if (env != NULL) {
  3051. int level = atoi(env);
  3052. if (level < 1) level = 1;
  3053. PrintStats(level);
  3054. }
  3055. #ifdef WIN32
  3056. UnpatchWindowsFunctions();
  3057. #endif
  3058. }
  3059. #endif
  3060. };
  3061. #ifndef WTF_CHANGES
  3062. static TCMallocGuard module_enter_exit_hook;
  3063. #endif
  3064. //-------------------------------------------------------------------
  3065. // Helpers for the exported routines below
  3066. //-------------------------------------------------------------------
  3067. #ifndef WTF_CHANGES
  3068. static Span* DoSampledAllocation(size_t size) {
  3069. // Grab the stack trace outside the heap lock
  3070. StackTrace tmp;
  3071. tmp.depth = GetStackTrace(tmp.stack, kMaxStackDepth, 1);
  3072. tmp.size = size;
  3073. SpinLockHolder h(&pageheap_lock);
  3074. // Allocate span
  3075. Span *span = pageheap->New(pages(size == 0 ? 1 : size));
  3076. if (span == NULL) {
  3077. return NULL;
  3078. }
  3079. // Allocate stack trace
  3080. StackTrace *stack = stacktrace_allocator.New();
  3081. if (stack == NULL) {
  3082. // Sampling failed because of lack of memory
  3083. return span;
  3084. }
  3085. *stack = tmp;
  3086. span->sample = 1;
  3087. span->objects = stack;
  3088. DLL_Prepend(&sampled_objects, span);
  3089. return span;
  3090. }
  3091. #endif
  3092. static inline bool CheckCachedSizeClass(void *ptr) {
  3093. PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
  3094. size_t cached_value = pageheap->GetSizeClassIfCached(p);
  3095. return cached_value == 0 ||
  3096. cached_value == pageheap->GetDescriptor(p)->sizeclass;
  3097. }
  3098. static inline void* CheckedMallocResult(void *result)
  3099. {
  3100. ASSERT(result == 0 || CheckCachedSizeClass(result));
  3101. return result;
  3102. }
  3103. static inline void* SpanToMallocResult(Span *span) {
  3104. ASSERT_SPAN_COMMITTED(span);
  3105. pageheap->CacheSizeClass(span->start, 0);
  3106. return
  3107. CheckedMallocResult(reinterpret_cast<void*>(span->start << kPageShift));
  3108. }
  3109. #ifdef WTF_CHANGES
  3110. template <bool crashOnFailure>
  3111. #endif
  3112. static ALWAYS_INLINE void* do_malloc(size_t size) {
  3113. void* ret = NULL;
  3114. #ifdef WTF_CHANGES
  3115. ASSERT(!isForbidden());
  3116. #endif
  3117. // The following call forces module initialization
  3118. TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCache();
  3119. #ifndef WTF_CHANGES
  3120. if ((FLAGS_tcmalloc_sample_parameter > 0) && heap->SampleAllocation(size)) {
  3121. Span* span = DoSampledAllocation(size);
  3122. if (span != NULL) {
  3123. ret = SpanToMallocResult(span);
  3124. }
  3125. } else
  3126. #endif
  3127. if (size > kMaxSize) {
  3128. // Use page-level allocator
  3129. SpinLockHolder h(&pageheap_lock);
  3130. Span* span = pageheap->New(pages(size));
  3131. if (span != NULL) {
  3132. ret = SpanToMallocResult(span);
  3133. }
  3134. } else {
  3135. // The common case, and also the simplest. This just pops the
  3136. // size-appropriate freelist, afer replenishing it if it's empty.
  3137. ret = CheckedMallocResult(heap->Allocate(size));
  3138. }
  3139. if (!ret) {
  3140. #ifdef WTF_CHANGES
  3141. if (crashOnFailure) // This branch should be optimized out by the compiler.
  3142. CRASH();
  3143. #else
  3144. errno = ENOMEM;
  3145. #endif
  3146. }
  3147. return ret;
  3148. }
  3149. static ALWAYS_INLINE void do_free(void* ptr) {
  3150. if (ptr == NULL) return;
  3151. ASSERT(pageheap != NULL); // Should not call free() before malloc()
  3152. const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
  3153. Span* span = NULL;
  3154. size_t cl = pageheap->GetSizeClassIfCached(p);
  3155. if (cl == 0) {
  3156. span = pageheap->GetDescriptor(p);
  3157. cl = span->sizeclass;
  3158. pageheap->CacheSizeClass(p, cl);
  3159. }
  3160. if (cl != 0) {
  3161. #ifndef NO_TCMALLOC_SAMPLES
  3162. ASSERT(!pageheap->GetDescriptor(p)->sample);
  3163. #endif
  3164. TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCacheIfPresent();
  3165. if (heap != NULL) {
  3166. heap->Deallocate(ptr, cl);
  3167. } else {
  3168. // Delete directly into central cache
  3169. SLL_SetNext(ptr, NULL);
  3170. central_cache[cl].InsertRange(ptr, ptr, 1);
  3171. }
  3172. } else {
  3173. SpinLockHolder h(&pageheap_lock);
  3174. ASSERT(reinterpret_cast<uintptr_t>(ptr) % kPageSize == 0);
  3175. ASSERT(span != NULL && span->start == p);
  3176. #ifndef NO_TCMALLOC_SAMPLES
  3177. if (span->sample) {
  3178. DLL_Remove(span);
  3179. stacktrace_allocator.Delete(reinterpret_cast<StackTrace*>(span->objects));
  3180. span->objects = NULL;
  3181. }
  3182. #endif
  3183. pageheap->Delete(span);
  3184. }
  3185. }
  3186. #ifndef WTF_CHANGES
  3187. // For use by exported routines below that want specific alignments
  3188. //
  3189. // Note: this code can be slow, and can significantly fragment memory.
  3190. // The expectation is that memalign/posix_memalign/valloc/pvalloc will
  3191. // not be invoked very often. This requirement simplifies our
  3192. // implementation and allows us to tune for expected allocation
  3193. // patterns.
  3194. static void* do_memalign(size_t align, size_t size) {
  3195. ASSERT((align & (align - 1)) == 0);
  3196. ASSERT(align > 0);
  3197. if (pageheap == NULL) TCMalloc_ThreadCache::InitModule();
  3198. // Allocate at least one byte to avoid boundary conditions below
  3199. if (size == 0) size = 1;
  3200. if (size <= kMaxSize && align < kPageSize) {
  3201. // Search through acceptable size classes looking for one with
  3202. // enough alignment. This depends on the fact that
  3203. // InitSizeClasses() currently produces several size classes that
  3204. // are aligned at powers of two. We will waste time and space if
  3205. // we miss in the size class array, but that is deemed acceptable
  3206. // since memalign() should be used rarely.
  3207. size_t cl = SizeClass(size);
  3208. while (cl < kNumClasses && ((class_to_size[cl] & (align - 1)) != 0)) {
  3209. cl++;
  3210. }
  3211. if (cl < kNumClasses) {
  3212. TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCache();
  3213. return CheckedMallocResult(heap->Allocate(class_to_size[cl]));
  3214. }
  3215. }
  3216. // We will allocate directly from the page heap
  3217. SpinLockHolder h(&pageheap_lock);
  3218. if (align <= kPageSize) {
  3219. // Any page-level allocation will be fine
  3220. // TODO: We could put the rest of this page in the appropriate
  3221. // TODO: cache but it does not seem worth it.
  3222. Span* span = pageheap->New(pages(size));
  3223. return span == NULL ? NULL : SpanToMallocResult(span);
  3224. }
  3225. // Allocate extra pages and carve off an aligned portion
  3226. const Length alloc = pages(size + align);
  3227. Span* span = pageheap->New(alloc);
  3228. if (span == NULL) return NULL;
  3229. // Skip starting portion so that we end up aligned
  3230. Length skip = 0;
  3231. while ((((span->start+skip) << kPageShift) & (align - 1)) != 0) {
  3232. skip++;
  3233. }
  3234. ASSERT(skip < alloc);
  3235. if (skip > 0) {
  3236. Span* rest = pageheap->Split(span, skip);
  3237. pageheap->Delete(span);
  3238. span = rest;
  3239. }
  3240. // Skip trailing portion that we do not need to return
  3241. const Length needed = pages(size);
  3242. ASSERT(span->length >= needed);
  3243. if (span->length > needed) {
  3244. Span* trailer = pageheap->Split(span, needed);
  3245. pageheap->Delete(trailer);
  3246. }
  3247. return SpanToMallocResult(span);
  3248. }
  3249. #endif
  3250. // Helpers for use by exported routines below:
  3251. #ifndef WTF_CHANGES
  3252. static inline void do_malloc_stats() {
  3253. PrintStats(1);
  3254. }
  3255. #endif
  3256. static inline int do_mallopt(int, int) {
  3257. return 1; // Indicates error
  3258. }
  3259. #ifdef HAVE_STRUCT_MALLINFO // mallinfo isn't defined on freebsd, for instance
  3260. static inline struct mallinfo do_mallinfo() {
  3261. TCMallocStats stats;
  3262. ExtractStats(&stats, NULL);
  3263. // Just some of the fields are filled in.
  3264. struct mallinfo info;
  3265. memset(&info, 0, sizeof(info));
  3266. // Unfortunately, the struct contains "int" field, so some of the
  3267. // size values will be truncated.
  3268. info.arena = static_cast<int>(stats.system_bytes);
  3269. info.fsmblks = static_cast<int>(stats.thread_bytes
  3270. + stats.central_bytes
  3271. + stats.transfer_bytes);
  3272. info.fordblks = static_cast<int>(stats.pageheap_bytes);
  3273. info.uordblks = static_cast<int>(stats.system_bytes
  3274. - stats.thread_bytes
  3275. - stats.central_bytes
  3276. - stats.transfer_bytes
  3277. - stats.pageheap_bytes);
  3278. return info;
  3279. }
  3280. #endif
  3281. //-------------------------------------------------------------------
  3282. // Exported routines
  3283. //-------------------------------------------------------------------
  3284. // CAVEAT: The code structure below ensures that MallocHook methods are always
  3285. // called from the stack frame of the invoked allocation function.
  3286. // heap-checker.cc depends on this to start a stack trace from
  3287. // the call to the (de)allocation function.
  3288. #ifndef WTF_CHANGES
  3289. extern "C"
  3290. #else
  3291. #define do_malloc do_malloc<crashOnFailure>
  3292. template <bool crashOnFailure>
  3293. ALWAYS_INLINE void* malloc(size_t);
  3294. void* fastMalloc(size_t size)
  3295. {
  3296. return malloc<true>(size);
  3297. }
  3298. TryMallocReturnValue tryFastMalloc(size_t size)
  3299. {
  3300. return malloc<false>(size);
  3301. }
  3302. template <bool crashOnFailure>
  3303. ALWAYS_INLINE
  3304. #endif
  3305. void* malloc(size_t size) {
  3306. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  3307. if (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= size) // If overflow would occur...
  3308. return 0;
  3309. size += sizeof(AllocAlignmentInteger);
  3310. void* result = do_malloc(size);
  3311. if (!result)
  3312. return 0;
  3313. *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
  3314. result = static_cast<AllocAlignmentInteger*>(result) + 1;
  3315. #else
  3316. void* result = do_malloc(size);
  3317. #endif
  3318. #ifndef WTF_CHANGES
  3319. MallocHook::InvokeNewHook(result, size);
  3320. #endif
  3321. return result;
  3322. }
  3323. #ifndef WTF_CHANGES
  3324. extern "C"
  3325. #endif
  3326. void free(void* ptr) {
  3327. #ifndef WTF_CHANGES
  3328. MallocHook::InvokeDeleteHook(ptr);
  3329. #endif
  3330. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  3331. if (!ptr)
  3332. return;
  3333. AllocAlignmentInteger* header = Internal::fastMallocMatchValidationValue(ptr);
  3334. if (*header != Internal::AllocTypeMalloc)
  3335. Internal::fastMallocMatchFailed(ptr);
  3336. do_free(header);
  3337. #else
  3338. do_free(ptr);
  3339. #endif
  3340. }
  3341. #ifndef WTF_CHANGES
  3342. extern "C"
  3343. #else
  3344. template <bool crashOnFailure>
  3345. ALWAYS_INLINE void* calloc(size_t, size_t);
  3346. void* fastCalloc(size_t n, size_t elem_size)
  3347. {
  3348. return calloc<true>(n, elem_size);
  3349. }
  3350. TryMallocReturnValue tryFastCalloc(size_t n, size_t elem_size)
  3351. {
  3352. return calloc<false>(n, elem_size);
  3353. }
  3354. template <bool crashOnFailure>
  3355. ALWAYS_INLINE
  3356. #endif
  3357. void* calloc(size_t n, size_t elem_size) {
  3358. size_t totalBytes = n * elem_size;
  3359. // Protect against overflow
  3360. if (n > 1 && elem_size && (totalBytes / elem_size) != n)
  3361. return 0;
  3362. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  3363. if (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= totalBytes) // If overflow would occur...
  3364. return 0;
  3365. totalBytes += sizeof(AllocAlignmentInteger);
  3366. void* result = do_malloc(totalBytes);
  3367. if (!result)
  3368. return 0;
  3369. memset(result, 0, totalBytes);
  3370. *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
  3371. result = static_cast<AllocAlignmentInteger*>(result) + 1;
  3372. #else
  3373. void* result = do_malloc(totalBytes);
  3374. if (result != NULL) {
  3375. memset(result, 0, totalBytes);
  3376. }
  3377. #endif
  3378. #ifndef WTF_CHANGES
  3379. MallocHook::InvokeNewHook(result, totalBytes);
  3380. #endif
  3381. return result;
  3382. }
  3383. // Since cfree isn't used anywhere, we don't compile it in.
  3384. #ifndef WTF_CHANGES
  3385. #ifndef WTF_CHANGES
  3386. extern "C"
  3387. #endif
  3388. void cfree(void* ptr) {
  3389. #ifndef WTF_CHANGES
  3390. MallocHook::InvokeDeleteHook(ptr);
  3391. #endif
  3392. do_free(ptr);
  3393. }
  3394. #endif
  3395. #ifndef WTF_CHANGES
  3396. extern "C"
  3397. #else
  3398. template <bool crashOnFailure>
  3399. ALWAYS_INLINE void* realloc(void*, size_t);
  3400. void* fastRealloc(void* old_ptr, size_t new_size)
  3401. {
  3402. return realloc<true>(old_ptr, new_size);
  3403. }
  3404. TryMallocReturnValue tryFastRealloc(void* old_ptr, size_t new_size)
  3405. {
  3406. return realloc<false>(old_ptr, new_size);
  3407. }
  3408. template <bool crashOnFailure>
  3409. ALWAYS_INLINE
  3410. #endif
  3411. void* realloc(void* old_ptr, size_t new_size) {
  3412. if (old_ptr == NULL) {
  3413. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  3414. void* result = malloc(new_size);
  3415. #else
  3416. void* result = do_malloc(new_size);
  3417. #ifndef WTF_CHANGES
  3418. MallocHook::InvokeNewHook(result, new_size);
  3419. #endif
  3420. #endif
  3421. return result;
  3422. }
  3423. if (new_size == 0) {
  3424. #ifndef WTF_CHANGES
  3425. MallocHook::InvokeDeleteHook(old_ptr);
  3426. #endif
  3427. free(old_ptr);
  3428. return NULL;
  3429. }
  3430. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  3431. if (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= new_size) // If overflow would occur...
  3432. return 0;
  3433. new_size += sizeof(AllocAlignmentInteger);
  3434. AllocAlignmentInteger* header = Internal::fastMallocMatchValidationValue(old_ptr);
  3435. if (*header != Internal::AllocTypeMalloc)
  3436. Internal::fastMallocMatchFailed(old_ptr);
  3437. old_ptr = header;
  3438. #endif
  3439. // Get the size of the old entry
  3440. const PageID p = reinterpret_cast<uintptr_t>(old_ptr) >> kPageShift;
  3441. size_t cl = pageheap->GetSizeClassIfCached(p);
  3442. Span *span = NULL;
  3443. size_t old_size;
  3444. if (cl == 0) {
  3445. span = pageheap->GetDescriptor(p);
  3446. cl = span->sizeclass;
  3447. pageheap->CacheSizeClass(p, cl);
  3448. }
  3449. if (cl != 0) {
  3450. old_size = ByteSizeForClass(cl);
  3451. } else {
  3452. ASSERT(span != NULL);
  3453. old_size = span->length << kPageShift;
  3454. }
  3455. // Reallocate if the new size is larger than the old size,
  3456. // or if the new size is significantly smaller than the old size.
  3457. if ((new_size > old_size) || (AllocationSize(new_size) < old_size)) {
  3458. // Need to reallocate
  3459. void* new_ptr = do_malloc(new_size);
  3460. if (new_ptr == NULL) {
  3461. return NULL;
  3462. }
  3463. #ifndef WTF_CHANGES
  3464. MallocHook::InvokeNewHook(new_ptr, new_size);
  3465. #endif
  3466. memcpy(new_ptr, old_ptr, ((old_size < new_size) ? old_size : new_size));
  3467. #ifndef WTF_CHANGES
  3468. MallocHook::InvokeDeleteHook(old_ptr);
  3469. #endif
  3470. // We could use a variant of do_free() that leverages the fact
  3471. // that we already know the sizeclass of old_ptr. The benefit
  3472. // would be small, so don't bother.
  3473. do_free(old_ptr);
  3474. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  3475. new_ptr = static_cast<AllocAlignmentInteger*>(new_ptr) + 1;
  3476. #endif
  3477. return new_ptr;
  3478. } else {
  3479. #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
  3480. old_ptr = static_cast<AllocAlignmentInteger*>(old_ptr) + 1; // Set old_ptr back to the user pointer.
  3481. #endif
  3482. return old_ptr;
  3483. }
  3484. }
  3485. #ifdef WTF_CHANGES
  3486. #undef do_malloc
  3487. #else
  3488. static SpinLock set_new_handler_lock = SPINLOCK_INITIALIZER;
  3489. static inline void* cpp_alloc(size_t size, bool nothrow) {
  3490. for (;;) {
  3491. void* p = do_malloc(size);
  3492. #ifdef PREANSINEW
  3493. return p;
  3494. #else
  3495. if (p == NULL) { // allocation failed
  3496. // Get the current new handler. NB: this function is not
  3497. // thread-safe. We make a feeble stab at making it so here, but
  3498. // this lock only protects against tcmalloc interfering with
  3499. // itself, not with other libraries calling set_new_handler.
  3500. std::new_handler nh;
  3501. {
  3502. SpinLockHolder h(&set_new_handler_lock);
  3503. nh = std::set_new_handler(0);
  3504. (void) std::set_new_handler(nh);
  3505. }
  3506. // If no new_handler is established, the allocation failed.
  3507. if (!nh) {
  3508. if (nothrow) return 0;
  3509. throw std::bad_alloc();
  3510. }
  3511. // Otherwise, try the new_handler. If it returns, retry the
  3512. // allocation. If it throws std::bad_alloc, fail the allocation.
  3513. // if it throws something else, don't interfere.
  3514. try {
  3515. (*nh)();
  3516. } catch (const std::bad_alloc&) {
  3517. if (!nothrow) throw;
  3518. return p;
  3519. }
  3520. } else { // allocation success
  3521. return p;
  3522. }
  3523. #endif
  3524. }
  3525. }
  3526. #if ENABLE(GLOBAL_FASTMALLOC_NEW)
  3527. void* operator new(size_t size) {
  3528. void* p = cpp_alloc(size, false);
  3529. // We keep this next instruction out of cpp_alloc for a reason: when
  3530. // it's in, and new just calls cpp_alloc, the optimizer may fold the
  3531. // new call into cpp_alloc, which messes up our whole section-based
  3532. // stacktracing (see ATTRIBUTE_SECTION, above). This ensures cpp_alloc
  3533. // isn't the last thing this fn calls, and prevents the folding.
  3534. MallocHook::InvokeNewHook(p, size);
  3535. return p;
  3536. }
  3537. void* operator new(size_t size, const std::nothrow_t&) __THROW {
  3538. void* p = cpp_alloc(size, true);
  3539. MallocHook::InvokeNewHook(p, size);
  3540. return p;
  3541. }
  3542. void operator delete(void* p) __THROW {
  3543. MallocHook::InvokeDeleteHook(p);
  3544. do_free(p);
  3545. }
  3546. void operator delete(void* p, const std::nothrow_t&) __THROW {
  3547. MallocHook::InvokeDeleteHook(p);
  3548. do_free(p);
  3549. }
  3550. void* operator new[](size_t size) {
  3551. void* p = cpp_alloc(size, false);
  3552. // We keep this next instruction out of cpp_alloc for a reason: when
  3553. // it's in, and new just calls cpp_alloc, the optimizer may fold the
  3554. // new call into cpp_alloc, which messes up our whole section-based
  3555. // stacktracing (see ATTRIBUTE_SECTION, above). This ensures cpp_alloc
  3556. // isn't the last thing this fn calls, and prevents the folding.
  3557. MallocHook::InvokeNewHook(p, size);
  3558. return p;
  3559. }
  3560. void* operator new[](size_t size, const std::nothrow_t&) __THROW {
  3561. void* p = cpp_alloc(size, true);
  3562. MallocHook::InvokeNewHook(p, size);
  3563. return p;
  3564. }
  3565. void operator delete[](void* p) __THROW {
  3566. MallocHook::InvokeDeleteHook(p);
  3567. do_free(p);
  3568. }
  3569. void operator delete[](void* p, const std::nothrow_t&) __THROW {
  3570. MallocHook::InvokeDeleteHook(p);
  3571. do_free(p);
  3572. }
  3573. #endif
  3574. extern "C" void* memalign(size_t align, size_t size) __THROW {
  3575. void* result = do_memalign(align, size);
  3576. MallocHook::InvokeNewHook(result, size);
  3577. return result;
  3578. }
  3579. extern "C" int posix_memalign(void** result_ptr, size_t align, size_t size)
  3580. __THROW {
  3581. if (((align % sizeof(void*)) != 0) ||
  3582. ((align & (align - 1)) != 0) ||
  3583. (align == 0)) {
  3584. return EINVAL;
  3585. }
  3586. void* result = do_memalign(align, size);
  3587. MallocHook::InvokeNewHook(result, size);
  3588. if (result == NULL) {
  3589. return ENOMEM;
  3590. } else {
  3591. *result_ptr = result;
  3592. return 0;
  3593. }
  3594. }
  3595. static size_t pagesize = 0;
  3596. extern "C" void* valloc(size_t size) __THROW {
  3597. // Allocate page-aligned object of length >= size bytes
  3598. if (pagesize == 0) pagesize = getpagesize();
  3599. void* result = do_memalign(pagesize, size);
  3600. MallocHook::InvokeNewHook(result, size);
  3601. return result;
  3602. }
  3603. extern "C" void* pvalloc(size_t size) __THROW {
  3604. // Round up size to a multiple of pagesize
  3605. if (pagesize == 0) pagesize = getpagesize();
  3606. size = (size + pagesize - 1) & ~(pagesize - 1);
  3607. void* result = do_memalign(pagesize, size);
  3608. MallocHook::InvokeNewHook(result, size);
  3609. return result;
  3610. }
  3611. extern "C" void malloc_stats(void) {
  3612. do_malloc_stats();
  3613. }
  3614. extern "C" int mallopt(int cmd, int value) {
  3615. return do_mallopt(cmd, value);
  3616. }
  3617. #ifdef HAVE_STRUCT_MALLINFO
  3618. extern "C" struct mallinfo mallinfo(void) {
  3619. return do_mallinfo();
  3620. }
  3621. #endif
  3622. //-------------------------------------------------------------------
  3623. // Some library routines on RedHat 9 allocate memory using malloc()
  3624. // and free it using __libc_free() (or vice-versa). Since we provide
  3625. // our own implementations of malloc/free, we need to make sure that
  3626. // the __libc_XXX variants (defined as part of glibc) also point to
  3627. // the same implementations.
  3628. //-------------------------------------------------------------------
  3629. #if defined(__GLIBC__)
  3630. extern "C" {
  3631. #if COMPILER(GCC) && !defined(__MACH__) && defined(HAVE___ATTRIBUTE__)
  3632. // Potentially faster variants that use the gcc alias extension.
  3633. // Mach-O (Darwin) does not support weak aliases, hence the __MACH__ check.
  3634. # define ALIAS(x) __attribute__ ((weak, alias (x)))
  3635. void* __libc_malloc(size_t size) ALIAS("malloc");
  3636. void __libc_free(void* ptr) ALIAS("free");
  3637. void* __libc_realloc(void* ptr, size_t size) ALIAS("realloc");
  3638. void* __libc_calloc(size_t n, size_t size) ALIAS("calloc");
  3639. void __libc_cfree(void* ptr) ALIAS("cfree");
  3640. void* __libc_memalign(size_t align, size_t s) ALIAS("memalign");
  3641. void* __libc_valloc(size_t size) ALIAS("valloc");
  3642. void* __libc_pvalloc(size_t size) ALIAS("pvalloc");
  3643. int __posix_memalign(void** r, size_t a, size_t s) ALIAS("posix_memalign");
  3644. # undef ALIAS
  3645. # else /* not __GNUC__ */
  3646. // Portable wrappers
  3647. void* __libc_malloc(size_t size) { return malloc(size); }
  3648. void __libc_free(void* ptr) { free(ptr); }
  3649. void* __libc_realloc(void* ptr, size_t size) { return realloc(ptr, size); }
  3650. void* __libc_calloc(size_t n, size_t size) { return calloc(n, size); }
  3651. void __libc_cfree(void* ptr) { cfree(ptr); }
  3652. void* __libc_memalign(size_t align, size_t s) { return memalign(align, s); }
  3653. void* __libc_valloc(size_t size) { return valloc(size); }
  3654. void* __libc_pvalloc(size_t size) { return pvalloc(size); }
  3655. int __posix_memalign(void** r, size_t a, size_t s) {
  3656. return posix_memalign(r, a, s);
  3657. }
  3658. # endif /* __GNUC__ */
  3659. }
  3660. #endif /* __GLIBC__ */
  3661. // Override __libc_memalign in libc on linux boxes specially.
  3662. // They have a bug in libc that causes them to (very rarely) allocate
  3663. // with __libc_memalign() yet deallocate with free() and the
  3664. // definitions above don't catch it.
  3665. // This function is an exception to the rule of calling MallocHook method
  3666. // from the stack frame of the allocation function;
  3667. // heap-checker handles this special case explicitly.
  3668. static void *MemalignOverride(size_t align, size_t size, const void *caller)
  3669. __THROW {
  3670. void* result = do_memalign(align, size);
  3671. MallocHook::InvokeNewHook(result, size);
  3672. return result;
  3673. }
  3674. void *(*__memalign_hook)(size_t, size_t, const void *) = MemalignOverride;
  3675. #endif
  3676. #ifdef WTF_CHANGES
  3677. void releaseFastMallocFreeMemory()
  3678. {
  3679. // Flush free pages in the current thread cache back to the page heap.
  3680. // Low watermark mechanism in Scavenge() prevents full return on the first pass.
  3681. // The second pass flushes everything.
  3682. if (TCMalloc_ThreadCache* threadCache = TCMalloc_ThreadCache::GetCacheIfPresent()) {
  3683. threadCache->Scavenge();
  3684. threadCache->Scavenge();
  3685. }
  3686. SpinLockHolder h(&pageheap_lock);
  3687. pageheap->ReleaseFreePages();
  3688. }
  3689. FastMallocStatistics fastMallocStatistics()
  3690. {
  3691. FastMallocStatistics statistics;
  3692. SpinLockHolder lockHolder(&pageheap_lock);
  3693. statistics.reservedVMBytes = static_cast<size_t>(pageheap->SystemBytes());
  3694. statistics.committedVMBytes = statistics.reservedVMBytes - pageheap->ReturnedBytes();
  3695. statistics.freeListBytes = 0;
  3696. for (unsigned cl = 0; cl < kNumClasses; ++cl) {
  3697. const int length = central_cache[cl].length();
  3698. const int tc_length = central_cache[cl].tc_length();
  3699. statistics.freeListBytes += ByteSizeForClass(cl) * (length + tc_length);
  3700. }
  3701. for (TCMalloc_ThreadCache* threadCache = thread_heaps; threadCache ; threadCache = threadCache->next_)
  3702. statistics.freeListBytes += threadCache->Size();
  3703. return statistics;
  3704. }
  3705. size_t fastMallocSize(const void* ptr)
  3706. {
  3707. const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
  3708. Span* span = pageheap->GetDescriptorEnsureSafe(p);
  3709. if (!span || span->free)
  3710. return 0;
  3711. for (void* free = span->objects; free != NULL; free = *((void**) free)) {
  3712. if (ptr == free)
  3713. return 0;
  3714. }
  3715. if (size_t cl = span->sizeclass)
  3716. return ByteSizeForClass(cl);
  3717. return span->length << kPageShift;
  3718. }
  3719. #if OS(DARWIN)
  3720. class FreeObjectFinder {
  3721. const RemoteMemoryReader& m_reader;
  3722. HashSet<void*> m_freeObjects;
  3723. public:
  3724. FreeObjectFinder(const RemoteMemoryReader& reader) : m_reader(reader) { }
  3725. void visit(void* ptr) { m_freeObjects.add(ptr); }
  3726. bool isFreeObject(void* ptr) const { return m_freeObjects.contains(ptr); }
  3727. bool isFreeObject(vm_address_t ptr) const { return isFreeObject(reinterpret_cast<void*>(ptr)); }
  3728. size_t freeObjectCount() const { return m_freeObjects.size(); }
  3729. void findFreeObjects(TCMalloc_ThreadCache* threadCache)
  3730. {
  3731. for (; threadCache; threadCache = (threadCache->next_ ? m_reader(threadCache->next_) : 0))
  3732. threadCache->enumerateFreeObjects(*this, m_reader);
  3733. }
  3734. void findFreeObjects(TCMalloc_Central_FreeListPadded* centralFreeList, size_t numSizes, TCMalloc_Central_FreeListPadded* remoteCentralFreeList)
  3735. {
  3736. for (unsigned i = 0; i < numSizes; i++)
  3737. centralFreeList[i].enumerateFreeObjects(*this, m_reader, remoteCentralFreeList + i);
  3738. }
  3739. };
  3740. class PageMapFreeObjectFinder {
  3741. const RemoteMemoryReader& m_reader;
  3742. FreeObjectFinder& m_freeObjectFinder;
  3743. public:
  3744. PageMapFreeObjectFinder(const RemoteMemoryReader& reader, FreeObjectFinder& freeObjectFinder)
  3745. : m_reader(reader)
  3746. , m_freeObjectFinder(freeObjectFinder)
  3747. { }
  3748. int visit(void* ptr) const
  3749. {
  3750. if (!ptr)
  3751. return 1;
  3752. Span* span = m_reader(reinterpret_cast<Span*>(ptr));
  3753. if (!span)
  3754. return 1;
  3755. if (span->free) {
  3756. void* ptr = reinterpret_cast<void*>(span->start << kPageShift);
  3757. m_freeObjectFinder.visit(ptr);
  3758. } else if (span->sizeclass) {
  3759. // Walk the free list of the small-object span, keeping track of each object seen
  3760. for (void* nextObject = span->objects; nextObject; nextObject = m_reader.nextEntryInLinkedList(reinterpret_cast<void**>(nextObject)))
  3761. m_freeObjectFinder.visit(nextObject);
  3762. }
  3763. return span->length;
  3764. }
  3765. };
  3766. class PageMapMemoryUsageRecorder {
  3767. task_t m_task;
  3768. void* m_context;
  3769. unsigned m_typeMask;
  3770. vm_range_recorder_t* m_recorder;
  3771. const RemoteMemoryReader& m_reader;
  3772. const FreeObjectFinder& m_freeObjectFinder;
  3773. HashSet<void*> m_seenPointers;
  3774. Vector<Span*> m_coalescedSpans;
  3775. public:
  3776. PageMapMemoryUsageRecorder(task_t task, void* context, unsigned typeMask, vm_range_recorder_t* recorder, const RemoteMemoryReader& reader, const FreeObjectFinder& freeObjectFinder)
  3777. : m_task(task)
  3778. , m_context(context)
  3779. , m_typeMask(typeMask)
  3780. , m_recorder(recorder)
  3781. , m_reader(reader)
  3782. , m_freeObjectFinder(freeObjectFinder)
  3783. { }
  3784. ~PageMapMemoryUsageRecorder()
  3785. {
  3786. ASSERT(!m_coalescedSpans.size());
  3787. }
  3788. void recordPendingRegions()
  3789. {
  3790. Span* lastSpan = m_coalescedSpans[m_coalescedSpans.size() - 1];
  3791. vm_range_t ptrRange = { m_coalescedSpans[0]->start << kPageShift, 0 };
  3792. ptrRange.size = (lastSpan->start << kPageShift) - ptrRange.address + (lastSpan->length * kPageSize);
  3793. // Mark the memory region the spans represent as a candidate for containing pointers
  3794. if (m_typeMask & MALLOC_PTR_REGION_RANGE_TYPE)
  3795. (*m_recorder)(m_task, m_context, MALLOC_PTR_REGION_RANGE_TYPE, &ptrRange, 1);
  3796. if (!(m_typeMask & MALLOC_PTR_IN_USE_RANGE_TYPE)) {
  3797. m_coalescedSpans.clear();
  3798. return;
  3799. }
  3800. Vector<vm_range_t, 1024> allocatedPointers;
  3801. for (size_t i = 0; i < m_coalescedSpans.size(); ++i) {
  3802. Span *theSpan = m_coalescedSpans[i];
  3803. if (theSpan->free)
  3804. continue;
  3805. vm_address_t spanStartAddress = theSpan->start << kPageShift;
  3806. vm_size_t spanSizeInBytes = theSpan->length * kPageSize;
  3807. if (!theSpan->sizeclass) {
  3808. // If it's an allocated large object span, mark it as in use
  3809. if (!m_freeObjectFinder.isFreeObject(spanStartAddress))
  3810. allocatedPointers.append((vm_range_t){spanStartAddress, spanSizeInBytes});
  3811. } else {
  3812. const size_t objectSize = ByteSizeForClass(theSpan->sizeclass);
  3813. // Mark each allocated small object within the span as in use
  3814. const vm_address_t endOfSpan = spanStartAddress + spanSizeInBytes;
  3815. for (vm_address_t object = spanStartAddress; object + objectSize <= endOfSpan; object += objectSize) {
  3816. if (!m_freeObjectFinder.isFreeObject(object))
  3817. allocatedPointers.append((vm_range_t){object, objectSize});
  3818. }
  3819. }
  3820. }
  3821. (*m_recorder)(m_task, m_context, MALLOC_PTR_IN_USE_RANGE_TYPE, allocatedPointers.data(), allocatedPointers.size());
  3822. m_coalescedSpans.clear();
  3823. }
  3824. int visit(void* ptr)
  3825. {
  3826. if (!ptr)
  3827. return 1;
  3828. Span* span = m_reader(reinterpret_cast<Span*>(ptr));
  3829. if (!span || !span->start)
  3830. return 1;
  3831. if (m_seenPointers.contains(ptr))
  3832. return span->length;
  3833. m_seenPointers.add(ptr);
  3834. if (!m_coalescedSpans.size()) {
  3835. m_coalescedSpans.append(span);
  3836. return span->length;
  3837. }
  3838. Span* previousSpan = m_coalescedSpans[m_coalescedSpans.size() - 1];
  3839. vm_address_t previousSpanStartAddress = previousSpan->start << kPageShift;
  3840. vm_size_t previousSpanSizeInBytes = previousSpan->length * kPageSize;
  3841. // If the new span is adjacent to the previous span, do nothing for now.
  3842. vm_address_t spanStartAddress = span->start << kPageShift;
  3843. if (spanStartAddress == previousSpanStartAddress + previousSpanSizeInBytes) {
  3844. m_coalescedSpans.append(span);
  3845. return span->length;
  3846. }
  3847. // New span is not adjacent to previous span, so record the spans coalesced so far.
  3848. recordPendingRegions();
  3849. m_coalescedSpans.append(span);
  3850. return span->length;
  3851. }
  3852. };
  3853. class AdminRegionRecorder {
  3854. task_t m_task;
  3855. void* m_context;
  3856. unsigned m_typeMask;
  3857. vm_range_recorder_t* m_recorder;
  3858. const RemoteMemoryReader& m_reader;
  3859. Vector<vm_range_t, 1024> m_pendingRegions;
  3860. public:
  3861. AdminRegionRecorder(task_t task, void* context, unsigned typeMask, vm_range_recorder_t* recorder, const RemoteMemoryReader& reader)
  3862. : m_task(task)
  3863. , m_context(context)
  3864. , m_typeMask(typeMask)
  3865. , m_recorder(recorder)
  3866. , m_reader(reader)
  3867. { }
  3868. void recordRegion(vm_address_t ptr, size_t size)
  3869. {
  3870. if (m_typeMask & MALLOC_ADMIN_REGION_RANGE_TYPE)
  3871. m_pendingRegions.append((vm_range_t){ ptr, size });
  3872. }
  3873. void visit(void *ptr, size_t size)
  3874. {
  3875. recordRegion(reinterpret_cast<vm_address_t>(ptr), size);
  3876. }
  3877. void recordPendingRegions()
  3878. {
  3879. if (m_pendingRegions.size()) {
  3880. (*m_recorder)(m_task, m_context, MALLOC_ADMIN_REGION_RANGE_TYPE, m_pendingRegions.data(), m_pendingRegions.size());
  3881. m_pendingRegions.clear();
  3882. }
  3883. }
  3884. ~AdminRegionRecorder()
  3885. {
  3886. ASSERT(!m_pendingRegions.size());
  3887. }
  3888. };
  3889. kern_return_t FastMallocZone::enumerate(task_t task, void* context, unsigned typeMask, vm_address_t zoneAddress, memory_reader_t reader, vm_range_recorder_t recorder)
  3890. {
  3891. RemoteMemoryReader memoryReader(task, reader);
  3892. InitSizeClasses();
  3893. FastMallocZone* mzone = memoryReader(reinterpret_cast<FastMallocZone*>(zoneAddress));
  3894. TCMalloc_PageHeap* pageHeap = memoryReader(mzone->m_pageHeap);
  3895. TCMalloc_ThreadCache** threadHeapsPointer = memoryReader(mzone->m_threadHeaps);
  3896. TCMalloc_ThreadCache* threadHeaps = memoryReader(*threadHeapsPointer);
  3897. TCMalloc_Central_FreeListPadded* centralCaches = memoryReader(mzone->m_centralCaches, sizeof(TCMalloc_Central_FreeListPadded) * kNumClasses);
  3898. FreeObjectFinder finder(memoryReader);
  3899. finder.findFreeObjects(threadHeaps);
  3900. finder.findFreeObjects(centralCaches, kNumClasses, mzone->m_centralCaches);
  3901. TCMalloc_PageHeap::PageMap* pageMap = &pageHeap->pagemap_;
  3902. PageMapFreeObjectFinder pageMapFinder(memoryReader, finder);
  3903. pageMap->visitValues(pageMapFinder, memoryReader);
  3904. PageMapMemoryUsageRecorder usageRecorder(task, context, typeMask, recorder, memoryReader, finder);
  3905. pageMap->visitValues(usageRecorder, memoryReader);
  3906. usageRecorder.recordPendingRegions();
  3907. AdminRegionRecorder adminRegionRecorder(task, context, typeMask, recorder, memoryReader);
  3908. pageMap->visitAllocations(adminRegionRecorder, memoryReader);
  3909. PageHeapAllocator<Span>* spanAllocator = memoryReader(mzone->m_spanAllocator);
  3910. PageHeapAllocator<TCMalloc_ThreadCache>* pageHeapAllocator = memoryReader(mzone->m_pageHeapAllocator);
  3911. spanAllocator->recordAdministrativeRegions(adminRegionRecorder, memoryReader);
  3912. pageHeapAllocator->recordAdministrativeRegions(adminRegionRecorder, memoryReader);
  3913. adminRegionRecorder.recordPendingRegions();
  3914. return 0;
  3915. }
  3916. size_t FastMallocZone::size(malloc_zone_t*, const void*)
  3917. {
  3918. return 0;
  3919. }
  3920. void* FastMallocZone::zoneMalloc(malloc_zone_t*, size_t)
  3921. {
  3922. return 0;
  3923. }
  3924. void* FastMallocZone::zoneCalloc(malloc_zone_t*, size_t, size_t)
  3925. {
  3926. return 0;
  3927. }
  3928. void FastMallocZone::zoneFree(malloc_zone_t*, void* ptr)
  3929. {
  3930. // Due to <rdar://problem/5671357> zoneFree may be called by the system free even if the pointer
  3931. // is not in this zone. When this happens, the pointer being freed was not allocated by any
  3932. // zone so we need to print a useful error for the application developer.
  3933. malloc_printf("*** error for object %p: pointer being freed was not allocated\n", ptr);
  3934. }
  3935. void* FastMallocZone::zoneRealloc(malloc_zone_t*, void*, size_t)
  3936. {
  3937. return 0;
  3938. }
  3939. #undef malloc
  3940. #undef free
  3941. #undef realloc
  3942. #undef calloc
  3943. extern "C" {
  3944. malloc_introspection_t jscore_fastmalloc_introspection = { &FastMallocZone::enumerate, &FastMallocZone::goodSize, &FastMallocZone::check, &FastMallocZone::print,
  3945. &FastMallocZone::log, &FastMallocZone::forceLock, &FastMallocZone::forceUnlock, &FastMallocZone::statistics
  3946. #if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD)
  3947. , 0 // zone_locked will not be called on the zone unless it advertises itself as version five or higher.
  3948. #endif
  3949. #if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) && !defined(BUILDING_ON_SNOW_LEOPARD)
  3950. , 0, 0, 0, 0 // These members will not be used unless the zone advertises itself as version seven or higher.
  3951. #endif
  3952. };
  3953. }
  3954. FastMallocZone::FastMallocZone(TCMalloc_PageHeap* pageHeap, TCMalloc_ThreadCache** threadHeaps, TCMalloc_Central_FreeListPadded* centralCaches, PageHeapAllocator<Span>* spanAllocator, PageHeapAllocator<TCMalloc_ThreadCache>* pageHeapAllocator)
  3955. : m_pageHeap(pageHeap)
  3956. , m_threadHeaps(threadHeaps)
  3957. , m_centralCaches(centralCaches)
  3958. , m_spanAllocator(spanAllocator)
  3959. , m_pageHeapAllocator(pageHeapAllocator)
  3960. {
  3961. memset(&m_zone, 0, sizeof(m_zone));
  3962. m_zone.version = 4;
  3963. m_zone.zone_name = "JavaScriptCore FastMalloc";
  3964. m_zone.size = &FastMallocZone::size;
  3965. m_zone.malloc = &FastMallocZone::zoneMalloc;
  3966. m_zone.calloc = &FastMallocZone::zoneCalloc;
  3967. m_zone.realloc = &FastMallocZone::zoneRealloc;
  3968. m_zone.free = &FastMallocZone::zoneFree;
  3969. m_zone.valloc = &FastMallocZone::zoneValloc;
  3970. m_zone.destroy = &FastMallocZone::zoneDestroy;
  3971. m_zone.introspect = &jscore_fastmalloc_introspection;
  3972. malloc_zone_register(&m_zone);
  3973. }
  3974. void FastMallocZone::init()
  3975. {
  3976. static FastMallocZone zone(pageheap, &thread_heaps, static_cast<TCMalloc_Central_FreeListPadded*>(central_cache), &span_allocator, &threadheap_allocator);
  3977. }
  3978. #endif // OS(DARWIN)
  3979. } // namespace WTF
  3980. #endif // WTF_CHANGES
  3981. #endif // FORCE_SYSTEM_MALLOC