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

/Source/JavaScriptCore/wtf/FastMalloc.cpp

https://bitbucket.org/codefirex/external_webkit
C++ | 4626 lines | 3257 code | 645 blank | 724 comment | 544 complexity | 0acf3c415fe5f364536a7e2c9c2efcf3 MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-2.0, BSD-3-Clause

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 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::scavenger

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