1 // Copyright (c) 2005, 2007, Google Inc.
2 // All rights reserved.
3 // Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
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
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.
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.
32 // Author: Sanjay Ghemawat <opensource@google.com>
34 // A malloc that uses a per-thread cache to satisfy small malloc requests.
35 // (The time for malloc/free of a small object drops from 300 ns to 50 ns.)
37 // See doc/tcmalloc.html for a high-level
38 // description of how this malloc works.
41 // 1. The thread-specific lists are accessed without acquiring any locks.
42 // This is safe because each such list is only accessed by one thread.
43 // 2. We have a lock per central free-list, and hold it while manipulating
44 // the central free list for a particular size.
45 // 3. The central page allocator is protected by "pageheap_lock".
46 // 4. The pagemap (which maps from page-number to descriptor),
47 // can be read without holding any locks, and written while holding
48 // the "pageheap_lock".
49 // 5. To improve performance, a subset of the information one can get
50 // from the pagemap is cached in a data structure, pagemap_cache_,
51 // that atomically reads and writes its entries. This cache can be
52 // read and written without locking.
54 // This multi-threaded access to the pagemap is safe for fairly
55 // subtle reasons. We basically assume that when an object X is
56 // allocated by thread A and deallocated by thread B, there must
57 // have been appropriate synchronization in the handoff of object
58 // X from thread A to thread B. The same logic applies to pagemap_cache_.
60 // THE PAGEID-TO-SIZECLASS CACHE
61 // Hot PageID-to-sizeclass mappings are held by pagemap_cache_. If this cache
62 // returns 0 for a particular PageID then that means "no information," not that
63 // the sizeclass is 0. The cache may have stale information for pages that do
64 // not hold the beginning of any free()'able object. Staleness is eliminated
65 // in Populate() for pages with sizeclass > 0 objects, and in do_malloc() and
66 // do_memalign() for all other relevant pages.
68 // TODO: Bias reclamation to larger addresses
69 // TODO: implement mallinfo/mallopt
70 // TODO: Better testing
72 // 9/28/2003 (new page-level allocator replaces ptmalloc2):
73 // * malloc/free of small objects goes from ~300 ns to ~50 ns.
74 // * allocation of a reasonably complicated struct
75 // goes from about 1100 ns to about 300 ns.
78 #include "FastMalloc.h"
80 #include "Assertions.h"
82 #if ENABLE(JSC_MULTIPLE_THREADS)
86 #ifndef NO_TCMALLOC_SAMPLES
88 #define NO_TCMALLOC_SAMPLES
92 #if !(defined(USE_SYSTEM_MALLOC) && USE_SYSTEM_MALLOC) && defined(NDEBUG)
93 #define FORCE_SYSTEM_MALLOC 0
95 #define FORCE_SYSTEM_MALLOC 1
98 // Use a background thread to periodically scavenge memory to release back to the system
99 // 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.
100 #if defined(BUILDING_ON_TIGER)
101 #define USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY 0
103 #define USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY 1
109 #if ENABLE(JSC_MULTIPLE_THREADS)
110 static pthread_key_t isForbiddenKey;
111 static pthread_once_t isForbiddenKeyOnce = PTHREAD_ONCE_INIT;
112 static void initializeIsForbiddenKey()
114 pthread_key_create(&isForbiddenKey, 0);
118 static bool isForbidden()
120 pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
121 return !!pthread_getspecific(isForbiddenKey);
125 void fastMallocForbid()
127 pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
128 pthread_setspecific(isForbiddenKey, &isForbiddenKey);
131 void fastMallocAllow()
133 pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
134 pthread_setspecific(isForbiddenKey, 0);
139 static bool staticIsForbidden;
140 static bool isForbidden()
142 return staticIsForbidden;
145 void fastMallocForbid()
147 staticIsForbidden = true;
150 void fastMallocAllow()
152 staticIsForbidden = false;
154 #endif // ENABLE(JSC_MULTIPLE_THREADS)
163 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
167 void fastMallocMatchFailed(void*)
172 } // namespace Internal
176 void* fastZeroedMalloc(size_t n)
178 void* result = fastMalloc(n);
179 memset(result, 0, n);
183 char* fastStrDup(const char* src)
185 int len = strlen(src) + 1;
186 char* dup = static_cast<char*>(fastMalloc(len));
189 memcpy(dup, src, len);
194 TryMallocReturnValue tryFastZeroedMalloc(size_t n)
197 if (!tryFastMalloc(n).getValue(result))
199 memset(result, 0, n);
205 #if FORCE_SYSTEM_MALLOC
208 #include "brew/SystemMallocBrew.h"
212 #include <malloc/malloc.h>
219 TryMallocReturnValue tryFastMalloc(size_t n)
221 ASSERT(!isForbidden());
223 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
224 if (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= n) // If overflow would occur...
227 void* result = malloc(n + sizeof(AllocAlignmentInteger));
231 *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
232 result = static_cast<AllocAlignmentInteger*>(result) + 1;
240 void* fastMalloc(size_t n)
242 ASSERT(!isForbidden());
244 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
245 TryMallocReturnValue returnValue = tryFastMalloc(n);
247 returnValue.getValue(result);
249 void* result = malloc(n);
254 // The behavior of malloc(0) is implementation defined.
255 // To make sure that fastMalloc never returns 0, retry with fastMalloc(1).
257 return fastMalloc(1);
265 TryMallocReturnValue tryFastCalloc(size_t n_elements, size_t element_size)
267 ASSERT(!isForbidden());
269 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
270 size_t totalBytes = n_elements * element_size;
271 if (n_elements > 1 && element_size && (totalBytes / element_size) != n_elements || (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= totalBytes))
274 totalBytes += sizeof(AllocAlignmentInteger);
275 void* result = malloc(totalBytes);
279 memset(result, 0, totalBytes);
280 *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
281 result = static_cast<AllocAlignmentInteger*>(result) + 1;
284 return calloc(n_elements, element_size);
288 void* fastCalloc(size_t n_elements, size_t element_size)
290 ASSERT(!isForbidden());
292 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
293 TryMallocReturnValue returnValue = tryFastCalloc(n_elements, element_size);
295 returnValue.getValue(result);
297 void* result = calloc(n_elements, element_size);
302 // If either n_elements or element_size is 0, the behavior of calloc is implementation defined.
303 // To make sure that fastCalloc never returns 0, retry with fastCalloc(1, 1).
304 if (!n_elements || !element_size)
305 return fastCalloc(1, 1);
313 void fastFree(void* p)
315 ASSERT(!isForbidden());
317 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
321 AllocAlignmentInteger* header = Internal::fastMallocMatchValidationValue(p);
322 if (*header != Internal::AllocTypeMalloc)
323 Internal::fastMallocMatchFailed(p);
330 TryMallocReturnValue tryFastRealloc(void* p, size_t n)
332 ASSERT(!isForbidden());
334 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
336 if (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= n) // If overflow would occur...
338 AllocAlignmentInteger* header = Internal::fastMallocMatchValidationValue(p);
339 if (*header != Internal::AllocTypeMalloc)
340 Internal::fastMallocMatchFailed(p);
341 void* result = realloc(header, n + sizeof(AllocAlignmentInteger));
345 // This should not be needed because the value is already there:
346 // *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
347 result = static_cast<AllocAlignmentInteger*>(result) + 1;
350 return fastMalloc(n);
353 return realloc(p, n);
357 void* fastRealloc(void* p, size_t n)
359 ASSERT(!isForbidden());
361 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
362 TryMallocReturnValue returnValue = tryFastRealloc(p, n);
364 returnValue.getValue(result);
366 void* result = realloc(p, n);
374 void releaseFastMallocFreeMemory() { }
376 FastMallocStatistics fastMallocStatistics()
378 FastMallocStatistics statistics = { 0, 0, 0 };
382 size_t fastMallocSize(const void* p)
385 return malloc_size(p);
387 return _msize(const_cast<void*>(p));
396 // This symbol is present in the JavaScriptCore exports file even when FastMalloc is disabled.
397 // It will never be used in this case, so it's type and value are less interesting than its presence.
398 extern "C" const int jscore_fastmalloc_introspection = 0;
401 #else // FORCE_SYSTEM_MALLOC
405 #elif HAVE(INTTYPES_H)
406 #include <inttypes.h>
408 #include <sys/types.h>
411 #include "AlwaysInline.h"
412 #include "Assertions.h"
413 #include "TCPackedCache.h"
414 #include "TCPageMap.h"
415 #include "TCSpinLock.h"
416 #include "TCSystemAlloc.h"
428 #ifndef WIN32_LEAN_AND_MEAN
429 #define WIN32_LEAN_AND_MEAN
437 #include "MallocZoneSupport.h"
438 #include <wtf/HashSet.h>
439 #include <wtf/Vector.h>
442 #include <dispatch/dispatch.h>
450 // Calling pthread_getspecific through a global function pointer is faster than a normal
451 // call to the function on Mac OS X, and it's used in performance-critical code. So we
452 // use a function pointer. But that's not necessarily faster on other platforms, and we had
453 // problems with this technique on Windows, so we'll do this only on Mac OS X.
455 static void* (*pthread_getspecific_function_pointer)(pthread_key_t) = pthread_getspecific;
456 #define pthread_getspecific(key) pthread_getspecific_function_pointer(key)
459 #define DEFINE_VARIABLE(type, name, value, meaning) \
460 namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead { \
461 type FLAGS_##name(value); \
462 char FLAGS_no##name; \
464 using FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead::FLAGS_##name
466 #define DEFINE_int64(name, value, meaning) \
467 DEFINE_VARIABLE(int64_t, name, value, meaning)
469 #define DEFINE_double(name, value, meaning) \
470 DEFINE_VARIABLE(double, name, value, meaning)
474 #define malloc fastMalloc
475 #define calloc fastCalloc
476 #define free fastFree
477 #define realloc fastRealloc
479 #define MESSAGE LOG_ERROR
480 #define CHECK_CONDITION ASSERT
484 class TCMalloc_Central_FreeListPadded;
485 class TCMalloc_PageHeap;
486 class TCMalloc_ThreadCache;
487 template <typename T> class PageHeapAllocator;
489 class FastMallocZone {
493 static kern_return_t enumerate(task_t, void*, unsigned typeMmask, vm_address_t zoneAddress, memory_reader_t, vm_range_recorder_t);
494 static size_t goodSize(malloc_zone_t*, size_t size) { return size; }
495 static boolean_t check(malloc_zone_t*) { return true; }
496 static void print(malloc_zone_t*, boolean_t) { }
497 static void log(malloc_zone_t*, void*) { }
498 static void forceLock(malloc_zone_t*) { }
499 static void forceUnlock(malloc_zone_t*) { }
500 static void statistics(malloc_zone_t*, malloc_statistics_t* stats) { memset(stats, 0, sizeof(malloc_statistics_t)); }
503 FastMallocZone(TCMalloc_PageHeap*, TCMalloc_ThreadCache**, TCMalloc_Central_FreeListPadded*, PageHeapAllocator<Span>*, PageHeapAllocator<TCMalloc_ThreadCache>*);
504 static size_t size(malloc_zone_t*, const void*);
505 static void* zoneMalloc(malloc_zone_t*, size_t);
506 static void* zoneCalloc(malloc_zone_t*, size_t numItems, size_t size);
507 static void zoneFree(malloc_zone_t*, void*);
508 static void* zoneRealloc(malloc_zone_t*, void*, size_t);
509 static void* zoneValloc(malloc_zone_t*, size_t) { LOG_ERROR("valloc is not supported"); return 0; }
510 static void zoneDestroy(malloc_zone_t*) { }
512 malloc_zone_t m_zone;
513 TCMalloc_PageHeap* m_pageHeap;
514 TCMalloc_ThreadCache** m_threadHeaps;
515 TCMalloc_Central_FreeListPadded* m_centralCaches;
516 PageHeapAllocator<Span>* m_spanAllocator;
517 PageHeapAllocator<TCMalloc_ThreadCache>* m_pageHeapAllocator;
525 // This #ifdef should almost never be set. Set NO_TCMALLOC_SAMPLES if
526 // you're porting to a system where you really can't get a stacktrace.
527 #ifdef NO_TCMALLOC_SAMPLES
528 // We use #define so code compiles even if you #include stacktrace.h somehow.
529 # define GetStackTrace(stack, depth, skip) (0)
531 # include <google/stacktrace.h>
535 // Even if we have support for thread-local storage in the compiler
536 // and linker, the OS may not support it. We need to check that at
537 // runtime. Right now, we have to keep a manual set of "bad" OSes.
538 #if defined(HAVE_TLS)
539 static bool kernel_supports_tls = false; // be conservative
540 static inline bool KernelSupportsTLS() {
541 return kernel_supports_tls;
543 # if !HAVE_DECL_UNAME // if too old for uname, probably too old for TLS
544 static void CheckIfKernelSupportsTLS() {
545 kernel_supports_tls = false;
548 # include <sys/utsname.h> // DECL_UNAME checked for <sys/utsname.h> too
549 static void CheckIfKernelSupportsTLS() {
551 if (uname(&buf) != 0) { // should be impossible
552 MESSAGE("uname failed assuming no TLS support (errno=%d)\n", errno);
553 kernel_supports_tls = false;
554 } else if (strcasecmp(buf.sysname, "linux") == 0) {
555 // The linux case: the first kernel to support TLS was 2.6.0
556 if (buf.release[0] < '2' && buf.release[1] == '.') // 0.x or 1.x
557 kernel_supports_tls = false;
558 else if (buf.release[0] == '2' && buf.release[1] == '.' &&
559 buf.release[2] >= '0' && buf.release[2] < '6' &&
560 buf.release[3] == '.') // 2.0 - 2.5
561 kernel_supports_tls = false;
563 kernel_supports_tls = true;
564 } else { // some other kernel, we'll be optimisitic
565 kernel_supports_tls = true;
567 // TODO(csilvers): VLOG(1) the tls status once we support RAW_VLOG
569 # endif // HAVE_DECL_UNAME
572 // __THROW is defined in glibc systems. It means, counter-intuitively,
573 // "This function will never throw an exception." It's an optional
574 // optimization tool, but we may need to use it to match glibc prototypes.
575 #ifndef __THROW // I guess we're not on a glibc system
576 # define __THROW // __THROW is just an optimization, so ok to make it ""
579 //-------------------------------------------------------------------
581 //-------------------------------------------------------------------
583 // Not all possible combinations of the following parameters make
584 // sense. In particular, if kMaxSize increases, you may have to
585 // increase kNumClasses as well.
586 static const size_t kPageShift = 12;
587 static const size_t kPageSize = 1 << kPageShift;
588 static const size_t kMaxSize = 8u * kPageSize;
589 static const size_t kAlignShift = 3;
590 static const size_t kAlignment = 1 << kAlignShift;
591 static const size_t kNumClasses = 68;
593 // Allocates a big block of memory for the pagemap once we reach more than
595 static const size_t kPageMapBigAllocationThreshold = 128 << 20;
597 // Minimum number of pages to fetch from system at a time. Must be
598 // significantly bigger than kPageSize to amortize system-call
599 // overhead, and also to reduce external fragementation. Also, we
600 // should keep this value big because various incarnations of Linux
601 // have small limits on the number of mmap() regions per
603 static const size_t kMinSystemAlloc = 1 << (20 - kPageShift);
605 // Number of objects to move between a per-thread list and a central
606 // list in one shot. We want this to be not too small so we can
607 // amortize the lock overhead for accessing the central list. Making
608 // it too big may temporarily cause unnecessary memory wastage in the
609 // per-thread free list until the scavenger cleans up the list.
610 static int num_objects_to_move[kNumClasses];
612 // Maximum length we allow a per-thread free-list to have before we
613 // move objects from it into the corresponding central free-list. We
614 // want this big to avoid locking the central free-list too often. It
615 // should not hurt to make this list somewhat big because the
616 // scavenging code will shrink it down when its contents are not in use.
617 static const int kMaxFreeListLength = 256;
619 // Lower and upper bounds on the per-thread cache sizes
620 static const size_t kMinThreadCacheSize = kMaxSize * 2;
621 static const size_t kMaxThreadCacheSize = 2 << 20;
623 // Default bound on the total amount of thread caches
624 static const size_t kDefaultOverallThreadCacheSize = 16 << 20;
626 // For all span-lengths < kMaxPages we keep an exact-size list.
627 // REQUIRED: kMaxPages >= kMinSystemAlloc;
628 static const size_t kMaxPages = kMinSystemAlloc;
630 /* The smallest prime > 2^n */
631 static int primes_list[] = {
632 // Small values might cause high rates of sampling
633 // and hence commented out.
634 // 2, 5, 11, 17, 37, 67, 131, 257,
635 // 521, 1031, 2053, 4099, 8209, 16411,
636 32771, 65537, 131101, 262147, 524309, 1048583,
637 2097169, 4194319, 8388617, 16777259, 33554467 };
639 // Twice the approximate gap between sampling actions.
640 // I.e., we take one sample approximately once every
641 // tcmalloc_sample_parameter/2
642 // bytes of allocation, i.e., ~ once every 128KB.
643 // Must be a prime number.
644 #ifdef NO_TCMALLOC_SAMPLES
645 DEFINE_int64(tcmalloc_sample_parameter, 0,
646 "Unused: code is compiled with NO_TCMALLOC_SAMPLES");
647 static size_t sample_period = 0;
649 DEFINE_int64(tcmalloc_sample_parameter, 262147,
650 "Twice the approximate gap between sampling actions."
651 " Must be a prime number. Otherwise will be rounded up to a "
652 " larger prime number");
653 static size_t sample_period = 262147;
656 // Protects sample_period above
657 static SpinLock sample_period_lock = SPINLOCK_INITIALIZER;
659 // Parameters for controlling how fast memory is returned to the OS.
661 DEFINE_double(tcmalloc_release_rate, 1,
662 "Rate at which we release unused memory to the system. "
663 "Zero means we never release memory back to the system. "
664 "Increase this flag to return memory faster; decrease it "
665 "to return memory slower. Reasonable rates are in the "
668 //-------------------------------------------------------------------
669 // Mapping from size to size_class and vice versa
670 //-------------------------------------------------------------------
672 // Sizes <= 1024 have an alignment >= 8. So for such sizes we have an
673 // array indexed by ceil(size/8). Sizes > 1024 have an alignment >= 128.
674 // So for these larger sizes we have an array indexed by ceil(size/128).
676 // We flatten both logical arrays into one physical array and use
677 // arithmetic to compute an appropriate index. The constants used by
678 // ClassIndex() were selected to make the flattening work.
681 // Size Expression Index
682 // -------------------------------------------------------
686 // 1024 (1024 + 7) / 8 128
687 // 1025 (1025 + 127 + (120<<7)) / 128 129
689 // 32768 (32768 + 127 + (120<<7)) / 128 376
690 static const size_t kMaxSmallSize = 1024;
691 static const int shift_amount[2] = { 3, 7 }; // For divides by 8 or 128
692 static const int add_amount[2] = { 7, 127 + (120 << 7) };
693 static unsigned char class_array[377];
695 // Compute index of the class_array[] entry for a given size
696 static inline int ClassIndex(size_t s) {
697 const int i = (s > kMaxSmallSize);
698 return static_cast<int>((s + add_amount[i]) >> shift_amount[i]);
701 // Mapping from size class to max size storable in that class
702 static size_t class_to_size[kNumClasses];
704 // Mapping from size class to number of pages to allocate at a time
705 static size_t class_to_pages[kNumClasses];
707 // TransferCache is used to cache transfers of num_objects_to_move[size_class]
708 // back and forth between thread caches and the central cache for a given size
711 void *head; // Head of chain of objects.
712 void *tail; // Tail of chain of objects.
714 // A central cache freelist can have anywhere from 0 to kNumTransferEntries
715 // slots to put link list chains into. To keep memory usage bounded the total
716 // number of TCEntries across size classes is fixed. Currently each size
717 // class is initially given one TCEntry which also means that the maximum any
718 // one class can have is kNumClasses.
719 static const int kNumTransferEntries = kNumClasses;
721 // Note: the following only works for "n"s that fit in 32-bits, but
722 // that is fine since we only use it for small sizes.
723 static inline int LgFloor(size_t n) {
725 for (int i = 4; i >= 0; --i) {
726 int shift = (1 << i);
727 size_t x = n >> shift;
737 // Some very basic linked list functions for dealing with using void * as
740 static inline void *SLL_Next(void *t) {
741 return *(reinterpret_cast<void**>(t));
744 static inline void SLL_SetNext(void *t, void *n) {
745 *(reinterpret_cast<void**>(t)) = n;
748 static inline void SLL_Push(void **list, void *element) {
749 SLL_SetNext(element, *list);
753 static inline void *SLL_Pop(void **list) {
754 void *result = *list;
755 *list = SLL_Next(*list);
760 // Remove N elements from a linked list to which head points. head will be
761 // modified to point to the new head. start and end will point to the first
762 // and last nodes of the range. Note that end will point to NULL after this
763 // function is called.
764 static inline void SLL_PopRange(void **head, int N, void **start, void **end) {
772 for (int i = 1; i < N; ++i) {
778 *head = SLL_Next(tmp);
779 // Unlink range from list.
780 SLL_SetNext(tmp, NULL);
783 static inline void SLL_PushRange(void **head, void *start, void *end) {
785 SLL_SetNext(end, *head);
789 static inline size_t SLL_Size(void *head) {
793 head = SLL_Next(head);
798 // Setup helper functions.
800 static ALWAYS_INLINE size_t SizeClass(size_t size) {
801 return class_array[ClassIndex(size)];
804 // Get the byte-size for a specified class
805 static ALWAYS_INLINE size_t ByteSizeForClass(size_t cl) {
806 return class_to_size[cl];
808 static int NumMoveSize(size_t size) {
809 if (size == 0) return 0;
810 // Use approx 64k transfers between thread and central caches.
811 int num = static_cast<int>(64.0 * 1024.0 / size);
812 if (num < 2) num = 2;
813 // Clamp well below kMaxFreeListLength to avoid ping pong between central
814 // and thread caches.
815 if (num > static_cast<int>(0.8 * kMaxFreeListLength))
816 num = static_cast<int>(0.8 * kMaxFreeListLength);
818 // Also, avoid bringing in too many objects into small object free
819 // lists. There are lots of such lists, and if we allow each one to
820 // fetch too many at a time, we end up having to scavenge too often
821 // (especially when there are lots of threads and each thread gets a
822 // small allowance for its thread cache).
824 // TODO: Make thread cache free list sizes dynamic so that we do not
825 // have to equally divide a fixed resource amongst lots of threads.
826 if (num > 32) num = 32;
831 // Initialize the mapping arrays
832 static void InitSizeClasses() {
833 // Do some sanity checking on add_amount[]/shift_amount[]/class_array[]
834 if (ClassIndex(0) < 0) {
835 MESSAGE("Invalid class index %d for size 0\n", ClassIndex(0));
838 if (static_cast<size_t>(ClassIndex(kMaxSize)) >= sizeof(class_array)) {
839 MESSAGE("Invalid class index %d for kMaxSize\n", ClassIndex(kMaxSize));
843 // Compute the size classes we want to use
844 size_t sc = 1; // Next size class to assign
845 unsigned char alignshift = kAlignShift;
847 for (size_t size = kAlignment; size <= kMaxSize; size += (1 << alignshift)) {
848 int lg = LgFloor(size);
850 // Increase alignment every so often.
852 // Since we double the alignment every time size doubles and
853 // size >= 128, this means that space wasted due to alignment is
854 // at most 16/128 i.e., 12.5%. Plus we cap the alignment at 256
855 // bytes, so the space wasted as a percentage starts falling for
857 if ((lg >= 7) && (alignshift < 8)) {
863 // Allocate enough pages so leftover is less than 1/8 of total.
864 // This bounds wasted space to at most 12.5%.
865 size_t psize = kPageSize;
866 while ((psize % size) > (psize >> 3)) {
869 const size_t my_pages = psize >> kPageShift;
871 if (sc > 1 && my_pages == class_to_pages[sc-1]) {
872 // See if we can merge this into the previous class without
873 // increasing the fragmentation of the previous class.
874 const size_t my_objects = (my_pages << kPageShift) / size;
875 const size_t prev_objects = (class_to_pages[sc-1] << kPageShift)
876 / class_to_size[sc-1];
877 if (my_objects == prev_objects) {
878 // Adjust last class to include this size
879 class_to_size[sc-1] = size;
885 class_to_pages[sc] = my_pages;
886 class_to_size[sc] = size;
889 if (sc != kNumClasses) {
890 MESSAGE("wrong number of size classes: found %" PRIuS " instead of %d\n",
891 sc, int(kNumClasses));
895 // Initialize the mapping arrays
897 for (unsigned char c = 1; c < kNumClasses; c++) {
898 const size_t max_size_in_class = class_to_size[c];
899 for (size_t s = next_size; s <= max_size_in_class; s += kAlignment) {
900 class_array[ClassIndex(s)] = c;
902 next_size = static_cast<int>(max_size_in_class + kAlignment);
905 // Double-check sizes just to be safe
906 for (size_t size = 0; size <= kMaxSize; size++) {
907 const size_t sc = SizeClass(size);
909 MESSAGE("Bad size class %" PRIuS " for %" PRIuS "\n", sc, size);
912 if (sc > 1 && size <= class_to_size[sc-1]) {
913 MESSAGE("Allocating unnecessarily large class %" PRIuS " for %" PRIuS
917 if (sc >= kNumClasses) {
918 MESSAGE("Bad size class %" PRIuS " for %" PRIuS "\n", sc, size);
921 const size_t s = class_to_size[sc];
923 MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %" PRIuS ")\n", s, size, sc);
927 MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %" PRIuS ")\n", s, size, sc);
932 // Initialize the num_objects_to_move array.
933 for (size_t cl = 1; cl < kNumClasses; ++cl) {
934 num_objects_to_move[cl] = NumMoveSize(ByteSizeForClass(cl));
939 // Dump class sizes and maximum external wastage per size class
940 for (size_t cl = 1; cl < kNumClasses; ++cl) {
941 const int alloc_size = class_to_pages[cl] << kPageShift;
942 const int alloc_objs = alloc_size / class_to_size[cl];
943 const int min_used = (class_to_size[cl-1] + 1) * alloc_objs;
944 const int max_waste = alloc_size - min_used;
945 MESSAGE("SC %3d [ %8d .. %8d ] from %8d ; %2.0f%% maxwaste\n",
947 int(class_to_size[cl-1] + 1),
948 int(class_to_size[cl]),
949 int(class_to_pages[cl] << kPageShift),
950 max_waste * 100.0 / alloc_size
957 // -------------------------------------------------------------------------
958 // Simple allocator for objects of a specified type. External locking
959 // is required before accessing one of these objects.
960 // -------------------------------------------------------------------------
962 // Metadata allocator -- keeps stats about how many bytes allocated
963 static uint64_t metadata_system_bytes = 0;
964 static void* MetaDataAlloc(size_t bytes) {
965 void* result = TCMalloc_SystemAlloc(bytes, 0);
966 if (result != NULL) {
967 metadata_system_bytes += bytes;
973 class PageHeapAllocator {
975 // How much to allocate from system at a time
976 static const size_t kAllocIncrement = 32 << 10;
979 static const size_t kAlignedSize
980 = (((sizeof(T) + kAlignment - 1) / kAlignment) * kAlignment);
982 // Free area from which to carve new objects
986 // Linked list of all regions allocated by this allocator
987 void* allocated_regions_;
989 // Free list of already carved objects
992 // Number of allocated but unfreed objects
997 ASSERT(kAlignedSize <= kAllocIncrement);
999 allocated_regions_ = 0;
1006 // Consult free list
1008 if (free_list_ != NULL) {
1009 result = free_list_;
1010 free_list_ = *(reinterpret_cast<void**>(result));
1012 if (free_avail_ < kAlignedSize) {
1014 char* new_allocation = reinterpret_cast<char*>(MetaDataAlloc(kAllocIncrement));
1015 if (!new_allocation)
1018 *(void**)new_allocation = allocated_regions_;
1019 allocated_regions_ = new_allocation;
1020 free_area_ = new_allocation + kAlignedSize;
1021 free_avail_ = kAllocIncrement - kAlignedSize;
1023 result = free_area_;
1024 free_area_ += kAlignedSize;
1025 free_avail_ -= kAlignedSize;
1028 return reinterpret_cast<T*>(result);
1032 *(reinterpret_cast<void**>(p)) = free_list_;
1037 int inuse() const { return inuse_; }
1039 #if defined(WTF_CHANGES) && OS(DARWIN)
1040 template <class Recorder>
1041 void recordAdministrativeRegions(Recorder& recorder, const RemoteMemoryReader& reader)
1043 vm_address_t adminAllocation = reinterpret_cast<vm_address_t>(allocated_regions_);
1044 while (adminAllocation) {
1045 recorder.recordRegion(adminAllocation, kAllocIncrement);
1046 adminAllocation = *reader(reinterpret_cast<vm_address_t*>(adminAllocation));
1052 // -------------------------------------------------------------------------
1053 // Span - a contiguous run of pages
1054 // -------------------------------------------------------------------------
1056 // Type that can hold a page number
1057 typedef uintptr_t PageID;
1059 // Type that can hold the length of a run of pages
1060 typedef uintptr_t Length;
1062 static const Length kMaxValidPages = (~static_cast<Length>(0)) >> kPageShift;
1064 // Convert byte size into pages. This won't overflow, but may return
1065 // an unreasonably large value if bytes is huge enough.
1066 static inline Length pages(size_t bytes) {
1067 return (bytes >> kPageShift) +
1068 ((bytes & (kPageSize - 1)) > 0 ? 1 : 0);
1071 // Convert a user size into the number of bytes that will actually be
1073 static size_t AllocationSize(size_t bytes) {
1074 if (bytes > kMaxSize) {
1075 // Large object: we allocate an integral number of pages
1076 ASSERT(bytes <= (kMaxValidPages << kPageShift));
1077 return pages(bytes) << kPageShift;
1079 // Small object: find the size class to which it belongs
1080 return ByteSizeForClass(SizeClass(bytes));
1084 // Information kept for a span (a contiguous run of pages).
1086 PageID start; // Starting page number
1087 Length length; // Number of pages in span
1088 Span* next; // Used when in link list
1089 Span* prev; // Used when in link list
1090 void* objects; // Linked list of free objects
1091 unsigned int free : 1; // Is the span free
1092 #ifndef NO_TCMALLOC_SAMPLES
1093 unsigned int sample : 1; // Sampled object?
1095 unsigned int sizeclass : 8; // Size-class for small objects (or 0)
1096 unsigned int refcount : 11; // Number of non-free objects
1097 bool decommitted : 1;
1101 // For debugging, we can keep a log events per span
1108 #define ASSERT_SPAN_COMMITTED(span) ASSERT(!span->decommitted)
1111 void Event(Span* span, char op, int v = 0) {
1112 span->history[span->nexthistory] = op;
1113 span->value[span->nexthistory] = v;
1114 span->nexthistory++;
1115 if (span->nexthistory == sizeof(span->history)) span->nexthistory = 0;
1118 #define Event(s,o,v) ((void) 0)
1121 // Allocator/deallocator for spans
1122 static PageHeapAllocator<Span> span_allocator;
1123 static Span* NewSpan(PageID p, Length len) {
1124 Span* result = span_allocator.New();
1125 memset(result, 0, sizeof(*result));
1127 result->length = len;
1129 result->nexthistory = 0;
1134 static inline void DeleteSpan(Span* span) {
1136 // In debug mode, trash the contents of deleted Spans
1137 memset(span, 0x3f, sizeof(*span));
1139 span_allocator.Delete(span);
1142 // -------------------------------------------------------------------------
1143 // Doubly linked list of spans.
1144 // -------------------------------------------------------------------------
1146 static inline void DLL_Init(Span* list) {
1151 static inline void DLL_Remove(Span* span) {
1152 span->prev->next = span->next;
1153 span->next->prev = span->prev;
1158 static ALWAYS_INLINE bool DLL_IsEmpty(const Span* list) {
1159 return list->next == list;
1162 static int DLL_Length(const Span* list) {
1164 for (Span* s = list->next; s != list; s = s->next) {
1170 #if 0 /* Not needed at the moment -- causes compiler warnings if not used */
1171 static void DLL_Print(const char* label, const Span* list) {
1172 MESSAGE("%-10s %p:", label, list);
1173 for (const Span* s = list->next; s != list; s = s->next) {
1174 MESSAGE(" <%p,%u,%u>", s, s->start, s->length);
1180 static inline void DLL_Prepend(Span* list, Span* span) {
1181 ASSERT(span->next == NULL);
1182 ASSERT(span->prev == NULL);
1183 span->next = list->next;
1185 list->next->prev = span;
1189 // -------------------------------------------------------------------------
1190 // Stack traces kept for sampled allocations
1191 // The following state is protected by pageheap_lock_.
1192 // -------------------------------------------------------------------------
1194 // size/depth are made the same size as a pointer so that some generic
1195 // code below can conveniently cast them back and forth to void*.
1196 static const int kMaxStackDepth = 31;
1198 uintptr_t size; // Size of object
1199 uintptr_t depth; // Number of PC values stored in array below
1200 void* stack[kMaxStackDepth];
1202 static PageHeapAllocator<StackTrace> stacktrace_allocator;
1203 static Span sampled_objects;
1205 // -------------------------------------------------------------------------
1206 // Map from page-id to per-page data
1207 // -------------------------------------------------------------------------
1209 // We use PageMap2<> for 32-bit and PageMap3<> for 64-bit machines.
1210 // We also use a simple one-level cache for hot PageID-to-sizeclass mappings,
1211 // because sometimes the sizeclass is all the information we need.
1213 // Selector class -- general selector uses 3-level map
1214 template <int BITS> class MapSelector {
1216 typedef TCMalloc_PageMap3<BITS-kPageShift> Type;
1217 typedef PackedCache<BITS, uint64_t> CacheType;
1220 #if defined(WTF_CHANGES)
1222 // On all known X86-64 platforms, the upper 16 bits are always unused and therefore
1223 // can be excluded from the PageMap key.
1224 // See http://en.wikipedia.org/wiki/X86-64#Virtual_address_space_details
1226 static const size_t kBitsUnusedOn64Bit = 16;
1228 static const size_t kBitsUnusedOn64Bit = 0;
1231 // A three-level map for 64-bit machines
1232 template <> class MapSelector<64> {
1234 typedef TCMalloc_PageMap3<64 - kPageShift - kBitsUnusedOn64Bit> Type;
1235 typedef PackedCache<64, uint64_t> CacheType;
1239 // A two-level map for 32-bit machines
1240 template <> class MapSelector<32> {
1242 typedef TCMalloc_PageMap2<32 - kPageShift> Type;
1243 typedef PackedCache<32 - kPageShift, uint16_t> CacheType;
1246 // -------------------------------------------------------------------------
1247 // Page-level allocator
1248 // * Eager coalescing
1250 // Heap for page-level allocation. We allow allocating and freeing a
1251 // contiguous runs of pages (called a "span").
1252 // -------------------------------------------------------------------------
1254 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1255 // The page heap maintains a free list for spans that are no longer in use by
1256 // the central cache or any thread caches. We use a background thread to
1257 // periodically scan the free list and release a percentage of it back to the OS.
1259 // If free_committed_pages_ exceeds kMinimumFreeCommittedPageCount, the
1260 // background thread:
1262 // - pauses for kScavengeDelayInSeconds
1263 // - returns to the OS a percentage of the memory that remained unused during
1264 // that pause (kScavengePercentage * min_free_committed_pages_since_last_scavenge_)
1265 // The goal of this strategy is to reduce memory pressure in a timely fashion
1266 // while avoiding thrashing the OS allocator.
1268 // Time delay before the page heap scavenger will consider returning pages to
1270 static const int kScavengeDelayInSeconds = 2;
1272 // Approximate percentage of free committed pages to return to the OS in one
1274 static const float kScavengePercentage = .5f;
1276 // Number of free committed pages that we want to keep around.
1277 static const size_t kMinimumFreeCommittedPageCount = 512;
1281 class TCMalloc_PageHeap {
1285 // Allocate a run of "n" pages. Returns zero if out of memory.
1286 Span* New(Length n);
1288 // Delete the span "[p, p+n-1]".
1289 // REQUIRES: span was returned by earlier call to New() and
1290 // has not yet been deleted.
1291 void Delete(Span* span);
1293 // Mark an allocated span as being used for small objects of the
1294 // specified size-class.
1295 // REQUIRES: span was returned by an earlier call to New()
1296 // and has not yet been deleted.
1297 void RegisterSizeClass(Span* span, size_t sc);
1299 // Split an allocated span into two spans: one of length "n" pages
1300 // followed by another span of length "span->length - n" pages.
1301 // Modifies "*span" to point to the first span of length "n" pages.
1302 // Returns a pointer to the second span.
1304 // REQUIRES: "0 < n < span->length"
1305 // REQUIRES: !span->free
1306 // REQUIRES: span->sizeclass == 0
1307 Span* Split(Span* span, Length n);
1309 // Return the descriptor for the specified page.
1310 inline Span* GetDescriptor(PageID p) const {
1311 return reinterpret_cast<Span*>(pagemap_.get(p));
1315 inline Span* GetDescriptorEnsureSafe(PageID p)
1317 pagemap_.Ensure(p, 1);
1318 return GetDescriptor(p);
1321 size_t ReturnedBytes() const;
1324 // Dump state to stderr
1326 void Dump(TCMalloc_Printer* out);
1329 // Return number of bytes allocated from system
1330 inline uint64_t SystemBytes() const { return system_bytes_; }
1332 // Return number of free bytes in heap
1333 uint64_t FreeBytes() const {
1334 return (static_cast<uint64_t>(free_pages_) << kPageShift);
1338 bool CheckList(Span* list, Length min_pages, Length max_pages);
1340 // Release all pages on the free list for reuse by the OS:
1341 void ReleaseFreePages();
1343 // Return 0 if we have no information, or else the correct sizeclass for p.
1344 // Reads and writes to pagemap_cache_ do not require locking.
1345 // The entries are 64 bits on 64-bit hardware and 16 bits on
1346 // 32-bit hardware, and we don't mind raciness as long as each read of
1347 // an entry yields a valid entry, not a partially updated entry.
1348 size_t GetSizeClassIfCached(PageID p) const {
1349 return pagemap_cache_.GetOrDefault(p, 0);
1351 void CacheSizeClass(PageID p, size_t cl) const { pagemap_cache_.Put(p, cl); }
1354 // Pick the appropriate map and cache types based on pointer size
1355 typedef MapSelector<8*sizeof(uintptr_t)>::Type PageMap;
1356 typedef MapSelector<8*sizeof(uintptr_t)>::CacheType PageMapCache;
1358 mutable PageMapCache pagemap_cache_;
1360 // We segregate spans of a given size into two circular linked
1361 // lists: one for normal spans, and one for spans whose memory
1362 // has been returned to the system.
1368 // List of free spans of length >= kMaxPages
1371 // Array mapping from span length to a doubly linked list of free spans
1372 SpanList free_[kMaxPages];
1374 // Number of pages kept in free lists
1375 uintptr_t free_pages_;
1377 // Bytes allocated from system
1378 uint64_t system_bytes_;
1380 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1381 // Number of pages kept in free lists that are still committed.
1382 Length free_committed_pages_;
1384 // Minimum number of free committed pages since last scavenge. (Can be 0 if
1385 // we've committed new pages since the last scavenge.)
1386 Length min_free_committed_pages_since_last_scavenge_;
1389 bool GrowHeap(Length n);
1391 // REQUIRES span->length >= n
1392 // Remove span from its free list, and move any leftover part of
1393 // span into appropriate free lists. Also update "span" to have
1394 // length exactly "n" and mark it as non-free so it can be returned
1397 // "released" is true iff "span" was found on a "returned" list.
1398 void Carve(Span* span, Length n, bool released);
1400 void RecordSpan(Span* span) {
1401 pagemap_.set(span->start, span);
1402 if (span->length > 1) {
1403 pagemap_.set(span->start + span->length - 1, span);
1407 // Allocate a large span of length == n. If successful, returns a
1408 // span of exactly the specified length. Else, returns NULL.
1409 Span* AllocLarge(Length n);
1411 #if !USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1412 // Incrementally release some memory to the system.
1413 // IncrementalScavenge(n) is called whenever n pages are freed.
1414 void IncrementalScavenge(Length n);
1417 // Number of pages to deallocate before doing more scavenging
1418 int64_t scavenge_counter_;
1420 // Index of last free list we scavenged
1421 size_t scavenge_index_;
1423 #if defined(WTF_CHANGES) && OS(DARWIN)
1424 friend class FastMallocZone;
1427 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1428 void initializeScavenger();
1429 ALWAYS_INLINE void signalScavenger();
1431 ALWAYS_INLINE bool shouldScavenge() const;
1433 #if !HAVE(DISPATCH_H)
1434 static NO_RETURN_WITH_VALUE void* runScavengerThread(void*);
1435 NO_RETURN void scavengerThread();
1437 // Keeps track of whether the background thread is actively scavenging memory every kScavengeDelayInSeconds, or
1438 // it's blocked waiting for more pages to be deleted.
1439 bool m_scavengeThreadActive;
1441 pthread_mutex_t m_scavengeMutex;
1442 pthread_cond_t m_scavengeCondition;
1443 #else // !HAVE(DISPATCH_H)
1444 void periodicScavenge();
1446 dispatch_queue_t m_scavengeQueue;
1447 dispatch_source_t m_scavengeTimer;
1448 bool m_scavengingScheduled;
1451 #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1454 void TCMalloc_PageHeap::init()
1456 pagemap_.init(MetaDataAlloc);
1457 pagemap_cache_ = PageMapCache(0);
1461 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1462 free_committed_pages_ = 0;
1463 min_free_committed_pages_since_last_scavenge_ = 0;
1464 #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1466 scavenge_counter_ = 0;
1467 // Start scavenging at kMaxPages list
1468 scavenge_index_ = kMaxPages-1;
1469 COMPILE_ASSERT(kNumClasses <= (1 << PageMapCache::kValuebits), valuebits);
1470 DLL_Init(&large_.normal);
1471 DLL_Init(&large_.returned);
1472 for (size_t i = 0; i < kMaxPages; i++) {
1473 DLL_Init(&free_[i].normal);
1474 DLL_Init(&free_[i].returned);
1477 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1478 initializeScavenger();
1479 #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1482 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1484 #if !HAVE(DISPATCH_H)
1486 void TCMalloc_PageHeap::initializeScavenger()
1488 pthread_mutex_init(&m_scavengeMutex, 0);
1489 pthread_cond_init(&m_scavengeCondition, 0);
1490 m_scavengeThreadActive = true;
1492 pthread_create(&thread, 0, runScavengerThread, this);
1495 void* TCMalloc_PageHeap::runScavengerThread(void* context)
1497 static_cast<TCMalloc_PageHeap*>(context)->scavengerThread();
1499 // Without this, Visual Studio will complain that this method does not return a value.
1504 ALWAYS_INLINE void TCMalloc_PageHeap::signalScavenger()
1506 if (!m_scavengeThreadActive && shouldScavenge())
1507 pthread_cond_signal(&m_scavengeCondition);
1510 #else // !HAVE(DISPATCH_H)
1512 void TCMalloc_PageHeap::initializeScavenger()
1514 m_scavengeQueue = dispatch_queue_create("com.apple.JavaScriptCore.FastMallocSavenger", NULL);
1515 m_scavengeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, m_scavengeQueue);
1516 dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, kScavengeDelayInSeconds * NSEC_PER_SEC);
1517 dispatch_source_set_timer(m_scavengeTimer, startTime, kScavengeDelayInSeconds * NSEC_PER_SEC, 1000 * NSEC_PER_USEC);
1518 dispatch_source_set_event_handler(m_scavengeTimer, ^{ periodicScavenge(); });
1519 m_scavengingScheduled = false;
1522 ALWAYS_INLINE void TCMalloc_PageHeap::signalScavenger()
1524 if (!m_scavengingScheduled && shouldScavenge()) {
1525 m_scavengingScheduled = true;
1526 dispatch_resume(m_scavengeTimer);
1532 void TCMalloc_PageHeap::scavenge()
1534 size_t pagesToRelease = min_free_committed_pages_since_last_scavenge_ * kScavengePercentage;
1535 size_t targetPageCount = std::max<size_t>(kMinimumFreeCommittedPageCount, free_committed_pages_ - pagesToRelease);
1537 for (int i = kMaxPages; i >= 0 && free_committed_pages_ > targetPageCount; i--) {
1538 SpanList* slist = (static_cast<size_t>(i) == kMaxPages) ? &large_ : &free_[i];
1539 while (!DLL_IsEmpty(&slist->normal) && free_committed_pages_ > targetPageCount) {
1540 Span* s = slist->normal.prev;
1542 ASSERT(!s->decommitted);
1543 if (!s->decommitted) {
1544 TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
1545 static_cast<size_t>(s->length << kPageShift));
1546 ASSERT(free_committed_pages_ >= s->length);
1547 free_committed_pages_ -= s->length;
1548 s->decommitted = true;
1550 DLL_Prepend(&slist->returned, s);
1554 min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
1557 ALWAYS_INLINE bool TCMalloc_PageHeap::shouldScavenge() const
1559 return free_committed_pages_ > kMinimumFreeCommittedPageCount;
1562 #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1564 inline Span* TCMalloc_PageHeap::New(Length n) {
1568 // Find first size >= n that has a non-empty list
1569 for (Length s = n; s < kMaxPages; s++) {
1571 bool released = false;
1572 if (!DLL_IsEmpty(&free_[s].normal)) {
1573 // Found normal span
1574 ll = &free_[s].normal;
1575 } else if (!DLL_IsEmpty(&free_[s].returned)) {
1576 // Found returned span; reallocate it
1577 ll = &free_[s].returned;
1580 // Keep looking in larger classes
1584 Span* result = ll->next;
1585 Carve(result, n, released);
1586 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1587 // The newly allocated memory is from a span that's in the normal span list (already committed). Update the
1588 // free committed pages count.
1589 ASSERT(free_committed_pages_ >= n);
1590 free_committed_pages_ -= n;
1591 if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
1592 min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
1593 #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1599 Span* result = AllocLarge(n);
1600 if (result != NULL) {
1601 ASSERT_SPAN_COMMITTED(result);
1605 // Grow the heap and try again
1611 return AllocLarge(n);
1614 Span* TCMalloc_PageHeap::AllocLarge(Length n) {
1615 // find the best span (closest to n in size).
1616 // The following loops implements address-ordered best-fit.
1617 bool from_released = false;
1620 // Search through normal list
1621 for (Span* span = large_.normal.next;
1622 span != &large_.normal;
1623 span = span->next) {
1624 if (span->length >= n) {
1626 || (span->length < best->length)
1627 || ((span->length == best->length) && (span->start < best->start))) {
1629 from_released = false;
1634 // Search through released list in case it has a better fit
1635 for (Span* span = large_.returned.next;
1636 span != &large_.returned;
1637 span = span->next) {
1638 if (span->length >= n) {
1640 || (span->length < best->length)
1641 || ((span->length == best->length) && (span->start < best->start))) {
1643 from_released = true;
1649 Carve(best, n, from_released);
1650 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1651 // The newly allocated memory is from a span that's in the normal span list (already committed). Update the
1652 // free committed pages count.
1653 ASSERT(free_committed_pages_ >= n);
1654 free_committed_pages_ -= n;
1655 if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
1656 min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
1657 #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1665 Span* TCMalloc_PageHeap::Split(Span* span, Length n) {
1667 ASSERT(n < span->length);
1668 ASSERT(!span->free);
1669 ASSERT(span->sizeclass == 0);
1670 Event(span, 'T', n);
1672 const Length extra = span->length - n;
1673 Span* leftover = NewSpan(span->start + n, extra);
1674 Event(leftover, 'U', extra);
1675 RecordSpan(leftover);
1676 pagemap_.set(span->start + n - 1, span); // Update map from pageid to span
1682 inline void TCMalloc_PageHeap::Carve(Span* span, Length n, bool released) {
1686 Event(span, 'A', n);
1689 // If the span chosen to carve from is decommited, commit the entire span at once to avoid committing spans 1 page at a time.
1690 ASSERT(span->decommitted);
1691 TCMalloc_SystemCommit(reinterpret_cast<void*>(span->start << kPageShift), static_cast<size_t>(span->length << kPageShift));
1692 span->decommitted = false;
1693 free_committed_pages_ += span->length;
1696 const int extra = static_cast<int>(span->length - n);
1699 Span* leftover = NewSpan(span->start + n, extra);
1701 leftover->decommitted = false;
1702 Event(leftover, 'S', extra);
1703 RecordSpan(leftover);
1705 // Place leftover span on appropriate free list
1706 SpanList* listpair = (static_cast<size_t>(extra) < kMaxPages) ? &free_[extra] : &large_;
1707 Span* dst = &listpair->normal;
1708 DLL_Prepend(dst, leftover);
1711 pagemap_.set(span->start + n - 1, span);
1715 static ALWAYS_INLINE void mergeDecommittedStates(Span* destination, Span* other)
1717 if (destination->decommitted && !other->decommitted) {
1718 TCMalloc_SystemRelease(reinterpret_cast<void*>(other->start << kPageShift),
1719 static_cast<size_t>(other->length << kPageShift));
1720 } else if (other->decommitted && !destination->decommitted) {
1721 TCMalloc_SystemRelease(reinterpret_cast<void*>(destination->start << kPageShift),
1722 static_cast<size_t>(destination->length << kPageShift));
1723 destination->decommitted = true;
1727 inline void TCMalloc_PageHeap::Delete(Span* span) {
1729 ASSERT(!span->free);
1730 ASSERT(span->length > 0);
1731 ASSERT(GetDescriptor(span->start) == span);
1732 ASSERT(GetDescriptor(span->start + span->length - 1) == span);
1733 span->sizeclass = 0;
1734 #ifndef NO_TCMALLOC_SAMPLES
1738 // Coalesce -- we guarantee that "p" != 0, so no bounds checking
1739 // necessary. We do not bother resetting the stale pagemap
1740 // entries for the pieces we are merging together because we only
1741 // care about the pagemap entries for the boundaries.
1742 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1743 // Track the total size of the neighboring free spans that are committed.
1744 Length neighboringCommittedSpansLength = 0;
1746 const PageID p = span->start;
1747 const Length n = span->length;
1748 Span* prev = GetDescriptor(p-1);
1749 if (prev != NULL && prev->free) {
1750 // Merge preceding span into this span
1751 ASSERT(prev->start + prev->length == p);
1752 const Length len = prev->length;
1753 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1754 if (!prev->decommitted)
1755 neighboringCommittedSpansLength += len;
1757 mergeDecommittedStates(span, prev);
1761 span->length += len;
1762 pagemap_.set(span->start, span);
1763 Event(span, 'L', len);
1765 Span* next = GetDescriptor(p+n);
1766 if (next != NULL && next->free) {
1767 // Merge next span into this span
1768 ASSERT(next->start == p+n);
1769 const Length len = next->length;
1770 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1771 if (!next->decommitted)
1772 neighboringCommittedSpansLength += len;
1774 mergeDecommittedStates(span, next);
1777 span->length += len;
1778 pagemap_.set(span->start + span->length - 1, span);
1779 Event(span, 'R', len);
1782 Event(span, 'D', span->length);
1784 if (span->decommitted) {
1785 if (span->length < kMaxPages)
1786 DLL_Prepend(&free_[span->length].returned, span);
1788 DLL_Prepend(&large_.returned, span);
1790 if (span->length < kMaxPages)
1791 DLL_Prepend(&free_[span->length].normal, span);
1793 DLL_Prepend(&large_.normal, span);
1797 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1798 if (span->decommitted) {
1799 // If the merged span is decommitted, that means we decommitted any neighboring spans that were
1800 // committed. Update the free committed pages count.
1801 free_committed_pages_ -= neighboringCommittedSpansLength;
1802 if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
1803 min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
1805 // If the merged span remains committed, add the deleted span's size to the free committed pages count.
1806 free_committed_pages_ += n;
1809 // Make sure the scavenge thread becomes active if we have enough freed pages to release some back to the system.
1812 IncrementalScavenge(n);
1818 #if !USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1819 void TCMalloc_PageHeap::IncrementalScavenge(Length n) {
1820 // Fast path; not yet time to release memory
1821 scavenge_counter_ -= n;
1822 if (scavenge_counter_ >= 0) return; // Not yet time to scavenge
1824 // If there is nothing to release, wait for so many pages before
1825 // scavenging again. With 4K pages, this comes to 16MB of memory.
1826 static const size_t kDefaultReleaseDelay = 1 << 8;
1828 // Find index of free list to scavenge
1829 size_t index = scavenge_index_ + 1;
1830 for (size_t i = 0; i < kMaxPages+1; i++) {
1831 if (index > kMaxPages) index = 0;
1832 SpanList* slist = (index == kMaxPages) ? &large_ : &free_[index];
1833 if (!DLL_IsEmpty(&slist->normal)) {
1834 // Release the last span on the normal portion of this list
1835 Span* s = slist->normal.prev;
1837 TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
1838 static_cast<size_t>(s->length << kPageShift));
1839 s->decommitted = true;
1840 DLL_Prepend(&slist->returned, s);
1842 scavenge_counter_ = std::max<size_t>(64UL, std::min<size_t>(kDefaultReleaseDelay, kDefaultReleaseDelay - (free_pages_ / kDefaultReleaseDelay)));
1844 if (index == kMaxPages && !DLL_IsEmpty(&slist->normal))
1845 scavenge_index_ = index - 1;
1847 scavenge_index_ = index;
1853 // Nothing to scavenge, delay for a while
1854 scavenge_counter_ = kDefaultReleaseDelay;
1858 void TCMalloc_PageHeap::RegisterSizeClass(Span* span, size_t sc) {
1859 // Associate span object with all interior pages as well
1860 ASSERT(!span->free);
1861 ASSERT(GetDescriptor(span->start) == span);
1862 ASSERT(GetDescriptor(span->start+span->length-1) == span);
1863 Event(span, 'C', sc);
1864 span->sizeclass = static_cast<unsigned int>(sc);
1865 for (Length i = 1; i < span->length-1; i++) {
1866 pagemap_.set(span->start+i, span);
1871 size_t TCMalloc_PageHeap::ReturnedBytes() const {
1873 for (unsigned s = 0; s < kMaxPages; s++) {
1874 const int r_length = DLL_Length(&free_[s].returned);
1875 unsigned r_pages = s * r_length;
1876 result += r_pages << kPageShift;
1879 for (Span* s = large_.returned.next; s != &large_.returned; s = s->next)
1880 result += s->length << kPageShift;
1886 static double PagesToMB(uint64_t pages) {
1887 return (pages << kPageShift) / 1048576.0;
1890 void TCMalloc_PageHeap::Dump(TCMalloc_Printer* out) {
1891 int nonempty_sizes = 0;
1892 for (int s = 0; s < kMaxPages; s++) {
1893 if (!DLL_IsEmpty(&free_[s].normal) || !DLL_IsEmpty(&free_[s].returned)) {
1897 out->printf("------------------------------------------------\n");
1898 out->printf("PageHeap: %d sizes; %6.1f MB free\n",
1899 nonempty_sizes, PagesToMB(free_pages_));
1900 out->printf("------------------------------------------------\n");
1901 uint64_t total_normal = 0;
1902 uint64_t total_returned = 0;
1903 for (int s = 0; s < kMaxPages; s++) {
1904 const int n_length = DLL_Length(&free_[s].normal);
1905 const int r_length = DLL_Length(&free_[s].returned);
1906 if (n_length + r_length > 0) {
1907 uint64_t n_pages = s * n_length;
1908 uint64_t r_pages = s * r_length;
1909 total_normal += n_pages;
1910 total_returned += r_pages;
1911 out->printf("%6u pages * %6u spans ~ %6.1f MB; %6.1f MB cum"
1912 "; unmapped: %6.1f MB; %6.1f MB cum\n",
1914 (n_length + r_length),
1915 PagesToMB(n_pages + r_pages),
1916 PagesToMB(total_normal + total_returned),
1918 PagesToMB(total_returned));
1922 uint64_t n_pages = 0;
1923 uint64_t r_pages = 0;
1926 out->printf("Normal large spans:\n");
1927 for (Span* s = large_.normal.next; s != &large_.normal; s = s->next) {
1928 out->printf(" [ %6" PRIuS " pages ] %6.1f MB\n",
1929 s->length, PagesToMB(s->length));
1930 n_pages += s->length;
1933 out->printf("Unmapped large spans:\n");
1934 for (Span* s = large_.returned.next; s != &large_.returned; s = s->next) {
1935 out->printf(" [ %6" PRIuS " pages ] %6.1f MB\n",
1936 s->length, PagesToMB(s->length));
1937 r_pages += s->length;
1940 total_normal += n_pages;
1941 total_returned += r_pages;
1942 out->printf(">255 large * %6u spans ~ %6.1f MB; %6.1f MB cum"
1943 "; unmapped: %6.1f MB; %6.1f MB cum\n",
1944 (n_spans + r_spans),
1945 PagesToMB(n_pages + r_pages),
1946 PagesToMB(total_normal + total_returned),
1948 PagesToMB(total_returned));
1952 bool TCMalloc_PageHeap::GrowHeap(Length n) {
1953 ASSERT(kMaxPages >= kMinSystemAlloc);
1954 if (n > kMaxValidPages) return false;
1955 Length ask = (n>kMinSystemAlloc) ? n : static_cast<Length>(kMinSystemAlloc);
1957 void* ptr = TCMalloc_SystemAlloc(ask << kPageShift, &actual_size, kPageSize);
1960 // Try growing just "n" pages
1962 ptr = TCMalloc_SystemAlloc(ask << kPageShift, &actual_size, kPageSize);
1964 if (ptr == NULL) return false;
1966 ask = actual_size >> kPageShift;
1968 uint64_t old_system_bytes = system_bytes_;
1969 system_bytes_ += (ask << kPageShift);
1970 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
1973 // If we have already a lot of pages allocated, just pre allocate a bunch of
1974 // memory for the page map. This prevents fragmentation by pagemap metadata
1975 // when a program keeps allocating and freeing large blocks.
1977 if (old_system_bytes < kPageMapBigAllocationThreshold
1978 && system_bytes_ >= kPageMapBigAllocationThreshold) {
1979 pagemap_.PreallocateMoreMemory();
1982 // Make sure pagemap_ has entries for all of the new pages.
1983 // Plus ensure one before and one after so coalescing code
1984 // does not need bounds-checking.
1985 if (pagemap_.Ensure(p-1, ask+2)) {
1986 // Pretend the new area is allocated and then Delete() it to
1987 // cause any necessary coalescing to occur.
1989 // We do not adjust free_pages_ here since Delete() will do it for us.
1990 Span* span = NewSpan(p, ask);
1996 // We could not allocate memory within "pagemap_"
1997 // TODO: Once we can return memory to the system, return the new span
2002 bool TCMalloc_PageHeap::Check() {
2003 ASSERT(free_[0].normal.next == &free_[0].normal);
2004 ASSERT(free_[0].returned.next == &free_[0].returned);
2005 CheckList(&large_.normal, kMaxPages, 1000000000);
2006 CheckList(&large_.returned, kMaxPages, 1000000000);
2007 for (Length s = 1; s < kMaxPages; s++) {
2008 CheckList(&free_[s].normal, s, s);
2009 CheckList(&free_[s].returned, s, s);
2015 bool TCMalloc_PageHeap::CheckList(Span*, Length, Length) {
2019 bool TCMalloc_PageHeap::CheckList(Span* list, Length min_pages, Length max_pages) {
2020 for (Span* s = list->next; s != list; s = s->next) {
2021 CHECK_CONDITION(s->free);
2022 CHECK_CONDITION(s->length >= min_pages);
2023 CHECK_CONDITION(s->length <= max_pages);
2024 CHECK_CONDITION(GetDescriptor(s->start) == s);
2025 CHECK_CONDITION(GetDescriptor(s->start+s->length-1) == s);
2031 static void ReleaseFreeList(Span* list, Span* returned) {
2032 // Walk backwards through list so that when we push these
2033 // spans on the "returned" list, we preserve the order.
2034 while (!DLL_IsEmpty(list)) {
2035 Span* s = list->prev;
2037 DLL_Prepend(returned, s);
2038 TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
2039 static_cast<size_t>(s->length << kPageShift));
2043 void TCMalloc_PageHeap::ReleaseFreePages() {
2044 for (Length s = 0; s < kMaxPages; s++) {
2045 ReleaseFreeList(&free_[s].normal, &free_[s].returned);
2047 ReleaseFreeList(&large_.normal, &large_.returned);
2051 //-------------------------------------------------------------------
2053 //-------------------------------------------------------------------
2055 class TCMalloc_ThreadCache_FreeList {
2057 void* list_; // Linked list of nodes
2058 uint16_t length_; // Current length
2059 uint16_t lowater_; // Low water mark for list length
2068 // Return current length of list
2069 int length() const {
2074 bool empty() const {
2075 return list_ == NULL;
2078 // Low-water mark management
2079 int lowwatermark() const { return lowater_; }
2080 void clear_lowwatermark() { lowater_ = length_; }
2082 ALWAYS_INLINE void Push(void* ptr) {
2083 SLL_Push(&list_, ptr);
2087 void PushRange(int N, void *start, void *end) {
2088 SLL_PushRange(&list_, start, end);
2089 length_ = length_ + static_cast<uint16_t>(N);
2092 void PopRange(int N, void **start, void **end) {
2093 SLL_PopRange(&list_, N, start, end);
2094 ASSERT(length_ >= N);
2095 length_ = length_ - static_cast<uint16_t>(N);
2096 if (length_ < lowater_) lowater_ = length_;
2099 ALWAYS_INLINE void* Pop() {
2100 ASSERT(list_ != NULL);
2102 if (length_ < lowater_) lowater_ = length_;
2103 return SLL_Pop(&list_);
2107 template <class Finder, class Reader>
2108 void enumerateFreeObjects(Finder& finder, const Reader& reader)
2110 for (void* nextObject = list_; nextObject; nextObject = *reader(reinterpret_cast<void**>(nextObject)))
2111 finder.visit(nextObject);
2116 //-------------------------------------------------------------------
2117 // Data kept per thread
2118 //-------------------------------------------------------------------
2120 class TCMalloc_ThreadCache {
2122 typedef TCMalloc_ThreadCache_FreeList FreeList;
2124 typedef DWORD ThreadIdentifier;
2126 typedef pthread_t ThreadIdentifier;
2129 size_t size_; // Combined size of data
2130 ThreadIdentifier tid_; // Which thread owns it
2131 bool in_setspecific_; // Called pthread_setspecific?
2132 FreeList list_[kNumClasses]; // Array indexed by size-class
2134 // We sample allocations, biased by the size of the allocation
2135 uint32_t rnd_; // Cheap random number generator
2136 size_t bytes_until_sample_; // Bytes until we sample next
2138 // Allocate a new heap. REQUIRES: pageheap_lock is held.
2139 static inline TCMalloc_ThreadCache* NewHeap(ThreadIdentifier tid);
2141 // Use only as pthread thread-specific destructor function.
2142 static void DestroyThreadCache(void* ptr);
2144 // All ThreadCache objects are kept in a linked list (for stats collection)
2145 TCMalloc_ThreadCache* next_;
2146 TCMalloc_ThreadCache* prev_;
2148 void Init(ThreadIdentifier tid);
2151 // Accessors (mostly just for printing stats)
2152 int freelist_length(size_t cl) const { return list_[cl].length(); }
2154 // Total byte size in cache
2155 size_t Size() const { return size_; }
2157 void* Allocate(size_t size);
2158 void Deallocate(void* ptr, size_t size_class);
2160 void FetchFromCentralCache(size_t cl, size_t allocationSize);
2161 void ReleaseToCentralCache(size_t cl, int N);
2165 // Record allocation of "k" bytes. Return true iff allocation
2166 // should be sampled
2167 bool SampleAllocation(size_t k);
2169 // Pick next sampling point
2170 void PickNextSample(size_t k);
2172 static void InitModule();
2173 static void InitTSD();
2174 static TCMalloc_ThreadCache* GetThreadHeap();
2175 static TCMalloc_ThreadCache* GetCache();
2176 static TCMalloc_ThreadCache* GetCacheIfPresent();
2177 static TCMalloc_ThreadCache* CreateCacheIfNecessary();
2178 static void DeleteCache(TCMalloc_ThreadCache* heap);
2179 static void BecomeIdle();
2180 static void RecomputeThreadCacheSize();
2183 template <class Finder, class Reader>
2184 void enumerateFreeObjects(Finder& finder, const Reader& reader)
2186 for (unsigned sizeClass = 0; sizeClass < kNumClasses; sizeClass++)
2187 list_[sizeClass].enumerateFreeObjects(finder, reader);
2192 //-------------------------------------------------------------------
2193 // Data kept per size-class in central cache
2194 //-------------------------------------------------------------------
2196 class TCMalloc_Central_FreeList {
2198 void Init(size_t cl);
2200 // These methods all do internal locking.
2202 // Insert the specified range into the central freelist. N is the number of
2203 // elements in the range.
2204 void InsertRange(void *start, void *end, int N);
2206 // Returns the actual number of fetched elements into N.
2207 void RemoveRange(void **start, void **end, int *N);
2209 // Returns the number of free objects in cache.
2211 SpinLockHolder h(&lock_);
2215 // Returns the number of free objects in the transfer cache.
2217 SpinLockHolder h(&lock_);
2218 return used_slots_ * num_objects_to_move[size_class_];
2222 template <class Finder, class Reader>
2223 void enumerateFreeObjects(Finder& finder, const Reader& reader, TCMalloc_Central_FreeList* remoteCentralFreeList)
2225 for (Span* span = &empty_; span && span != &empty_; span = (span->next ? reader(span->next) : 0))
2226 ASSERT(!span->objects);
2228 ASSERT(!nonempty_.objects);
2229 static const ptrdiff_t nonemptyOffset = reinterpret_cast<const char*>(&nonempty_) - reinterpret_cast<const char*>(this);
2231 Span* remoteNonempty = reinterpret_cast<Span*>(reinterpret_cast<char*>(remoteCentralFreeList) + nonemptyOffset);
2232 Span* remoteSpan = nonempty_.next;
2234 for (Span* span = reader(remoteSpan); span && remoteSpan != remoteNonempty; remoteSpan = span->next, span = (span->next ? reader(span->next) : 0)) {
2235 for (void* nextObject = span->objects; nextObject; nextObject = *reader(reinterpret_cast<void**>(nextObject)))
2236 finder.visit(nextObject);
2242 // REQUIRES: lock_ is held
2243 // Remove object from cache and return.
2244 // Return NULL if no free entries in cache.
2245 void* FetchFromSpans();
2247 // REQUIRES: lock_ is held
2248 // Remove object from cache and return. Fetches
2249 // from pageheap if cache is empty. Only returns
2250 // NULL on allocation failure.
2251 void* FetchFromSpansSafe();
2253 // REQUIRES: lock_ is held
2254 // Release a linked list of objects to spans.
2255 // May temporarily release lock_.
2256 void ReleaseListToSpans(void *start);
2258 // REQUIRES: lock_ is held
2259 // Release an object to spans.
2260 // May temporarily release lock_.
2261 void ReleaseToSpans(void* object);
2263 // REQUIRES: lock_ is held
2264 // Populate cache by fetching from the page heap.
2265 // May temporarily release lock_.
2268 // REQUIRES: lock is held.
2269 // Tries to make room for a TCEntry. If the cache is full it will try to
2270 // expand it at the cost of some other cache size. Return false if there is
2272 bool MakeCacheSpace();
2274 // REQUIRES: lock_ for locked_size_class is held.
2275 // Picks a "random" size class to steal TCEntry slot from. In reality it
2276 // just iterates over the sizeclasses but does so without taking a lock.
2277 // Returns true on success.
2278 // May temporarily lock a "random" size class.
2279 static bool EvictRandomSizeClass(size_t locked_size_class, bool force);
2281 // REQUIRES: lock_ is *not* held.
2282 // Tries to shrink the Cache. If force is true it will relase objects to
2283 // spans if it allows it to shrink the cache. Return false if it failed to
2284 // shrink the cache. Decrements cache_size_ on succeess.
2285 // May temporarily take lock_. If it takes lock_, the locked_size_class
2286 // lock is released to the thread from holding two size class locks
2287 // concurrently which could lead to a deadlock.
2288 bool ShrinkCache(int locked_size_class, bool force);
2290 // This lock protects all the data members. cached_entries and cache_size_
2291 // may be looked at without holding the lock.
2294 // We keep linked lists of empty and non-empty spans.
2295 size_t size_class_; // My size class
2296 Span empty_; // Dummy header for list of empty spans
2297 Span nonempty_; // Dummy header for list of non-empty spans
2298 size_t counter_; // Number of free objects in cache entry
2300 // Here we reserve space for TCEntry cache slots. Since one size class can
2301 // end up getting all the TCEntries quota in the system we just preallocate
2302 // sufficient number of entries here.
2303 TCEntry tc_slots_[kNumTransferEntries];
2305 // Number of currently used cached entries in tc_slots_. This variable is
2306 // updated under a lock but can be read without one.
2307 int32_t used_slots_;
2308 // The current number of slots for this size class. This is an
2309 // adaptive value that is increased if there is lots of traffic
2310 // on a given size class.
2311 int32_t cache_size_;
2314 // Pad each CentralCache object to multiple of 64 bytes
2315 class TCMalloc_Central_FreeListPadded : public TCMalloc_Central_FreeList {
2317 char pad_[(64 - (sizeof(TCMalloc_Central_FreeList) % 64)) % 64];
2320 //-------------------------------------------------------------------
2322 //-------------------------------------------------------------------
2324 // Central cache -- a collection of free-lists, one per size-class.
2325 // We have a separate lock per free-list to reduce contention.
2326 static TCMalloc_Central_FreeListPadded central_cache[kNumClasses];
2328 // Page-level allocator
2329 static SpinLock pageheap_lock = SPINLOCK_INITIALIZER;
2330 static void* pageheap_memory[(sizeof(TCMalloc_PageHeap) + sizeof(void*) - 1) / sizeof(void*)];
2331 static bool phinited = false;
2333 // Avoid extra level of indirection by making "pageheap" be just an alias
2334 // of pageheap_memory.
2337 TCMalloc_PageHeap* m_pageHeap;
2340 static inline TCMalloc_PageHeap* getPageHeap()
2342 PageHeapUnion u = { &pageheap_memory[0] };
2343 return u.m_pageHeap;
2346 #define pageheap getPageHeap()
2348 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
2350 #if !HAVE(DISPATCH_H)
2352 static void sleep(unsigned seconds)
2354 ::Sleep(seconds * 1000);
2358 void TCMalloc_PageHeap::scavengerThread()
2360 #if HAVE(PTHREAD_SETNAME_NP)
2361 pthread_setname_np("JavaScriptCore: FastMalloc scavenger");
2365 if (!shouldScavenge()) {
2366 pthread_mutex_lock(&m_scavengeMutex);
2367 m_scavengeThreadActive = false;
2368 // Block until there are enough free committed pages to release back to the system.
2369 pthread_cond_wait(&m_scavengeCondition, &m_scavengeMutex);
2370 m_scavengeThreadActive = true;
2371 pthread_mutex_unlock(&m_scavengeMutex);
2373 sleep(kScavengeDelayInSeconds);
2375 SpinLockHolder h(&pageheap_lock);
2376 pageheap->scavenge();
2383 void TCMalloc_PageHeap::periodicScavenge()
2386 SpinLockHolder h(&pageheap_lock);
2387 pageheap->scavenge();
2390 if (!shouldScavenge()) {
2391 m_scavengingScheduled = false;
2392 dispatch_suspend(m_scavengeTimer);
2395 #endif // HAVE(DISPATCH_H)
2399 // If TLS is available, we also store a copy
2400 // of the per-thread object in a __thread variable
2401 // since __thread variables are faster to read
2402 // than pthread_getspecific(). We still need
2403 // pthread_setspecific() because __thread
2404 // variables provide no way to run cleanup
2405 // code when a thread is destroyed.
2407 static __thread TCMalloc_ThreadCache *threadlocal_heap;
2409 // Thread-specific key. Initialization here is somewhat tricky
2410 // because some Linux startup code invokes malloc() before it
2411 // is in a good enough state to handle pthread_keycreate().
2412 // Therefore, we use TSD keys only after tsd_inited is set to true.
2413 // Until then, we use a slow path to get the heap object.
2414 static bool tsd_inited = false;
2415 static pthread_key_t heap_key;
2417 DWORD tlsIndex = TLS_OUT_OF_INDEXES;
2420 static ALWAYS_INLINE void setThreadHeap(TCMalloc_ThreadCache* heap)
2422 // still do pthread_setspecific when using MSVC fast TLS to
2423 // benefit from the delete callback.
2424 pthread_setspecific(heap_key, heap);
2426 TlsSetValue(tlsIndex, heap);
2430 // Allocator for thread heaps
2431 static PageHeapAllocator<TCMalloc_ThreadCache> threadheap_allocator;
2433 // Linked list of heap objects. Protected by pageheap_lock.
2434 static TCMalloc_ThreadCache* thread_heaps = NULL;
2435 static int thread_heap_count = 0;
2437 // Overall thread cache size. Protected by pageheap_lock.
2438 static size_t overall_thread_cache_size = kDefaultOverallThreadCacheSize;
2440 // Global per-thread cache size. Writes are protected by
2441 // pageheap_lock. Reads are done without any locking, which should be
2442 // fine as long as size_t can be written atomically and we don't place
2443 // invariants between this variable and other pieces of state.
2444 static volatile size_t per_thread_cache_size = kMaxThreadCacheSize;
2446 //-------------------------------------------------------------------
2447 // Central cache implementation
2448 //-------------------------------------------------------------------
2450 void TCMalloc_Central_FreeList::Init(size_t cl) {
2454 DLL_Init(&nonempty_);
2459 ASSERT(cache_size_ <= kNumTransferEntries);
2462 void TCMalloc_Central_FreeList::ReleaseListToSpans(void* start) {
2464 void *next = SLL_Next(start);
2465 ReleaseToSpans(start);
2470 ALWAYS_INLINE void TCMalloc_Central_FreeList::ReleaseToSpans(void* object) {
2471 const PageID p = reinterpret_cast<uintptr_t>(object) >> kPageShift;
2472 Span* span = pageheap->GetDescriptor(p);
2473 ASSERT(span != NULL);
2474 ASSERT(span->refcount > 0);
2476 // If span is empty, move it to non-empty list
2477 if (span->objects == NULL) {
2479 DLL_Prepend(&nonempty_, span);
2480 Event(span, 'N', 0);
2483 // The following check is expensive, so it is disabled by default
2485 // Check that object does not occur in list
2487 for (void* p = span->objects; p != NULL; p = *((void**) p)) {
2488 ASSERT(p != object);
2491 ASSERT(got + span->refcount ==
2492 (span->length<<kPageShift)/ByteSizeForClass(span->sizeclass));
2497 if (span->refcount == 0) {
2498 Event(span, '#', 0);
2499 counter_ -= (span->length<<kPageShift) / ByteSizeForClass(span->sizeclass);
2502 // Release central list lock while operating on pageheap
2505 SpinLockHolder h(&pageheap_lock);
2506 pageheap->Delete(span);
2510 *(reinterpret_cast<void**>(object)) = span->objects;
2511 span->objects = object;
2515 ALWAYS_INLINE bool TCMalloc_Central_FreeList::EvictRandomSizeClass(
2516 size_t locked_size_class, bool force) {
2517 static int race_counter = 0;
2518 int t = race_counter++; // Updated without a lock, but who cares.
2519 if (t >= static_cast<int>(kNumClasses)) {
2520 while (t >= static_cast<int>(kNumClasses)) {
2526 ASSERT(t < static_cast<int>(kNumClasses));
2527 if (t == static_cast<int>(locked_size_class)) return false;
2528 return central_cache[t].ShrinkCache(static_cast<int>(locked_size_class), force);
2531 bool TCMalloc_Central_FreeList::MakeCacheSpace() {
2532 // Is there room in the cache?
2533 if (used_slots_ < cache_size_) return true;
2534 // Check if we can expand this cache?
2535 if (cache_size_ == kNumTransferEntries) return false;
2536 // Ok, we'll try to grab an entry from some other size class.
2537 if (EvictRandomSizeClass(size_class_, false) ||
2538 EvictRandomSizeClass(size_class_, true)) {
2539 // Succeeded in evicting, we're going to make our cache larger.
2548 class LockInverter {
2550 SpinLock *held_, *temp_;
2552 inline explicit LockInverter(SpinLock* held, SpinLock *temp)
2553 : held_(held), temp_(temp) { held_->Unlock(); temp_->Lock(); }
2554 inline ~LockInverter() { temp_->Unlock(); held_->Lock(); }
2558 bool TCMalloc_Central_FreeList::ShrinkCache(int locked_size_class, bool force) {
2559 // Start with a quick check without taking a lock.
2560 if (cache_size_ == 0) return false;
2561 // We don't evict from a full cache unless we are 'forcing'.
2562 if (force == false && used_slots_ == cache_size_) return false;
2564 // Grab lock, but first release the other lock held by this thread. We use
2565 // the lock inverter to ensure that we never hold two size class locks
2566 // concurrently. That can create a deadlock because there is no well
2567 // defined nesting order.
2568 LockInverter li(¢ral_cache[locked_size_class].lock_, &lock_);
2569 ASSERT(used_slots_ <= cache_size_);
2570 ASSERT(0 <= cache_size_);
2571 if (cache_size_ == 0) return false;
2572 if (used_slots_ == cache_size_) {
2573 if (force == false) return false;
2574 // ReleaseListToSpans releases the lock, so we have to make all the
2575 // updates to the central list before calling it.
2578 ReleaseListToSpans(tc_slots_[used_slots_].head);
2585 void TCMalloc_Central_FreeList::InsertRange(void *start, void *end, int N) {
2586 SpinLockHolder h(&lock_);
2587 if (N == num_objects_to_move[size_class_] &&
2589 int slot = used_slots_++;
2591 ASSERT(slot < kNumTransferEntries);
2592 TCEntry *entry = &tc_slots_[slot];
2593 entry->head = start;
2597 ReleaseListToSpans(start);
2600 void TCMalloc_Central_FreeList::RemoveRange(void **start, void **end, int *N) {
2604 SpinLockHolder h(&lock_);
2605 if (num == num_objects_to_move[size_class_] && used_slots_ > 0) {
2606 int slot = --used_slots_;
2608 TCEntry *entry = &tc_slots_[slot];
2609 *start = entry->head;
2614 // TODO: Prefetch multiple TCEntries?
2615 void *tail = FetchFromSpansSafe();
2617 // We are completely out of memory.
2618 *start = *end = NULL;
2623 SLL_SetNext(tail, NULL);
2626 while (count < num) {
2627 void *t = FetchFromSpans();
2638 void* TCMalloc_Central_FreeList::FetchFromSpansSafe() {
2639 void *t = FetchFromSpans();
2642 t = FetchFromSpans();
2647 void* TCMalloc_Central_FreeList::FetchFromSpans() {
2648 if (DLL_IsEmpty(&nonempty_)) return NULL;
2649 Span* span = nonempty_.next;
2651 ASSERT(span->objects != NULL);
2652 ASSERT_SPAN_COMMITTED(span);
2654 void* result = span->objects;
2655 span->objects = *(reinterpret_cast<void**>(result));
2656 if (span->objects == NULL) {
2657 // Move to empty list
2659 DLL_Prepend(&empty_, span);
2660 Event(span, 'E', 0);
2666 // Fetch memory from the system and add to the central cache freelist.
2667 ALWAYS_INLINE void TCMalloc_Central_FreeList::Populate() {
2668 // Release central list lock while operating on pageheap
2670 const size_t npages = class_to_pages[size_class_];
2674 SpinLockHolder h(&pageheap_lock);
2675 span = pageheap->New(npages);
2676 if (span) pageheap->RegisterSizeClass(span, size_class_);
2679 MESSAGE("allocation failed: %d\n", errno);
2683 ASSERT_SPAN_COMMITTED(span);
2684 ASSERT(span->length == npages);
2685 // Cache sizeclass info eagerly. Locking is not necessary.
2686 // (Instead of being eager, we could just replace any stale info
2687 // about this span, but that seems to be no better in practice.)
2688 for (size_t i = 0; i < npages; i++) {
2689 pageheap->CacheSizeClass(span->start + i, size_class_);
2692 // Split the block into pieces and add to the free-list
2693 // TODO: coloring of objects to avoid cache conflicts?
2694 void** tail = &span->objects;
2695 char* ptr = reinterpret_cast<char*>(span->start << kPageShift);
2696 char* limit = ptr + (npages << kPageShift);
2697 const size_t size = ByteSizeForClass(size_class_);
2700 while ((nptr = ptr + size) <= limit) {
2702 tail = reinterpret_cast<void**>(ptr);
2706 ASSERT(ptr <= limit);
2708 span->refcount = 0; // No sub-object in use yet
2710 // Add span to list of non-empty spans
2712 DLL_Prepend(&nonempty_, span);
2716 //-------------------------------------------------------------------
2717 // TCMalloc_ThreadCache implementation
2718 //-------------------------------------------------------------------
2720 inline bool TCMalloc_ThreadCache::SampleAllocation(size_t k) {
2721 if (bytes_until_sample_ < k) {
2725 bytes_until_sample_ -= k;
2730 void TCMalloc_ThreadCache::Init(ThreadIdentifier tid) {
2735 in_setspecific_ = false;
2736 for (size_t cl = 0; cl < kNumClasses; ++cl) {
2740 // Initialize RNG -- run it for a bit to get to good values
2741 bytes_until_sample_ = 0;
2742 rnd_ = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(this));
2743 for (int i = 0; i < 100; i++) {
2744 PickNextSample(static_cast<size_t>(FLAGS_tcmalloc_sample_parameter * 2));
2748 void TCMalloc_ThreadCache::Cleanup() {
2749 // Put unused memory back into central cache
2750 for (size_t cl = 0; cl < kNumClasses; ++cl) {
2751 if (list_[cl].length() > 0) {
2752 ReleaseToCentralCache(cl, list_[cl].length());
2757 ALWAYS_INLINE void* TCMalloc_ThreadCache::Allocate(size_t size) {
2758 ASSERT(size <= kMaxSize);
2759 const size_t cl = SizeClass(size);
2760 FreeList* list = &list_[cl];
2761 size_t allocationSize = ByteSizeForClass(cl);
2762 if (list->empty()) {
2763 FetchFromCentralCache(cl, allocationSize);
2764 if (list->empty()) return NULL;
2766 size_ -= allocationSize;
2770 inline void TCMalloc_ThreadCache::Deallocate(void* ptr, size_t cl) {
2771 size_ += ByteSizeForClass(cl);
2772 FreeList* list = &list_[cl];
2774 // If enough data is free, put back into central cache
2775 if (list->length() > kMaxFreeListLength) {
2776 ReleaseToCentralCache(cl, num_objects_to_move[cl]);
2778 if (size_ >= per_thread_cache_size) Scavenge();
2781 // Remove some objects of class "cl" from central cache and add to thread heap
2782 ALWAYS_INLINE void TCMalloc_ThreadCache::FetchFromCentralCache(size_t cl, size_t allocationSize) {
2783 int fetch_count = num_objects_to_move[cl];
2785 central_cache[cl].RemoveRange(&start, &end, &fetch_count);
2786 list_[cl].PushRange(fetch_count, start, end);
2787 size_ += allocationSize * fetch_count;
2790 // Remove some objects of class "cl" from thread heap and add to central cache
2791 inline void TCMalloc_ThreadCache::ReleaseToCentralCache(size_t cl, int N) {
2793 FreeList* src = &list_[cl];
2794 if (N > src->length()) N = src->length();
2795 size_ -= N*ByteSizeForClass(cl);
2797 // We return prepackaged chains of the correct size to the central cache.
2798 // TODO: Use the same format internally in the thread caches?
2799 int batch_size = num_objects_to_move[cl];
2800 while (N > batch_size) {
2802 src->PopRange(batch_size, &head, &tail);
2803 central_cache[cl].InsertRange(head, tail, batch_size);
2807 src->PopRange(N, &head, &tail);
2808 central_cache[cl].InsertRange(head, tail, N);
2811 // Release idle memory to the central cache
2812 inline void TCMalloc_ThreadCache::Scavenge() {
2813 // If the low-water mark for the free list is L, it means we would
2814 // not have had to allocate anything from the central cache even if
2815 // we had reduced the free list size by L. We aim to get closer to
2816 // that situation by dropping L/2 nodes from the free list. This
2817 // may not release much memory, but if so we will call scavenge again
2818 // pretty soon and the low-water marks will be high on that call.
2819 //int64 start = CycleClock::Now();
2821 for (size_t cl = 0; cl < kNumClasses; cl++) {
2822 FreeList* list = &list_[cl];
2823 const int lowmark = list->lowwatermark();
2825 const int drop = (lowmark > 1) ? lowmark/2 : 1;
2826 ReleaseToCentralCache(cl, drop);
2828 list->clear_lowwatermark();
2831 //int64 finish = CycleClock::Now();
2833 //MESSAGE("GC: %.0f ns\n", ct.CyclesToUsec(finish-start)*1000.0);
2836 void TCMalloc_ThreadCache::PickNextSample(size_t k) {
2837 // Make next "random" number
2838 // x^32+x^22+x^2+x^1+1 is a primitive polynomial for random numbers
2839 static const uint32_t kPoly = (1 << 22) | (1 << 2) | (1 << 1) | (1 << 0);
2841 rnd_ = (r << 1) ^ ((static_cast<int32_t>(r) >> 31) & kPoly);
2843 // Next point is "rnd_ % (sample_period)". I.e., average
2844 // increment is "sample_period/2".
2845 const int flag_value = static_cast<int>(FLAGS_tcmalloc_sample_parameter);
2846 static int last_flag_value = -1;
2848 if (flag_value != last_flag_value) {
2849 SpinLockHolder h(&sample_period_lock);
2851 for (i = 0; i < (static_cast<int>(sizeof(primes_list)/sizeof(primes_list[0])) - 1); i++) {
2852 if (primes_list[i] >= flag_value) {
2856 sample_period = primes_list[i];
2857 last_flag_value = flag_value;
2860 bytes_until_sample_ += rnd_ % sample_period;
2862 if (k > (static_cast<size_t>(-1) >> 2)) {
2863 // If the user has asked for a huge allocation then it is possible
2864 // for the code below to loop infinitely. Just return (note that
2865 // this throws off the sampling accuracy somewhat, but a user who
2866 // is allocating more than 1G of memory at a time can live with a
2867 // minor inaccuracy in profiling of small allocations, and also
2868 // would rather not wait for the loop below to terminate).
2872 while (bytes_until_sample_ < k) {
2873 // Increase bytes_until_sample_ by enough average sampling periods
2874 // (sample_period >> 1) to allow us to sample past the current
2876 bytes_until_sample_ += (sample_period >> 1);
2879 bytes_until_sample_ -= k;
2882 void TCMalloc_ThreadCache::InitModule() {
2883 // There is a slight potential race here because of double-checked
2884 // locking idiom. However, as long as the program does a small
2885 // allocation before switching to multi-threaded mode, we will be
2886 // fine. We increase the chances of doing such a small allocation
2887 // by doing one in the constructor of the module_enter_exit_hook
2888 // object declared below.
2889 SpinLockHolder h(&pageheap_lock);
2895 threadheap_allocator.Init();
2896 span_allocator.Init();
2897 span_allocator.New(); // Reduce cache conflicts
2898 span_allocator.New(); // Reduce cache conflicts
2899 stacktrace_allocator.Init();
2900 DLL_Init(&sampled_objects);
2901 for (size_t i = 0; i < kNumClasses; ++i) {
2902 central_cache[i].Init(i);
2906 #if defined(WTF_CHANGES) && OS(DARWIN)
2907 FastMallocZone::init();
2912 inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::NewHeap(ThreadIdentifier tid) {
2913 // Create the heap and add it to the linked list
2914 TCMalloc_ThreadCache *heap = threadheap_allocator.New();
2916 heap->next_ = thread_heaps;
2918 if (thread_heaps != NULL) thread_heaps->prev_ = heap;
2919 thread_heaps = heap;
2920 thread_heap_count++;
2921 RecomputeThreadCacheSize();
2925 inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetThreadHeap() {
2927 // __thread is faster, but only when the kernel supports it
2928 if (KernelSupportsTLS())
2929 return threadlocal_heap;
2930 #elif COMPILER(MSVC)
2931 return static_cast<TCMalloc_ThreadCache*>(TlsGetValue(tlsIndex));
2933 return static_cast<TCMalloc_ThreadCache*>(pthread_getspecific(heap_key));
2937 inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetCache() {
2938 TCMalloc_ThreadCache* ptr = NULL;
2942 ptr = GetThreadHeap();
2944 if (ptr == NULL) ptr = CreateCacheIfNecessary();
2948 // In deletion paths, we do not try to create a thread-cache. This is
2949 // because we may be in the thread destruction code and may have
2950 // already cleaned up the cache for this thread.
2951 inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetCacheIfPresent() {
2952 if (!tsd_inited) return NULL;
2953 void* const p = GetThreadHeap();
2954 return reinterpret_cast<TCMalloc_ThreadCache*>(p);
2957 void TCMalloc_ThreadCache::InitTSD() {
2958 ASSERT(!tsd_inited);
2959 pthread_key_create(&heap_key, DestroyThreadCache);
2961 tlsIndex = TlsAlloc();
2966 // We may have used a fake pthread_t for the main thread. Fix it.
2968 memset(&zero, 0, sizeof(zero));
2971 SpinLockHolder h(&pageheap_lock);
2973 ASSERT(pageheap_lock.IsHeld());
2975 for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
2978 h->tid_ = GetCurrentThreadId();
2981 if (pthread_equal(h->tid_, zero)) {
2982 h->tid_ = pthread_self();
2988 TCMalloc_ThreadCache* TCMalloc_ThreadCache::CreateCacheIfNecessary() {
2989 // Initialize per-thread data if necessary
2990 TCMalloc_ThreadCache* heap = NULL;
2992 SpinLockHolder h(&pageheap_lock);
2999 me = GetCurrentThreadId();
3002 // Early on in glibc's life, we cannot even call pthread_self()
3005 memset(&me, 0, sizeof(me));
3007 me = pthread_self();
3011 // This may be a recursive malloc call from pthread_setspecific()
3012 // In that case, the heap for this thread has already been created
3013 // and added to the linked list. So we search for that first.
3014 for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
3016 if (h->tid_ == me) {
3018 if (pthread_equal(h->tid_, me)) {
3025 if (heap == NULL) heap = NewHeap(me);
3028 // We call pthread_setspecific() outside the lock because it may
3029 // call malloc() recursively. The recursive call will never get
3030 // here again because it will find the already allocated heap in the
3031 // linked list of heaps.
3032 if (!heap->in_setspecific_ && tsd_inited) {
3033 heap->in_setspecific_ = true;
3034 setThreadHeap(heap);
3039 void TCMalloc_ThreadCache::BecomeIdle() {
3040 if (!tsd_inited) return; // No caches yet
3041 TCMalloc_ThreadCache* heap = GetThreadHeap();
3042 if (heap == NULL) return; // No thread cache to remove
3043 if (heap->in_setspecific_) return; // Do not disturb the active caller
3045 heap->in_setspecific_ = true;
3046 pthread_setspecific(heap_key, NULL);
3048 // Also update the copy in __thread
3049 threadlocal_heap = NULL;
3051 heap->in_setspecific_ = false;
3052 if (GetThreadHeap() == heap) {
3053 // Somehow heap got reinstated by a recursive call to malloc
3054 // from pthread_setspecific. We give up in this case.
3058 // We can now get rid of the heap
3062 void TCMalloc_ThreadCache::DestroyThreadCache(void* ptr) {
3063 // Note that "ptr" cannot be NULL since pthread promises not
3064 // to invoke the destructor on NULL values, but for safety,
3066 if (ptr == NULL) return;
3068 // Prevent fast path of GetThreadHeap() from returning heap.
3069 threadlocal_heap = NULL;
3071 DeleteCache(reinterpret_cast<TCMalloc_ThreadCache*>(ptr));
3074 void TCMalloc_ThreadCache::DeleteCache(TCMalloc_ThreadCache* heap) {
3075 // Remove all memory from heap
3078 // Remove from linked list
3079 SpinLockHolder h(&pageheap_lock);
3080 if (heap->next_ != NULL) heap->next_->prev_ = heap->prev_;
3081 if (heap->prev_ != NULL) heap->prev_->next_ = heap->next_;
3082 if (thread_heaps == heap) thread_heaps = heap->next_;
3083 thread_heap_count--;
3084 RecomputeThreadCacheSize();
3086 threadheap_allocator.Delete(heap);
3089 void TCMalloc_ThreadCache::RecomputeThreadCacheSize() {
3090 // Divide available space across threads
3091 int n = thread_heap_count > 0 ? thread_heap_count : 1;
3092 size_t space = overall_thread_cache_size / n;
3094 // Limit to allowed range
3095 if (space < kMinThreadCacheSize) space = kMinThreadCacheSize;
3096 if (space > kMaxThreadCacheSize) space = kMaxThreadCacheSize;
3098 per_thread_cache_size = space;
3101 void TCMalloc_ThreadCache::Print() const {
3102 for (size_t cl = 0; cl < kNumClasses; ++cl) {
3103 MESSAGE(" %5" PRIuS " : %4d len; %4d lo\n",
3104 ByteSizeForClass(cl),
3106 list_[cl].lowwatermark());
3110 // Extract interesting stats
3111 struct TCMallocStats {
3112 uint64_t system_bytes; // Bytes alloced from system
3113 uint64_t thread_bytes; // Bytes in thread caches
3114 uint64_t central_bytes; // Bytes in central cache
3115 uint64_t transfer_bytes; // Bytes in central transfer cache
3116 uint64_t pageheap_bytes; // Bytes in page heap
3117 uint64_t metadata_bytes; // Bytes alloced for metadata
3121 // Get stats into "r". Also get per-size-class counts if class_count != NULL
3122 static void ExtractStats(TCMallocStats* r, uint64_t* class_count) {
3123 r->central_bytes = 0;
3124 r->transfer_bytes = 0;
3125 for (int cl = 0; cl < kNumClasses; ++cl) {
3126 const int length = central_cache[cl].length();
3127 const int tc_length = central_cache[cl].tc_length();
3128 r->central_bytes += static_cast<uint64_t>(ByteSizeForClass(cl)) * length;
3129 r->transfer_bytes +=
3130 static_cast<uint64_t>(ByteSizeForClass(cl)) * tc_length;
3131 if (class_count) class_count[cl] = length + tc_length;
3134 // Add stats from per-thread heaps
3135 r->thread_bytes = 0;
3137 SpinLockHolder h(&pageheap_lock);
3138 for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
3139 r->thread_bytes += h->Size();
3141 for (size_t cl = 0; cl < kNumClasses; ++cl) {
3142 class_count[cl] += h->freelist_length(cl);
3149 SpinLockHolder h(&pageheap_lock);
3150 r->system_bytes = pageheap->SystemBytes();
3151 r->metadata_bytes = metadata_system_bytes;
3152 r->pageheap_bytes = pageheap->FreeBytes();
3158 // WRITE stats to "out"
3159 static void DumpStats(TCMalloc_Printer* out, int level) {
3160 TCMallocStats stats;
3161 uint64_t class_count[kNumClasses];
3162 ExtractStats(&stats, (level >= 2 ? class_count : NULL));
3165 out->printf("------------------------------------------------\n");
3166 uint64_t cumulative = 0;
3167 for (int cl = 0; cl < kNumClasses; ++cl) {
3168 if (class_count[cl] > 0) {
3169 uint64_t class_bytes = class_count[cl] * ByteSizeForClass(cl);
3170 cumulative += class_bytes;
3171 out->printf("class %3d [ %8" PRIuS " bytes ] : "
3172 "%8" PRIu64 " objs; %5.1f MB; %5.1f cum MB\n",
3173 cl, ByteSizeForClass(cl),
3175 class_bytes / 1048576.0,
3176 cumulative / 1048576.0);
3180 SpinLockHolder h(&pageheap_lock);
3181 pageheap->Dump(out);
3184 const uint64_t bytes_in_use = stats.system_bytes
3185 - stats.pageheap_bytes
3186 - stats.central_bytes
3187 - stats.transfer_bytes
3188 - stats.thread_bytes;
3190 out->printf("------------------------------------------------\n"
3191 "MALLOC: %12" PRIu64 " Heap size\n"
3192 "MALLOC: %12" PRIu64 " Bytes in use by application\n"
3193 "MALLOC: %12" PRIu64 " Bytes free in page heap\n"
3194 "MALLOC: %12" PRIu64 " Bytes free in central cache\n"
3195 "MALLOC: %12" PRIu64 " Bytes free in transfer cache\n"
3196 "MALLOC: %12" PRIu64 " Bytes free in thread caches\n"
3197 "MALLOC: %12" PRIu64 " Spans in use\n"
3198 "MALLOC: %12" PRIu64 " Thread heaps in use\n"
3199 "MALLOC: %12" PRIu64 " Metadata allocated\n"
3200 "------------------------------------------------\n",
3203 stats.pageheap_bytes,
3204 stats.central_bytes,
3205 stats.transfer_bytes,
3207 uint64_t(span_allocator.inuse()),
3208 uint64_t(threadheap_allocator.inuse()),
3209 stats.metadata_bytes);
3212 static void PrintStats(int level) {
3213 const int kBufferSize = 16 << 10;
3214 char* buffer = new char[kBufferSize];
3215 TCMalloc_Printer printer(buffer, kBufferSize);
3216 DumpStats(&printer, level);
3217 write(STDERR_FILENO, buffer, strlen(buffer));
3221 static void** DumpStackTraces() {
3222 // Count how much space we need
3223 int needed_slots = 0;
3225 SpinLockHolder h(&pageheap_lock);
3226 for (Span* s = sampled_objects.next; s != &sampled_objects; s = s->next) {
3227 StackTrace* stack = reinterpret_cast<StackTrace*>(s->objects);
3228 needed_slots += 3 + stack->depth;
3230 needed_slots += 100; // Slop in case sample grows
3231 needed_slots += needed_slots/8; // An extra 12.5% slop
3234 void** result = new void*[needed_slots];
3235 if (result == NULL) {
3236 MESSAGE("tcmalloc: could not allocate %d slots for stack traces\n",
3241 SpinLockHolder h(&pageheap_lock);
3243 for (Span* s = sampled_objects.next; s != &sampled_objects; s = s->next) {
3244 ASSERT(used_slots < needed_slots); // Need to leave room for terminator
3245 StackTrace* stack = reinterpret_cast<StackTrace*>(s->objects);
3246 if (used_slots + 3 + stack->depth >= needed_slots) {
3251 result[used_slots+0] = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
3252 result[used_slots+1] = reinterpret_cast<void*>(stack->size);
3253 result[used_slots+2] = reinterpret_cast<void*>(stack->depth);
3254 for (int d = 0; d < stack->depth; d++) {
3255 result[used_slots+3+d] = stack->stack[d];
3257 used_slots += 3 + stack->depth;
3259 result[used_slots] = reinterpret_cast<void*>(static_cast<uintptr_t>(0));
3266 // TCMalloc's support for extra malloc interfaces
3267 class TCMallocImplementation : public MallocExtension {
3269 virtual void GetStats(char* buffer, int buffer_length) {
3270 ASSERT(buffer_length > 0);
3271 TCMalloc_Printer printer(buffer, buffer_length);
3273 // Print level one stats unless lots of space is available
3274 if (buffer_length < 10000) {
3275 DumpStats(&printer, 1);
3277 DumpStats(&printer, 2);
3281 virtual void** ReadStackTraces() {
3282 return DumpStackTraces();
3285 virtual bool GetNumericProperty(const char* name, size_t* value) {
3286 ASSERT(name != NULL);
3288 if (strcmp(name, "generic.current_allocated_bytes") == 0) {
3289 TCMallocStats stats;
3290 ExtractStats(&stats, NULL);
3291 *value = stats.system_bytes
3292 - stats.thread_bytes
3293 - stats.central_bytes
3294 - stats.pageheap_bytes;
3298 if (strcmp(name, "generic.heap_size") == 0) {
3299 TCMallocStats stats;
3300 ExtractStats(&stats, NULL);
3301 *value = stats.system_bytes;
3305 if (strcmp(name, "tcmalloc.slack_bytes") == 0) {
3306 // We assume that bytes in the page heap are not fragmented too
3307 // badly, and are therefore available for allocation.
3308 SpinLockHolder l(&pageheap_lock);
3309 *value = pageheap->FreeBytes();
3313 if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
3314 SpinLockHolder l(&pageheap_lock);
3315 *value = overall_thread_cache_size;
3319 if (strcmp(name, "tcmalloc.current_total_thread_cache_bytes") == 0) {
3320 TCMallocStats stats;
3321 ExtractStats(&stats, NULL);
3322 *value = stats.thread_bytes;
3329 virtual bool SetNumericProperty(const char* name, size_t value) {
3330 ASSERT(name != NULL);
3332 if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
3333 // Clip the value to a reasonable range
3334 if (value < kMinThreadCacheSize) value = kMinThreadCacheSize;
3335 if (value > (1<<30)) value = (1<<30); // Limit to 1GB
3337 SpinLockHolder l(&pageheap_lock);
3338 overall_thread_cache_size = static_cast<size_t>(value);
3339 TCMalloc_ThreadCache::RecomputeThreadCacheSize();
3346 virtual void MarkThreadIdle() {
3347 TCMalloc_ThreadCache::BecomeIdle();
3350 virtual void ReleaseFreeMemory() {
3351 SpinLockHolder h(&pageheap_lock);
3352 pageheap->ReleaseFreePages();
3357 // The constructor allocates an object to ensure that initialization
3358 // runs before main(), and therefore we do not have a chance to become
3359 // multi-threaded before initialization. We also create the TSD key
3360 // here. Presumably by the time this constructor runs, glibc is in
3361 // good enough shape to handle pthread_key_create().
3363 // The constructor also takes the opportunity to tell STL to use
3364 // tcmalloc. We want to do this early, before construct time, so
3365 // all user STL allocations go through tcmalloc (which works really
3368 // The destructor prints stats when the program exits.
3369 class TCMallocGuard {
3373 #ifdef HAVE_TLS // this is true if the cc/ld/libc combo support TLS
3374 // Check whether the kernel also supports TLS (needs to happen at runtime)
3375 CheckIfKernelSupportsTLS();
3378 #ifdef WIN32 // patch the windows VirtualAlloc, etc.
3379 PatchWindowsFunctions(); // defined in windows/patch_functions.cc
3383 TCMalloc_ThreadCache::InitTSD();
3386 MallocExtension::Register(new TCMallocImplementation);
3392 const char* env = getenv("MALLOCSTATS");
3394 int level = atoi(env);
3395 if (level < 1) level = 1;
3399 UnpatchWindowsFunctions();
3406 static TCMallocGuard module_enter_exit_hook;
3410 //-------------------------------------------------------------------
3411 // Helpers for the exported routines below
3412 //-------------------------------------------------------------------
3416 static Span* DoSampledAllocation(size_t size) {
3418 // Grab the stack trace outside the heap lock
3420 tmp.depth = GetStackTrace(tmp.stack, kMaxStackDepth, 1);
3423 SpinLockHolder h(&pageheap_lock);
3425 Span *span = pageheap->New(pages(size == 0 ? 1 : size));
3430 // Allocate stack trace
3431 StackTrace *stack = stacktrace_allocator.New();
3432 if (stack == NULL) {
3433 // Sampling failed because of lack of memory
3439 span->objects = stack;
3440 DLL_Prepend(&sampled_objects, span);
3446 static inline bool CheckCachedSizeClass(void *ptr) {
3447 PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
3448 size_t cached_value = pageheap->GetSizeClassIfCached(p);
3449 return cached_value == 0 ||
3450 cached_value == pageheap->GetDescriptor(p)->sizeclass;
3453 static inline void* CheckedMallocResult(void *result)
3455 ASSERT(result == 0 || CheckCachedSizeClass(result));
3459 static inline void* SpanToMallocResult(Span *span) {
3460 ASSERT_SPAN_COMMITTED(span);
3461 pageheap->CacheSizeClass(span->start, 0);
3463 CheckedMallocResult(reinterpret_cast<void*>(span->start << kPageShift));
3467 template <bool crashOnFailure>
3469 static ALWAYS_INLINE void* do_malloc(size_t size) {
3473 ASSERT(!isForbidden());
3476 // The following call forces module initialization
3477 TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCache();
3479 if ((FLAGS_tcmalloc_sample_parameter > 0) && heap->SampleAllocation(size)) {
3480 Span* span = DoSampledAllocation(size);
3482 ret = SpanToMallocResult(span);
3486 if (size > kMaxSize) {
3487 // Use page-level allocator
3488 SpinLockHolder h(&pageheap_lock);
3489 Span* span = pageheap->New(pages(size));
3491 ret = SpanToMallocResult(span);
3494 // The common case, and also the simplest. This just pops the
3495 // size-appropriate freelist, afer replenishing it if it's empty.
3496 ret = CheckedMallocResult(heap->Allocate(size));
3500 if (crashOnFailure) // This branch should be optimized out by the compiler.
3509 static ALWAYS_INLINE void do_free(void* ptr) {
3510 if (ptr == NULL) return;
3511 ASSERT(pageheap != NULL); // Should not call free() before malloc()
3512 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
3514 size_t cl = pageheap->GetSizeClassIfCached(p);
3517 span = pageheap->GetDescriptor(p);
3518 cl = span->sizeclass;
3519 pageheap->CacheSizeClass(p, cl);
3522 #ifndef NO_TCMALLOC_SAMPLES
3523 ASSERT(!pageheap->GetDescriptor(p)->sample);
3525 TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCacheIfPresent();
3527 heap->Deallocate(ptr, cl);
3529 // Delete directly into central cache
3530 SLL_SetNext(ptr, NULL);
3531 central_cache[cl].InsertRange(ptr, ptr, 1);
3534 SpinLockHolder h(&pageheap_lock);
3535 ASSERT(reinterpret_cast<uintptr_t>(ptr) % kPageSize == 0);
3536 ASSERT(span != NULL && span->start == p);
3537 #ifndef NO_TCMALLOC_SAMPLES
3540 stacktrace_allocator.Delete(reinterpret_cast<StackTrace*>(span->objects));
3541 span->objects = NULL;
3544 pageheap->Delete(span);
3549 // For use by exported routines below that want specific alignments
3551 // Note: this code can be slow, and can significantly fragment memory.
3552 // The expectation is that memalign/posix_memalign/valloc/pvalloc will
3553 // not be invoked very often. This requirement simplifies our
3554 // implementation and allows us to tune for expected allocation
3556 static void* do_memalign(size_t align, size_t size) {
3557 ASSERT((align & (align - 1)) == 0);
3559 if (pageheap == NULL) TCMalloc_ThreadCache::InitModule();
3561 // Allocate at least one byte to avoid boundary conditions below
3562 if (size == 0) size = 1;
3564 if (size <= kMaxSize && align < kPageSize) {
3565 // Search through acceptable size classes looking for one with
3566 // enough alignment. This depends on the fact that
3567 // InitSizeClasses() currently produces several size classes that
3568 // are aligned at powers of two. We will waste time and space if
3569 // we miss in the size class array, but that is deemed acceptable
3570 // since memalign() should be used rarely.
3571 size_t cl = SizeClass(size);
3572 while (cl < kNumClasses && ((class_to_size[cl] & (align - 1)) != 0)) {
3575 if (cl < kNumClasses) {
3576 TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCache();
3577 return CheckedMallocResult(heap->Allocate(class_to_size[cl]));
3581 // We will allocate directly from the page heap
3582 SpinLockHolder h(&pageheap_lock);
3584 if (align <= kPageSize) {
3585 // Any page-level allocation will be fine
3586 // TODO: We could put the rest of this page in the appropriate
3587 // TODO: cache but it does not seem worth it.
3588 Span* span = pageheap->New(pages(size));
3589 return span == NULL ? NULL : SpanToMallocResult(span);
3592 // Allocate extra pages and carve off an aligned portion
3593 const Length alloc = pages(size + align);
3594 Span* span = pageheap->New(alloc);
3595 if (span == NULL) return NULL;
3597 // Skip starting portion so that we end up aligned
3599 while ((((span->start+skip) << kPageShift) & (align - 1)) != 0) {
3602 ASSERT(skip < alloc);
3604 Span* rest = pageheap->Split(span, skip);
3605 pageheap->Delete(span);
3609 // Skip trailing portion that we do not need to return
3610 const Length needed = pages(size);
3611 ASSERT(span->length >= needed);
3612 if (span->length > needed) {
3613 Span* trailer = pageheap->Split(span, needed);
3614 pageheap->Delete(trailer);
3616 return SpanToMallocResult(span);
3620 // Helpers for use by exported routines below:
3623 static inline void do_malloc_stats() {
3628 static inline int do_mallopt(int, int) {
3629 return 1; // Indicates error
3632 #ifdef HAVE_STRUCT_MALLINFO // mallinfo isn't defined on freebsd, for instance
3633 static inline struct mallinfo do_mallinfo() {
3634 TCMallocStats stats;
3635 ExtractStats(&stats, NULL);
3637 // Just some of the fields are filled in.
3638 struct mallinfo info;
3639 memset(&info, 0, sizeof(info));
3641 // Unfortunately, the struct contains "int" field, so some of the
3642 // size values will be truncated.
3643 info.arena = static_cast<int>(stats.system_bytes);
3644 info.fsmblks = static_cast<int>(stats.thread_bytes
3645 + stats.central_bytes
3646 + stats.transfer_bytes);
3647 info.fordblks = static_cast<int>(stats.pageheap_bytes);
3648 info.uordblks = static_cast<int>(stats.system_bytes
3649 - stats.thread_bytes
3650 - stats.central_bytes
3651 - stats.transfer_bytes
3652 - stats.pageheap_bytes);