PageRenderTime 61ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/webview/native/Source/WTF/wtf/FastMalloc.cpp

https://bitbucket.org/rbair/rbair-controls-8
C++ | 4699 lines | 3334 code | 645 blank | 720 comment | 542 complexity | 327fc0ee0e4f35cde8c4dcd7c8510a7d MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1, GPL-2.0, LGPL-2.0

Large files files are truncated, but you can click here to view the full file

  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 OS(WINDOWS)
  80. #include <windows.h>
  81. #else
  82. #include <pthread.h>
  83. #endif
  84. #include <wtf/StdLibExtras.h>
  85. #include <string.h>
  86. #ifndef NO_TCMALLOC_SAMPLES
  87. #ifdef WTF_CHANGES
  88. #define NO_TCMALLOC_SAMPLES
  89. #endif
  90. #endif
  91. #if !(defined(USE_SYSTEM_MALLOC) && USE_SYSTEM_MALLOC) && defined(NDEBUG)
  92. #define FORCE_SYSTEM_MALLOC 0
  93. #else
  94. #define FORCE_SYSTEM_MALLOC 1
  95. #endif
  96. // Use a background thread to periodically scavenge memory to release back to the system
  97. #if PLATFORM(IOS)
  98. #define USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY 0
  99. #else
  100. #define USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY 1
  101. #endif
  102. #ifndef NDEBUG
  103. namespace WTF {
  104. #if OS(WINDOWS)
  105. // TLS_OUT_OF_INDEXES is not defined on WinCE.
  106. #ifndef TLS_OUT_OF_INDEXES
  107. #define TLS_OUT_OF_INDEXES 0xffffffff
  108. #endif
  109. static DWORD isForibiddenTlsIndex = TLS_OUT_OF_INDEXES;
  110. static const LPVOID kTlsAllowValue = reinterpret_cast<LPVOID>(0); // Must be zero.
  111. static const LPVOID kTlsForbiddenValue = reinterpret_cast<LPVOID>(1);
  112. #if !ASSERT_DISABLED
  113. static bool isForbidden()
  114. {
  115. // By default, fastMalloc is allowed so we don't allocate the
  116. // tls index unless we're asked to make it forbidden. If TlsSetValue
  117. // has not been called on a thread, the value returned by TlsGetValue is 0.
  118. return (isForibiddenTlsIndex != TLS_OUT_OF_INDEXES) && (TlsGetValue(isForibiddenTlsIndex) == kTlsForbiddenValue);
  119. }
  120. #endif
  121. void fastMallocForbid()
  122. {
  123. if (isForibiddenTlsIndex == TLS_OUT_OF_INDEXES)
  124. isForibiddenTlsIndex = TlsAlloc(); // a little racey, but close enough for debug only
  125. TlsSetValue(isForibiddenTlsIndex, kTlsForbiddenValue);
  126. }
  127. void fastMallocAllow()
  128. {
  129. if (isForibiddenTlsIndex == TLS_OUT_OF_INDEXES)
  130. return;
  131. TlsSetValue(isForibiddenTlsIndex, kTlsAllowValue);
  132. }
  133. #else // !OS(WINDOWS)
  134. static pthread_key_t isForbiddenKey;
  135. static pthread_once_t isForbiddenKeyOnce = PTHREAD_ONCE_INIT;
  136. static void initializeIsForbiddenKey()
  137. {
  138. pthread_key_create(&isForbiddenKey, 0);
  139. }
  140. #if !ASSERT_DISABLED
  141. static bool isForbidden()
  142. {
  143. pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
  144. return !!pthread_getspecific(isForbiddenKey);
  145. }
  146. #endif
  147. void fastMallocForbid()
  148. {
  149. pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
  150. pthread_setspecific(isForbiddenKey, &isForbiddenKey);
  151. }
  152. void fastMallocAllow()
  153. {
  154. pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
  155. pthread_setspecific(isForbiddenKey, 0);
  156. }
  157. #endif // OS(WINDOWS)
  158. } // namespace WTF
  159. #endif // NDEBUG
  160. namespace WTF {
  161. namespace Internal {
  162. #if !ENABLE(WTF_MALLOC_VALIDATION)
  163. WTF_EXPORT_PRIVATE void fastMallocMatchFailed(void*);
  164. #else
  165. COMPILE_ASSERT(((sizeof(ValidationHeader) % sizeof(AllocAlignmentInteger)) == 0), ValidationHeader_must_produce_correct_alignment);
  166. #endif
  167. NO_RETURN_DUE_TO_CRASH void fastMallocMatchFailed(void*)
  168. {
  169. CRASH();
  170. }
  171. } // namespace Internal
  172. void* fastZeroedMalloc(size_t n)
  173. {
  174. void* result = fastMalloc(n);
  175. memset(result, 0, n);
  176. return result;
  177. }
  178. char* fastStrDup(const char* src)
  179. {
  180. size_t len = strlen(src) + 1;
  181. char* dup = static_cast<char*>(fastMalloc(len));
  182. memcpy(dup, src, len);
  183. return dup;
  184. }
  185. TryMallocReturnValue tryFastZeroedMalloc(size_t n)
  186. {
  187. void* result;
  188. if (!tryFastMalloc(n).getValue(result))
  189. return 0;
  190. memset(result, 0, n);
  191. return result;
  192. }
  193. } // namespace WTF
  194. #if FORCE_SYSTEM_MALLOC
  195. #if OS(DARWIN)
  196. #include <malloc/malloc.h>
  197. #elif OS(WINDOWS)
  198. #include <malloc.h>
  199. #endif
  200. namespace WTF {
  201. TryMallocReturnValue tryFastMalloc(size_t n)
  202. {
  203. ASSERT(!isForbidden());
  204. #if ENABLE(WTF_MALLOC_VALIDATION)
  205. if (std::numeric_limits<size_t>::max() - Internal::ValidationBufferSize <= n) // If overflow would occur...
  206. return 0;
  207. void* result = malloc(n + Internal::ValidationBufferSize);
  208. if (!result)
  209. return 0;
  210. Internal::ValidationHeader* header = static_cast<Internal::ValidationHeader*>(result);
  211. header->m_size = n;
  212. header->m_type = Internal::AllocTypeMalloc;
  213. header->m_prefix = static_cast<unsigned>(Internal::ValidationPrefix);
  214. result = header + 1;
  215. *Internal::fastMallocValidationSuffix(result) = Internal::ValidationSuffix;
  216. fastMallocValidate(result);
  217. return result;
  218. #else
  219. return malloc(n);
  220. #endif
  221. }
  222. void* fastMalloc(size_t n)
  223. {
  224. ASSERT(!isForbidden());
  225. #if ENABLE(WTF_MALLOC_VALIDATION)
  226. TryMallocReturnValue returnValue = tryFastMalloc(n);
  227. void* result;
  228. if (!returnValue.getValue(result))
  229. CRASH();
  230. #else
  231. void* result = malloc(n);
  232. #endif
  233. if (!result)
  234. CRASH();
  235. return result;
  236. }
  237. TryMallocReturnValue tryFastCalloc(size_t n_elements, size_t element_size)
  238. {
  239. ASSERT(!isForbidden());
  240. #if ENABLE(WTF_MALLOC_VALIDATION)
  241. size_t totalBytes = n_elements * element_size;
  242. if (n_elements > 1 && element_size && (totalBytes / element_size) != n_elements)
  243. return 0;
  244. TryMallocReturnValue returnValue = tryFastMalloc(totalBytes);
  245. void* result;
  246. if (!returnValue.getValue(result))
  247. return 0;
  248. memset(result, 0, totalBytes);
  249. fastMallocValidate(result);
  250. return result;
  251. #else
  252. return calloc(n_elements, element_size);
  253. #endif
  254. }
  255. void* fastCalloc(size_t n_elements, size_t element_size)
  256. {
  257. ASSERT(!isForbidden());
  258. #if ENABLE(WTF_MALLOC_VALIDATION)
  259. TryMallocReturnValue returnValue = tryFastCalloc(n_elements, element_size);
  260. void* result;
  261. if (!returnValue.getValue(result))
  262. CRASH();
  263. #else
  264. void* result = calloc(n_elements, element_size);
  265. #endif
  266. if (!result)
  267. CRASH();
  268. return result;
  269. }
  270. void fastFree(void* p)
  271. {
  272. ASSERT(!isForbidden());
  273. #if ENABLE(WTF_MALLOC_VALIDATION)
  274. if (!p)
  275. return;
  276. fastMallocMatchValidateFree(p, Internal::AllocTypeMalloc);
  277. Internal::ValidationHeader* header = Internal::fastMallocValidationHeader(p);
  278. memset(p, 0xCC, header->m_size);
  279. free(header);
  280. #else
  281. free(p);
  282. #endif
  283. }
  284. TryMallocReturnValue tryFastRealloc(void* p, size_t n)
  285. {
  286. ASSERT(!isForbidden());
  287. #if ENABLE(WTF_MALLOC_VALIDATION)
  288. if (p) {
  289. if (std::numeric_limits<size_t>::max() - Internal::ValidationBufferSize <= n) // If overflow would occur...
  290. return 0;
  291. fastMallocValidate(p);
  292. Internal::ValidationHeader* result = static_cast<Internal::ValidationHeader*>(realloc(Internal::fastMallocValidationHeader(p), n + Internal::ValidationBufferSize));
  293. if (!result)
  294. return 0;
  295. result->m_size = n;
  296. result = result + 1;
  297. *fastMallocValidationSuffix(result) = Internal::ValidationSuffix;
  298. fastMallocValidate(result);
  299. return result;
  300. } else {
  301. return fastMalloc(n);
  302. }
  303. #else
  304. return realloc(p, n);
  305. #endif
  306. }
  307. void* fastRealloc(void* p, size_t n)
  308. {
  309. ASSERT(!isForbidden());
  310. #if ENABLE(WTF_MALLOC_VALIDATION)
  311. TryMallocReturnValue returnValue = tryFastRealloc(p, n);
  312. void* result;
  313. if (!returnValue.getValue(result))
  314. CRASH();
  315. #else
  316. void* result = realloc(p, n);
  317. #endif
  318. if (!result)
  319. CRASH();
  320. return result;
  321. }
  322. void releaseFastMallocFreeMemory() { }
  323. FastMallocStatistics fastMallocStatistics()
  324. {
  325. FastMallocStatistics statistics = { 0, 0, 0 };
  326. return statistics;
  327. }
  328. size_t fastMallocSize(const void* p)
  329. {
  330. #if ENABLE(WTF_MALLOC_VALIDATION)
  331. return Internal::fastMallocValidationHeader(const_cast<void*>(p))->m_size;
  332. #elif OS(DARWIN)
  333. return malloc_size(p);
  334. #elif OS(WINDOWS)
  335. return _msize(const_cast<void*>(p));
  336. #else
  337. return 1;
  338. #endif
  339. }
  340. } // namespace WTF
  341. #if OS(DARWIN)
  342. // This symbol is present in the JavaScriptCore exports file even when FastMalloc is disabled.
  343. // It will never be used in this case, so it's type and value are less interesting than its presence.
  344. extern "C" WTF_EXPORT_PRIVATE const int jscore_fastmalloc_introspection = 0;
  345. #endif
  346. #else // FORCE_SYSTEM_MALLOC
  347. #include "AlwaysInline.h"
  348. #include "TCPackedCache.h"
  349. #include "TCPageMap.h"
  350. #include "TCSpinLock.h"
  351. #include "TCSystemAlloc.h"
  352. #include <algorithm>
  353. #include <pthread.h>
  354. #include <stdarg.h>
  355. #include <stddef.h>
  356. #include <stdint.h>
  357. #include <stdio.h>
  358. #if HAVE(ERRNO_H)
  359. #include <errno.h>
  360. #endif
  361. #if OS(UNIX)
  362. #include <unistd.h>
  363. #endif
  364. #if OS(WINDOWS)
  365. #ifndef WIN32_LEAN_AND_MEAN
  366. #define WIN32_LEAN_AND_MEAN
  367. #endif
  368. #include <windows.h>
  369. #endif
  370. #ifdef WTF_CHANGES
  371. #if OS(DARWIN)
  372. #include "MallocZoneSupport.h"
  373. #include <wtf/HashSet.h>
  374. #include <wtf/Vector.h>
  375. #endif
  376. #if HAVE(HEADER_DETECTION_H)
  377. #include "HeaderDetection.h"
  378. #endif
  379. #if HAVE(DISPATCH_H)
  380. #include <dispatch/dispatch.h>
  381. #endif
  382. #if HAVE(PTHREAD_MACHDEP_H)
  383. #include <System/pthread_machdep.h>
  384. #if defined(__PTK_FRAMEWORK_JAVASCRIPTCORE_KEY0)
  385. #define WTF_USE_PTHREAD_GETSPECIFIC_DIRECT 1
  386. #endif
  387. #endif
  388. #ifndef PRIuS
  389. #define PRIuS "zu"
  390. #endif
  391. // Calling pthread_getspecific through a global function pointer is faster than a normal
  392. // call to the function on Mac OS X, and it's used in performance-critical code. So we
  393. // use a function pointer. But that's not necessarily faster on other platforms, and we had
  394. // problems with this technique on Windows, so we'll do this only on Mac OS X.
  395. #if OS(DARWIN)
  396. #if !USE(PTHREAD_GETSPECIFIC_DIRECT)
  397. static void* (*pthread_getspecific_function_pointer)(pthread_key_t) = pthread_getspecific;
  398. #define pthread_getspecific(key) pthread_getspecific_function_pointer(key)
  399. #else
  400. #define pthread_getspecific(key) _pthread_getspecific_direct(key)
  401. #define pthread_setspecific(key, val) _pthread_setspecific_direct(key, (val))
  402. #endif
  403. #endif
  404. #define DEFINE_VARIABLE(type, name, value, meaning) \
  405. namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead { \
  406. type FLAGS_##name(value); \
  407. char FLAGS_no##name; \
  408. } \
  409. using FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead::FLAGS_##name
  410. #define DEFINE_int64(name, value, meaning) \
  411. DEFINE_VARIABLE(int64_t, name, value, meaning)
  412. #define DEFINE_double(name, value, meaning) \
  413. DEFINE_VARIABLE(double, name, value, meaning)
  414. namespace WTF {
  415. #define malloc fastMalloc
  416. #define calloc fastCalloc
  417. #define free fastFree
  418. #define realloc fastRealloc
  419. #define MESSAGE LOG_ERROR
  420. #define CHECK_CONDITION ASSERT
  421. #if OS(DARWIN)
  422. struct Span;
  423. class TCMalloc_Central_FreeListPadded;
  424. class TCMalloc_PageHeap;
  425. class TCMalloc_ThreadCache;
  426. template <typename T> class PageHeapAllocator;
  427. class FastMallocZone {
  428. public:
  429. static void init();
  430. static kern_return_t enumerate(task_t, void*, unsigned typeMmask, vm_address_t zoneAddress, memory_reader_t, vm_range_recorder_t);
  431. static size_t goodSize(malloc_zone_t*, size_t size) { return size; }
  432. static boolean_t check(malloc_zone_t*) { return true; }
  433. static void print(malloc_zone_t*, boolean_t) { }
  434. static void log(malloc_zone_t*, void*) { }
  435. static void forceLock(malloc_zone_t*) { }
  436. static void forceUnlock(malloc_zone_t*) { }
  437. static void statistics(malloc_zone_t*, malloc_statistics_t* stats) { memset(stats, 0, sizeof(malloc_statistics_t)); }
  438. private:
  439. FastMallocZone(TCMalloc_PageHeap*, TCMalloc_ThreadCache**, TCMalloc_Central_FreeListPadded*, PageHeapAllocator<Span>*, PageHeapAllocator<TCMalloc_ThreadCache>*);
  440. static size_t size(malloc_zone_t*, const void*);
  441. static void* zoneMalloc(malloc_zone_t*, size_t);
  442. static void* zoneCalloc(malloc_zone_t*, size_t numItems, size_t size);
  443. static void zoneFree(malloc_zone_t*, void*);
  444. static void* zoneRealloc(malloc_zone_t*, void*, size_t);
  445. static void* zoneValloc(malloc_zone_t*, size_t) { LOG_ERROR("valloc is not supported"); return 0; }
  446. static void zoneDestroy(malloc_zone_t*) { }
  447. malloc_zone_t m_zone;
  448. TCMalloc_PageHeap* m_pageHeap;
  449. TCMalloc_ThreadCache** m_threadHeaps;
  450. TCMalloc_Central_FreeListPadded* m_centralCaches;
  451. PageHeapAllocator<Span>* m_spanAllocator;
  452. PageHeapAllocator<TCMalloc_ThreadCache>* m_pageHeapAllocator;
  453. };
  454. #endif
  455. #endif
  456. #ifndef WTF_CHANGES
  457. // This #ifdef should almost never be set. Set NO_TCMALLOC_SAMPLES if
  458. // you're porting to a system where you really can't get a stacktrace.
  459. #ifdef NO_TCMALLOC_SAMPLES
  460. // We use #define so code compiles even if you #include stacktrace.h somehow.
  461. # define GetStackTrace(stack, depth, skip) (0)
  462. #else
  463. # include <google/stacktrace.h>
  464. #endif
  465. #endif
  466. // Even if we have support for thread-local storage in the compiler
  467. // and linker, the OS may not support it. We need to check that at
  468. // runtime. Right now, we have to keep a manual set of "bad" OSes.
  469. #if defined(HAVE_TLS)
  470. static bool kernel_supports_tls = false; // be conservative
  471. static inline bool KernelSupportsTLS() {
  472. return kernel_supports_tls;
  473. }
  474. # if !HAVE_DECL_UNAME // if too old for uname, probably too old for TLS
  475. static void CheckIfKernelSupportsTLS() {
  476. kernel_supports_tls = false;
  477. }
  478. # else
  479. # include <sys/utsname.h> // DECL_UNAME checked for <sys/utsname.h> too
  480. static void CheckIfKernelSupportsTLS() {
  481. struct utsname buf;
  482. if (uname(&buf) != 0) { // should be impossible
  483. MESSAGE("uname failed assuming no TLS support (errno=%d)\n", errno);
  484. kernel_supports_tls = false;
  485. } else if (strcasecmp(buf.sysname, "linux") == 0) {
  486. // The linux case: the first kernel to support TLS was 2.6.0
  487. if (buf.release[0] < '2' && buf.release[1] == '.') // 0.x or 1.x
  488. kernel_supports_tls = false;
  489. else if (buf.release[0] == '2' && buf.release[1] == '.' &&
  490. buf.release[2] >= '0' && buf.release[2] < '6' &&
  491. buf.release[3] == '.') // 2.0 - 2.5
  492. kernel_supports_tls = false;
  493. else
  494. kernel_supports_tls = true;
  495. } else { // some other kernel, we'll be optimisitic
  496. kernel_supports_tls = true;
  497. }
  498. // TODO(csilvers): VLOG(1) the tls status once we support RAW_VLOG
  499. }
  500. # endif // HAVE_DECL_UNAME
  501. #endif // HAVE_TLS
  502. // __THROW is defined in glibc systems. It means, counter-intuitively,
  503. // "This function will never throw an exception." It's an optional
  504. // optimization tool, but we may need to use it to match glibc prototypes.
  505. #ifndef __THROW // I guess we're not on a glibc system
  506. # define __THROW // __THROW is just an optimization, so ok to make it ""
  507. #endif
  508. //-------------------------------------------------------------------
  509. // Configuration
  510. //-------------------------------------------------------------------
  511. // Not all possible combinations of the following parameters make
  512. // sense. In particular, if kMaxSize increases, you may have to
  513. // increase kNumClasses as well.
  514. static const size_t kPageShift = 12;
  515. static const size_t kPageSize = 1 << kPageShift;
  516. static const size_t kMaxSize = 8u * kPageSize;
  517. static const size_t kAlignShift = 3;
  518. static const size_t kAlignment = 1 << kAlignShift;
  519. static const size_t kNumClasses = 68;
  520. // Allocates a big block of memory for the pagemap once we reach more than
  521. // 128MB
  522. static const size_t kPageMapBigAllocationThreshold = 128 << 20;
  523. // Minimum number of pages to fetch from system at a time. Must be
  524. // significantly bigger than kPageSize to amortize system-call
  525. // overhead, and also to reduce external fragementation. Also, we
  526. // should keep this value big because various incarnations of Linux
  527. // have small limits on the number of mmap() regions per
  528. // address-space.
  529. static const size_t kMinSystemAlloc = 1 << (20 - kPageShift);
  530. // Number of objects to move between a per-thread list and a central
  531. // list in one shot. We want this to be not too small so we can
  532. // amortize the lock overhead for accessing the central list. Making
  533. // it too big may temporarily cause unnecessary memory wastage in the
  534. // per-thread free list until the scavenger cleans up the list.
  535. static int num_objects_to_move[kNumClasses];
  536. // Maximum length we allow a per-thread free-list to have before we
  537. // move objects from it into the corresponding central free-list. We
  538. // want this big to avoid locking the central free-list too often. It
  539. // should not hurt to make this list somewhat big because the
  540. // scavenging code will shrink it down when its contents are not in use.
  541. static const int kMaxFreeListLength = 256;
  542. // Lower and upper bounds on the per-thread cache sizes
  543. static const size_t kMinThreadCacheSize = kMaxSize * 2;
  544. #if PLATFORM(IOS)
  545. static const size_t kMaxThreadCacheSize = 512 * 1024;
  546. #else
  547. static const size_t kMaxThreadCacheSize = 2 << 20;
  548. #endif
  549. // Default bound on the total amount of thread caches
  550. static const size_t kDefaultOverallThreadCacheSize = 16 << 20;
  551. // For all span-lengths < kMaxPages we keep an exact-size list.
  552. // REQUIRED: kMaxPages >= kMinSystemAlloc;
  553. static const size_t kMaxPages = kMinSystemAlloc;
  554. /* The smallest prime > 2^n */
  555. static int primes_list[] = {
  556. // Small values might cause high rates of sampling
  557. // and hence commented out.
  558. // 2, 5, 11, 17, 37, 67, 131, 257,
  559. // 521, 1031, 2053, 4099, 8209, 16411,
  560. 32771, 65537, 131101, 262147, 524309, 1048583,
  561. 2097169, 4194319, 8388617, 16777259, 33554467 };
  562. // Twice the approximate gap between sampling actions.
  563. // I.e., we take one sample approximately once every
  564. // tcmalloc_sample_parameter/2
  565. // bytes of allocation, i.e., ~ once every 128KB.
  566. // Must be a prime number.
  567. #ifdef NO_TCMALLOC_SAMPLES
  568. DEFINE_int64(tcmalloc_sample_parameter, 0,
  569. "Unused: code is compiled with NO_TCMALLOC_SAMPLES");
  570. static size_t sample_period = 0;
  571. #else
  572. DEFINE_int64(tcmalloc_sample_parameter, 262147,
  573. "Twice the approximate gap between sampling actions."
  574. " Must be a prime number. Otherwise will be rounded up to a "
  575. " larger prime number");
  576. static size_t sample_period = 262147;
  577. #endif
  578. // Protects sample_period above
  579. static SpinLock sample_period_lock = SPINLOCK_INITIALIZER;
  580. // Parameters for controlling how fast memory is returned to the OS.
  581. DEFINE_double(tcmalloc_release_rate, 1,
  582. "Rate at which we release unused memory to the system. "
  583. "Zero means we never release memory back to the system. "
  584. "Increase this flag to return memory faster; decrease it "
  585. "to return memory slower. Reasonable rates are in the "
  586. "range [0,10]");
  587. //-------------------------------------------------------------------
  588. // Mapping from size to size_class and vice versa
  589. //-------------------------------------------------------------------
  590. // Sizes <= 1024 have an alignment >= 8. So for such sizes we have an
  591. // array indexed by ceil(size/8). Sizes > 1024 have an alignment >= 128.
  592. // So for these larger sizes we have an array indexed by ceil(size/128).
  593. //
  594. // We flatten both logical arrays into one physical array and use
  595. // arithmetic to compute an appropriate index. The constants used by
  596. // ClassIndex() were selected to make the flattening work.
  597. //
  598. // Examples:
  599. // Size Expression Index
  600. // -------------------------------------------------------
  601. // 0 (0 + 7) / 8 0
  602. // 1 (1 + 7) / 8 1
  603. // ...
  604. // 1024 (1024 + 7) / 8 128
  605. // 1025 (1025 + 127 + (120<<7)) / 128 129
  606. // ...
  607. // 32768 (32768 + 127 + (120<<7)) / 128 376
  608. static const size_t kMaxSmallSize = 1024;
  609. static const int shift_amount[2] = { 3, 7 }; // For divides by 8 or 128
  610. static const int add_amount[2] = { 7, 127 + (120 << 7) };
  611. static unsigned char class_array[377];
  612. // Compute index of the class_array[] entry for a given size
  613. static inline int ClassIndex(size_t s) {
  614. const int i = (s > kMaxSmallSize);
  615. return static_cast<int>((s + add_amount[i]) >> shift_amount[i]);
  616. }
  617. // Mapping from size class to max size storable in that class
  618. static size_t class_to_size[kNumClasses];
  619. // Mapping from size class to number of pages to allocate at a time
  620. static size_t class_to_pages[kNumClasses];
  621. // TransferCache is used to cache transfers of num_objects_to_move[size_class]
  622. // back and forth between thread caches and the central cache for a given size
  623. // class.
  624. struct TCEntry {
  625. void *head; // Head of chain of objects.
  626. void *tail; // Tail of chain of objects.
  627. };
  628. // A central cache freelist can have anywhere from 0 to kNumTransferEntries
  629. // slots to put link list chains into. To keep memory usage bounded the total
  630. // number of TCEntries across size classes is fixed. Currently each size
  631. // class is initially given one TCEntry which also means that the maximum any
  632. // one class can have is kNumClasses.
  633. static const int kNumTransferEntries = kNumClasses;
  634. // Note: the following only works for "n"s that fit in 32-bits, but
  635. // that is fine since we only use it for small sizes.
  636. static inline int LgFloor(size_t n) {
  637. int log = 0;
  638. for (int i = 4; i >= 0; --i) {
  639. int shift = (1 << i);
  640. size_t x = n >> shift;
  641. if (x != 0) {
  642. n = x;
  643. log += shift;
  644. }
  645. }
  646. ASSERT(n == 1);
  647. return log;
  648. }
  649. // Some very basic linked list functions for dealing with using void * as
  650. // storage.
  651. static inline void *SLL_Next(void *t) {
  652. return *(reinterpret_cast<void**>(t));
  653. }
  654. static inline void SLL_SetNext(void *t, void *n) {
  655. *(reinterpret_cast<void**>(t)) = n;
  656. }
  657. static inline void SLL_Push(void **list, void *element) {
  658. SLL_SetNext(element, *list);
  659. *list = element;
  660. }
  661. static inline void *SLL_Pop(void **list) {
  662. void *result = *list;
  663. *list = SLL_Next(*list);
  664. return result;
  665. }
  666. // Remove N elements from a linked list to which head points. head will be
  667. // modified to point to the new head. start and end will point to the first
  668. // and last nodes of the range. Note that end will point to NULL after this
  669. // function is called.
  670. static inline void SLL_PopRange(void **head, int N, void **start, void **end) {
  671. if (N == 0) {
  672. *start = NULL;
  673. *end = NULL;
  674. return;
  675. }
  676. void *tmp = *head;
  677. for (int i = 1; i < N; ++i) {
  678. tmp = SLL_Next(tmp);
  679. }
  680. *start = *head;
  681. *end = tmp;
  682. *head = SLL_Next(tmp);
  683. // Unlink range from list.
  684. SLL_SetNext(tmp, NULL);
  685. }
  686. static inline void SLL_PushRange(void **head, void *start, void *end) {
  687. if (!start) return;
  688. SLL_SetNext(end, *head);
  689. *head = start;
  690. }
  691. static inline size_t SLL_Size(void *head) {
  692. int count = 0;
  693. while (head) {
  694. count++;
  695. head = SLL_Next(head);
  696. }
  697. return count;
  698. }
  699. // Setup helper functions.
  700. static ALWAYS_INLINE size_t SizeClass(size_t size) {
  701. return class_array[ClassIndex(size)];
  702. }
  703. // Get the byte-size for a specified class
  704. static ALWAYS_INLINE size_t ByteSizeForClass(size_t cl) {
  705. return class_to_size[cl];
  706. }
  707. static int NumMoveSize(size_t size) {
  708. if (size == 0) return 0;
  709. // Use approx 64k transfers between thread and central caches.
  710. int num = static_cast<int>(64.0 * 1024.0 / size);
  711. if (num < 2) num = 2;
  712. // Clamp well below kMaxFreeListLength to avoid ping pong between central
  713. // and thread caches.
  714. if (num > static_cast<int>(0.8 * kMaxFreeListLength))
  715. num = static_cast<int>(0.8 * kMaxFreeListLength);
  716. // Also, avoid bringing in too many objects into small object free
  717. // lists. There are lots of such lists, and if we allow each one to
  718. // fetch too many at a time, we end up having to scavenge too often
  719. // (especially when there are lots of threads and each thread gets a
  720. // small allowance for its thread cache).
  721. //
  722. // TODO: Make thread cache free list sizes dynamic so that we do not
  723. // have to equally divide a fixed resource amongst lots of threads.
  724. if (num > 32) num = 32;
  725. return num;
  726. }
  727. // Initialize the mapping arrays
  728. static void InitSizeClasses() {
  729. // Do some sanity checking on add_amount[]/shift_amount[]/class_array[]
  730. if (ClassIndex(0) < 0) {
  731. MESSAGE("Invalid class index %d for size 0\n", ClassIndex(0));
  732. CRASH();
  733. }
  734. if (static_cast<size_t>(ClassIndex(kMaxSize)) >= sizeof(class_array)) {
  735. MESSAGE("Invalid class index %d for kMaxSize\n", ClassIndex(kMaxSize));
  736. CRASH();
  737. }
  738. // Compute the size classes we want to use
  739. size_t sc = 1; // Next size class to assign
  740. unsigned char alignshift = kAlignShift;
  741. int last_lg = -1;
  742. for (size_t size = kAlignment; size <= kMaxSize; size += (1 << alignshift)) {
  743. int lg = LgFloor(size);
  744. if (lg > last_lg) {
  745. // Increase alignment every so often.
  746. //
  747. // Since we double the alignment every time size doubles and
  748. // size >= 128, this means that space wasted due to alignment is
  749. // at most 16/128 i.e., 12.5%. Plus we cap the alignment at 256
  750. // bytes, so the space wasted as a percentage starts falling for
  751. // sizes > 2K.
  752. if ((lg >= 7) && (alignshift < 8)) {
  753. alignshift++;
  754. }
  755. last_lg = lg;
  756. }
  757. // Allocate enough pages so leftover is less than 1/8 of total.
  758. // This bounds wasted space to at most 12.5%.
  759. size_t psize = kPageSize;
  760. while ((psize % size) > (psize >> 3)) {
  761. psize += kPageSize;
  762. }
  763. const size_t my_pages = psize >> kPageShift;
  764. if (sc > 1 && my_pages == class_to_pages[sc-1]) {
  765. // See if we can merge this into the previous class without
  766. // increasing the fragmentation of the previous class.
  767. const size_t my_objects = (my_pages << kPageShift) / size;
  768. const size_t prev_objects = (class_to_pages[sc-1] << kPageShift)
  769. / class_to_size[sc-1];
  770. if (my_objects == prev_objects) {
  771. // Adjust last class to include this size
  772. class_to_size[sc-1] = size;
  773. continue;
  774. }
  775. }
  776. // Add new class
  777. class_to_pages[sc] = my_pages;
  778. class_to_size[sc] = size;
  779. sc++;
  780. }
  781. if (sc != kNumClasses) {
  782. MESSAGE("wrong number of size classes: found %" PRIuS " instead of %d\n",
  783. sc, int(kNumClasses));
  784. CRASH();
  785. }
  786. // Initialize the mapping arrays
  787. int next_size = 0;
  788. for (unsigned char c = 1; c < kNumClasses; c++) {
  789. const size_t max_size_in_class = class_to_size[c];
  790. for (size_t s = next_size; s <= max_size_in_class; s += kAlignment) {
  791. class_array[ClassIndex(s)] = c;
  792. }
  793. next_size = static_cast<int>(max_size_in_class + kAlignment);
  794. }
  795. // Double-check sizes just to be safe
  796. for (size_t size = 0; size <= kMaxSize; size++) {
  797. const size_t sc = SizeClass(size);
  798. if (sc == 0) {
  799. MESSAGE("Bad size class %" PRIuS " for %" PRIuS "\n", sc, size);
  800. CRASH();
  801. }
  802. if (sc > 1 && size <= class_to_size[sc-1]) {
  803. MESSAGE("Allocating unnecessarily large class %" PRIuS " for %" PRIuS
  804. "\n", sc, size);
  805. CRASH();
  806. }
  807. if (sc >= kNumClasses) {
  808. MESSAGE("Bad size class %" PRIuS " for %" PRIuS "\n", sc, size);
  809. CRASH();
  810. }
  811. const size_t s = class_to_size[sc];
  812. if (size > s) {
  813. MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %" PRIuS ")\n", s, size, sc);
  814. CRASH();
  815. }
  816. if (s == 0) {
  817. MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %" PRIuS ")\n", s, size, sc);
  818. CRASH();
  819. }
  820. }
  821. // Initialize the num_objects_to_move array.
  822. for (size_t cl = 1; cl < kNumClasses; ++cl) {
  823. num_objects_to_move[cl] = NumMoveSize(ByteSizeForClass(cl));
  824. }
  825. #ifndef WTF_CHANGES
  826. if (false) {
  827. // Dump class sizes and maximum external wastage per size class
  828. for (size_t cl = 1; cl < kNumClasses; ++cl) {
  829. const int alloc_size = class_to_pages[cl] << kPageShift;
  830. const int alloc_objs = alloc_size / class_to_size[cl];
  831. const int min_used = (class_to_size[cl-1] + 1) * alloc_objs;
  832. const int max_waste = alloc_size - min_used;
  833. MESSAGE("SC %3d [ %8d .. %8d ] from %8d ; %2.0f%% maxwaste\n",
  834. int(cl),
  835. int(class_to_size[cl-1] + 1),
  836. int(class_to_size[cl]),
  837. int(class_to_pages[cl] << kPageShift),
  838. max_waste * 100.0 / alloc_size
  839. );
  840. }
  841. }
  842. #endif
  843. }
  844. // -------------------------------------------------------------------------
  845. // Simple allocator for objects of a specified type. External locking
  846. // is required before accessing one of these objects.
  847. // -------------------------------------------------------------------------
  848. // Metadata allocator -- keeps stats about how many bytes allocated
  849. static uint64_t metadata_system_bytes = 0;
  850. static void* MetaDataAlloc(size_t bytes) {
  851. void* result = TCMalloc_SystemAlloc(bytes, 0);
  852. if (result != NULL) {
  853. metadata_system_bytes += bytes;
  854. }
  855. return result;
  856. }
  857. template <class T>
  858. class PageHeapAllocator {
  859. private:
  860. // How much to allocate from system at a time
  861. static const size_t kAllocIncrement = 32 << 10;
  862. // Aligned size of T
  863. static const size_t kAlignedSize
  864. = (((sizeof(T) + kAlignment - 1) / kAlignment) * kAlignment);
  865. // Free area from which to carve new objects
  866. char* free_area_;
  867. size_t free_avail_;
  868. // Linked list of all regions allocated by this allocator
  869. void* allocated_regions_;
  870. // Free list of already carved objects
  871. void* free_list_;
  872. // Number of allocated but unfreed objects
  873. int inuse_;
  874. public:
  875. void Init() {
  876. ASSERT(kAlignedSize <= kAllocIncrement);
  877. inuse_ = 0;
  878. allocated_regions_ = 0;
  879. free_area_ = NULL;
  880. free_avail_ = 0;
  881. free_list_ = NULL;
  882. }
  883. T* New() {
  884. // Consult free list
  885. void* result;
  886. if (free_list_ != NULL) {
  887. result = free_list_;
  888. free_list_ = *(reinterpret_cast<void**>(result));
  889. } else {
  890. if (free_avail_ < kAlignedSize) {
  891. // Need more room
  892. char* new_allocation = reinterpret_cast<char*>(MetaDataAlloc(kAllocIncrement));
  893. if (!new_allocation)
  894. CRASH();
  895. *reinterpret_cast_ptr<void**>(new_allocation) = allocated_regions_;
  896. allocated_regions_ = new_allocation;
  897. free_area_ = new_allocation + kAlignedSize;
  898. free_avail_ = kAllocIncrement - kAlignedSize;
  899. }
  900. result = free_area_;
  901. free_area_ += kAlignedSize;
  902. free_avail_ -= kAlignedSize;
  903. }
  904. inuse_++;
  905. return reinterpret_cast<T*>(result);
  906. }
  907. void Delete(T* p) {
  908. *(reinterpret_cast<void**>(p)) = free_list_;
  909. free_list_ = p;
  910. inuse_--;
  911. }
  912. int inuse() const { return inuse_; }
  913. #if defined(WTF_CHANGES) && OS(DARWIN)
  914. template <class Recorder>
  915. void recordAdministrativeRegions(Recorder& recorder, const RemoteMemoryReader& reader)
  916. {
  917. for (void* adminAllocation = allocated_regions_; adminAllocation; adminAllocation = reader.nextEntryInLinkedList(reinterpret_cast<void**>(adminAllocation)))
  918. recorder.recordRegion(reinterpret_cast<vm_address_t>(adminAllocation), kAllocIncrement);
  919. }
  920. #endif
  921. };
  922. // -------------------------------------------------------------------------
  923. // Span - a contiguous run of pages
  924. // -------------------------------------------------------------------------
  925. // Type that can hold a page number
  926. typedef uintptr_t PageID;
  927. // Type that can hold the length of a run of pages
  928. typedef uintptr_t Length;
  929. static const Length kMaxValidPages = (~static_cast<Length>(0)) >> kPageShift;
  930. // Convert byte size into pages. This won't overflow, but may return
  931. // an unreasonably large value if bytes is huge enough.
  932. static inline Length pages(size_t bytes) {
  933. return (bytes >> kPageShift) +
  934. ((bytes & (kPageSize - 1)) > 0 ? 1 : 0);
  935. }
  936. // Convert a user size into the number of bytes that will actually be
  937. // allocated
  938. static size_t AllocationSize(size_t bytes) {
  939. if (bytes > kMaxSize) {
  940. // Large object: we allocate an integral number of pages
  941. ASSERT(bytes <= (kMaxValidPages << kPageShift));
  942. return pages(bytes) << kPageShift;
  943. } else {
  944. // Small object: find the size class to which it belongs
  945. return ByteSizeForClass(SizeClass(bytes));
  946. }
  947. }
  948. // Information kept for a span (a contiguous run of pages).
  949. struct Span {
  950. PageID start; // Starting page number
  951. Length length; // Number of pages in span
  952. Span* next; // Used when in link list
  953. Span* prev; // Used when in link list
  954. void* objects; // Linked list of free objects
  955. unsigned int free : 1; // Is the span free
  956. #ifndef NO_TCMALLOC_SAMPLES
  957. unsigned int sample : 1; // Sampled object?
  958. #endif
  959. unsigned int sizeclass : 8; // Size-class for small objects (or 0)
  960. unsigned int refcount : 11; // Number of non-free objects
  961. bool decommitted : 1;
  962. #undef SPAN_HISTORY
  963. #ifdef SPAN_HISTORY
  964. // For debugging, we can keep a log events per span
  965. int nexthistory;
  966. char history[64];
  967. int value[64];
  968. #endif
  969. };
  970. #define ASSERT_SPAN_COMMITTED(span) ASSERT(!span->decommitted)
  971. #ifdef SPAN_HISTORY
  972. void Event(Span* span, char op, int v = 0) {
  973. span->history[span->nexthistory] = op;
  974. span->value[span->nexthistory] = v;
  975. span->nexthistory++;
  976. if (span->nexthistory == sizeof(span->history)) span->nexthistory = 0;
  977. }
  978. #else
  979. #define Event(s,o,v) ((void) 0)
  980. #endif
  981. // Allocator/deallocator for spans
  982. static PageHeapAllocator<Span> span_allocator;
  983. static Span* NewSpan(PageID p, Length len) {
  984. Span* result = span_allocator.New();
  985. memset(result, 0, sizeof(*result));
  986. result->start = p;
  987. result->length = len;
  988. #ifdef SPAN_HISTORY
  989. result->nexthistory = 0;
  990. #endif
  991. return result;
  992. }
  993. static inline void DeleteSpan(Span* span) {
  994. #ifndef NDEBUG
  995. // In debug mode, trash the contents of deleted Spans
  996. memset(span, 0x3f, sizeof(*span));
  997. #endif
  998. span_allocator.Delete(span);
  999. }
  1000. // -------------------------------------------------------------------------
  1001. // Doubly linked list of spans.
  1002. // -------------------------------------------------------------------------
  1003. static inline void DLL_Init(Span* list) {
  1004. list->next = list;
  1005. list->prev = list;
  1006. }
  1007. static inline void DLL_Remove(Span* span) {
  1008. span->prev->next = span->next;
  1009. span->next->prev = span->prev;
  1010. span->prev = NULL;
  1011. span->next = NULL;
  1012. }
  1013. static ALWAYS_INLINE bool DLL_IsEmpty(const Span* list) {
  1014. return list->next == list;
  1015. }
  1016. static int DLL_Length(const Span* list) {
  1017. int result = 0;
  1018. for (Span* s = list->next; s != list; s = s->next) {
  1019. result++;
  1020. }
  1021. return result;
  1022. }
  1023. #if 0 /* Not needed at the moment -- causes compiler warnings if not used */
  1024. static void DLL_Print(const char* label, const Span* list) {
  1025. MESSAGE("%-10s %p:", label, list);
  1026. for (const Span* s = list->next; s != list; s = s->next) {
  1027. MESSAGE(" <%p,%u,%u>", s, s->start, s->length);
  1028. }
  1029. MESSAGE("\n");
  1030. }
  1031. #endif
  1032. static inline void DLL_Prepend(Span* list, Span* span) {
  1033. ASSERT(span->next == NULL);
  1034. ASSERT(span->prev == NULL);
  1035. span->next = list->next;
  1036. span->prev = list;
  1037. list->next->prev = span;
  1038. list->next = span;
  1039. }
  1040. // -------------------------------------------------------------------------
  1041. // Stack traces kept for sampled allocations
  1042. // The following state is protected by pageheap_lock_.
  1043. // -------------------------------------------------------------------------
  1044. // size/depth are made the same size as a pointer so that some generic
  1045. // code below can conveniently cast them back and forth to void*.
  1046. static const int kMaxStackDepth = 31;
  1047. struct StackTrace {
  1048. uintptr_t size; // Size of object
  1049. uintptr_t depth; // Number of PC values stored in array below
  1050. void* stack[kMaxStackDepth];
  1051. };
  1052. static PageHeapAllocator<StackTrace> stacktrace_allocator;
  1053. static Span sampled_objects;
  1054. // -------------------------------------------------------------------------
  1055. // Map from page-id to per-page data
  1056. // -------------------------------------------------------------------------
  1057. // We use PageMap2<> for 32-bit and PageMap3<> for 64-bit machines.
  1058. // We also use a simple one-level cache for hot PageID-to-sizeclass mappings,
  1059. // because sometimes the sizeclass is all the information we need.
  1060. // Selector class -- general selector uses 3-level map
  1061. template <int BITS> class MapSelector {
  1062. public:
  1063. typedef TCMalloc_PageMap3<BITS-kPageShift> Type;
  1064. typedef PackedCache<BITS, uint64_t> CacheType;
  1065. };
  1066. #if defined(WTF_CHANGES)
  1067. #if CPU(X86_64)
  1068. // On all known X86-64 platforms, the upper 16 bits are always unused and therefore
  1069. // can be excluded from the PageMap key.
  1070. // See http://en.wikipedia.org/wiki/X86-64#Virtual_address_space_details
  1071. static const size_t kBitsUnusedOn64Bit = 16;
  1072. #else
  1073. static const size_t kBitsUnusedOn64Bit = 0;
  1074. #endif
  1075. // A three-level map for 64-bit machines
  1076. template <> class MapSelector<64> {
  1077. public:
  1078. typedef TCMalloc_PageMap3<64 - kPageShift - kBitsUnusedOn64Bit> Type;
  1079. typedef PackedCache<64, uint64_t> CacheType;
  1080. };
  1081. #endif
  1082. // A two-level map for 32-bit machines
  1083. template <> class MapSelector<32> {
  1084. public:
  1085. typedef TCMalloc_PageMap2<32 - kPageShift> Type;
  1086. typedef PackedCache<32 - kPageShift, uint16_t> CacheType;
  1087. };
  1088. // -------------------------------------------------------------------------
  1089. // Page-level allocator
  1090. // * Eager coalescing
  1091. //
  1092. // Heap for page-level allocation. We allow allocating and freeing a
  1093. // contiguous runs of pages (called a "span").
  1094. // -------------------------------------------------------------------------
  1095. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1096. // The page heap maintains a free list for spans that are no longer in use by
  1097. // the central cache or any thread caches. We use a background thread to
  1098. // periodically scan the free list and release a percentage of it back to the OS.
  1099. // If free_committed_pages_ exceeds kMinimumFreeCommittedPageCount, the
  1100. // background thread:
  1101. // - wakes up
  1102. // - pauses for kScavengeDelayInSeconds
  1103. // - returns to the OS a percentage of the memory that remained unused during
  1104. // that pause (kScavengePercentage * min_free_committed_pages_since_last_scavenge_)
  1105. // The goal of this strategy is to reduce memory pressure in a timely fashion
  1106. // while avoiding thrashing the OS allocator.
  1107. // Time delay before the page heap scavenger will consider returning pages to
  1108. // the OS.
  1109. static const int kScavengeDelayInSeconds = 2;
  1110. // Approximate percentage of free committed pages to return to the OS in one
  1111. // scavenge.
  1112. static const float kScavengePercentage = .5f;
  1113. // number of span lists to keep spans in when memory is returned.
  1114. static const int kMinSpanListsWithSpans = 32;
  1115. // Number of free committed pages that we want to keep around. The minimum number of pages used when there
  1116. // is 1 span in each of the first kMinSpanListsWithSpans spanlists. Currently 528 pages.
  1117. static const size_t kMinimumFreeCommittedPageCount = kMinSpanListsWithSpans * ((1.0f+kMinSpanListsWithSpans) / 2.0f);
  1118. #endif
  1119. static SpinLock pageheap_lock = SPINLOCK_INITIALIZER;
  1120. class TCMalloc_PageHeap {
  1121. public:
  1122. void init();
  1123. // Allocate a run of "n" pages. Returns zero if out of memory.
  1124. Span* New(Length n);
  1125. // Delete the span "[p, p+n-1]".
  1126. // REQUIRES: span was returned by earlier call to New() and
  1127. // has not yet been deleted.
  1128. void Delete(Span* span);
  1129. // Mark an allocated span as being used for small objects of the
  1130. // specified size-class.
  1131. // REQUIRES: span was returned by an earlier call to New()
  1132. // and has not yet been deleted.
  1133. void RegisterSizeClass(Span* span, size_t sc);
  1134. // Split an allocated span into two spans: one of length "n" pages
  1135. // followed by another span of length "span->length - n" pages.
  1136. // Modifies "*span" to point to the first span of length "n" pages.
  1137. // Returns a pointer to the second span.
  1138. //
  1139. // REQUIRES: "0 < n < span->length"
  1140. // REQUIRES: !span->free
  1141. // REQUIRES: span->sizeclass == 0
  1142. Span* Split(Span* span, Length n);
  1143. // Return the descriptor for the specified page.
  1144. inline Span* GetDescriptor(PageID p) const {
  1145. return reinterpret_cast<Span*>(pagemap_.get(p));
  1146. }
  1147. #ifdef WTF_CHANGES
  1148. inline Span* GetDescriptorEnsureSafe(PageID p)
  1149. {
  1150. pagemap_.Ensure(p, 1);
  1151. return GetDescriptor(p);
  1152. }
  1153. size_t ReturnedBytes() const;
  1154. #endif
  1155. // Dump state to stderr
  1156. #ifndef WTF_CHANGES
  1157. void Dump(TCMalloc_Printer* out);
  1158. #endif
  1159. // Return number of bytes allocated from system
  1160. inline uint64_t SystemBytes() const { return system_bytes_; }
  1161. // Return number of free bytes in heap
  1162. uint64_t FreeBytes() const {
  1163. return (static_cast<uint64_t>(free_pages_) << kPageShift);
  1164. }
  1165. bool Check();
  1166. size_t CheckList(Span* list, Length min_pages, Length max_pages, bool decommitted);
  1167. // Release all pages on the free list for reuse by the OS:
  1168. void ReleaseFreePages();
  1169. void ReleaseFreeList(Span*, Span*);
  1170. // Return 0 if we have no information, or else the correct sizeclass for p.
  1171. // Reads and writes to pagemap_cache_ do not require locking.
  1172. // The entries are 64 bits on 64-bit hardware and 16 bits on
  1173. // 32-bit hardware, and we don't mind raciness as long as each read of
  1174. // an entry yields a valid entry, not a partially updated entry.
  1175. size_t GetSizeClassIfCached(PageID p) const {
  1176. return pagemap_cache_.GetOrDefault(p, 0);
  1177. }
  1178. void CacheSizeClass(PageID p, size_t cl) const { pagemap_cache_.Put(p, cl); }
  1179. private:
  1180. // Pick the appropriate map and cache types based on pointer size
  1181. typedef MapSelector<8*sizeof(uintptr_t)>::Type PageMap;
  1182. typedef MapSelector<8*sizeof(uintptr_t)>::CacheType PageMapCache;
  1183. PageMap pagemap_;
  1184. mutable PageMapCache pagemap_cache_;
  1185. // We segregate spans of a given size into two circular linked
  1186. // lists: one for normal spans, and one for spans whose memory
  1187. // has been returned to the system.
  1188. struct SpanList {
  1189. Span normal;
  1190. Span returned;
  1191. };
  1192. // List of free spans of length >= kMaxPages
  1193. SpanList large_;
  1194. // Array mapping from span length to a doubly linked list of free spans
  1195. SpanList free_[kMaxPages];
  1196. // Number of pages kept in free lists
  1197. uintptr_t free_pages_;
  1198. // Bytes allocated from system
  1199. uint64_t system_bytes_;
  1200. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1201. // Number of pages kept in free lists that are still committed.
  1202. Length free_committed_pages_;
  1203. // Minimum number of free committed pages since last scavenge. (Can be 0 if
  1204. // we've committed new pages since the last scavenge.)
  1205. Length min_free_committed_pages_since_last_scavenge_;
  1206. #endif
  1207. bool GrowHeap(Length n);
  1208. // REQUIRES span->length >= n
  1209. // Remove span from its free list, and move any leftover part of
  1210. // span into appropriate free lists. Also update "span" to have
  1211. // length exactly "n" and mark it as non-free so it can be returned
  1212. // to the client.
  1213. //
  1214. // "released" is true iff "span" was found on a "returned" list.
  1215. void Carve(Span* span, Length n, bool released);
  1216. void RecordSpan(Span* span) {
  1217. pagemap_.set(span->start, span);
  1218. if (span->length > 1) {
  1219. pagemap_.set(span->start + span->length - 1, span);
  1220. }
  1221. }
  1222. // Allocate a large span of length == n. If successful, returns a
  1223. // span of exactly the specified length. Else, returns NULL.
  1224. Span* AllocLarge(Length n);
  1225. #if !USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1226. // Incrementally release some memory to the system.
  1227. // IncrementalScavenge(n) is called whenever n pages are freed.
  1228. void IncrementalScavenge(Length n);
  1229. #endif
  1230. // Number of pages to deallocate before doing more scavenging
  1231. int64_t scavenge_counter_;
  1232. // Index of last free list we scavenged
  1233. size_t scavenge_index_;
  1234. #if defined(WTF_CHANGES) && OS(DARWIN)
  1235. friend class FastMallocZone;
  1236. #endif
  1237. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1238. void initializeScavenger();
  1239. ALWAYS_INLINE void signalScavenger();
  1240. void scavenge();
  1241. ALWAYS_INLINE bool shouldScavenge() const;
  1242. #if HAVE(DISPATCH_H) || OS(WINDOWS)
  1243. void periodicScavenge();
  1244. ALWAYS_INLINE bool isScavengerSuspended();
  1245. ALWAYS_INLINE void scheduleScavenger();
  1246. ALWAYS_INLINE void rescheduleScavenger();
  1247. ALWAYS_INLINE void suspendScavenger();
  1248. #endif
  1249. #if HAVE(DISPATCH_H)
  1250. dispatch_queue_t m_scavengeQueue;
  1251. dispatch_source_t m_scavengeTimer;
  1252. bool m_scavengingSuspended;
  1253. #elif OS(WINDOWS)
  1254. static void CALLBACK scavengerTimerFired(void*, BOOLEAN);
  1255. HANDLE m_scavengeQueueTimer;
  1256. #else
  1257. static NO_RETURN_WITH_VALUE void* runScavengerThread(void*);
  1258. NO_RETURN void scavengerThread();
  1259. // Keeps track of whether the background thread is actively scavenging memory every kScavengeDelayInSeconds, or
  1260. // it's blocked waiting for more pages to be deleted.
  1261. bool m_scavengeThreadActive;
  1262. pthread_mutex_t m_scavengeMutex;
  1263. pthread_cond_t m_scavengeCondition;
  1264. #endif
  1265. #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1266. };
  1267. void TCMalloc_PageHeap::init()
  1268. {
  1269. pagemap_.init(MetaDataAlloc);
  1270. pagemap_cache_ = PageMapCache(0);
  1271. free_pages_ = 0;
  1272. system_bytes_ = 0;
  1273. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1274. free_committed_pages_ = 0;
  1275. min_free_committed_pages_since_last_scavenge_ = 0;
  1276. #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1277. scavenge_counter_ = 0;
  1278. // Start scavenging at kMaxPages list
  1279. scavenge_index_ = kMaxPages-1;
  1280. COMPILE_ASSERT(kNumClasses <= (1 << PageMapCache::kValuebits), valuebits);
  1281. DLL_Init(&large_.normal);
  1282. DLL_Init(&large_.returned);
  1283. for (size_t i = 0; i < kMaxPages; i++) {
  1284. DLL_Init(&free_[i].normal);
  1285. DLL_Init(&free_[i].returned);
  1286. }
  1287. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1288. initializeScavenger();
  1289. #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1290. }
  1291. #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
  1292. #if HAVE(DISPATCH_H)
  1293. void TCMalloc_PageHeap::initializeScavenger()
  1294. {
  1295. m_scavengeQueue = dispatch_queue_create("com.apple.JavaScriptCore.FastMallocSavenger", NULL);
  1296. m_scavengeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, m_scavengeQueue);
  1297. dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, kScavengeDelayInSeconds * NSEC_PER_SEC);
  1298. dispatch_source_set_timer(m_scavengeTimer, startTime, kScavengeDelayInSeconds * NSEC_PER_SEC, 1000 * NSEC_PER_USEC);
  1299. dispatch_source_set_event_handler(m_scavengeTimer, ^{ periodicScavenge(); });
  1300. m_scavengingSuspended = true;
  1301. }
  1302. ALWAYS_INLINE bool TCMalloc_PageHeap::isScavengerSuspended()
  1303. {
  1304. ASSERT(pageheap_lock.IsHeld());
  1305. return m_scavengingSuspended;
  1306. }
  1307. ALWAYS_INLINE void TCMalloc_PageHeap::scheduleScavenger()
  1308. {
  1309. ASSERT(pageheap_lock.IsHeld());
  1310. m_scavengingSuspended = false;
  1311. dispatch_resume(m_scav

Large files files are truncated, but you can click here to view the full file