2 * Copyright (C) 2013 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "wtf/PartitionAlloc.h"
40 // Two partition pages are used as guard / metadata page so make sure the super
41 // page size is bigger.
42 COMPILE_ASSERT(WTF::kPartitionPageSize * 4 <= WTF::kSuperPageSize, ok_super_page_size);
43 COMPILE_ASSERT(!(WTF::kSuperPageSize % WTF::kPartitionPageSize), ok_super_page_multiple);
44 // Four system pages gives us room to hack out a still-guard-paged piece
45 // of metadata in the middle of a guard partition page.
46 COMPILE_ASSERT(WTF::kSystemPageSize * 4 <= WTF::kPartitionPageSize, ok_partition_page_size);
47 COMPILE_ASSERT(!(WTF::kPartitionPageSize % WTF::kSystemPageSize), ok_partition_page_multiple);
48 COMPILE_ASSERT(sizeof(WTF::PartitionPage) <= WTF::kPageMetadataSize, PartitionPage_not_too_big);
49 COMPILE_ASSERT(sizeof(WTF::PartitionBucket) <= WTF::kPageMetadataSize, PartitionBucket_not_too_big);
50 COMPILE_ASSERT(sizeof(WTF::PartitionSuperPageExtentEntry) <= WTF::kPageMetadataSize, PartitionSuperPageExtentEntry_not_too_big);
51 COMPILE_ASSERT(WTF::kPageMetadataSize * WTF::kNumPartitionPagesPerSuperPage <= WTF::kSystemPageSize, page_metadata_fits_in_hole);
52 // Check that some of our zanier calculations worked out as expected.
53 COMPILE_ASSERT(WTF::kGenericSmallestBucket == 8, generic_smallest_bucket);
54 COMPILE_ASSERT(WTF::kGenericMaxBucketed == 983040, generic_max_bucketed);
58 int PartitionRootBase::gInitializedLock = 0;
59 bool PartitionRootBase::gInitialized = false;
60 PartitionPage PartitionRootBase::gSeedPage;
61 PartitionBucket PartitionRootBase::gPagedBucket;
63 static size_t partitionBucketNumSystemPages(size_t size)
65 // This works out reasonably for the current bucket sizes of the generic
66 // allocator, and the current values of partition page size and constants.
67 // Specifically, we have enough room to always pack the slots perfectly into
68 // some number of system pages. The only waste is the waste associated with
69 // unfaulted pages (i.e. wasted address space).
70 // TODO: we end up using a lot of system pages for very small sizes. For
71 // example, we'll use 12 system pages for slot size 24. The slot size is
72 // so small that the waste would be tiny with just 4, or 1, system pages.
73 // Later, we can investigate whether there are anti-fragmentation benefits
74 // to using fewer system pages.
75 double bestWasteRatio = 1.0f;
77 if (size > kMaxSystemPagesPerSlotSpan * kSystemPageSize) {
78 ASSERT(!(size % kSystemPageSize));
79 return size / kSystemPageSize;
81 ASSERT(size <= kMaxSystemPagesPerSlotSpan * kSystemPageSize);
82 for (size_t i = kNumSystemPagesPerPartitionPage - 1; i <= kMaxSystemPagesPerSlotSpan; ++i) {
83 size_t pageSize = kSystemPageSize * i;
84 size_t numSlots = pageSize / size;
85 size_t waste = pageSize - (numSlots * size);
86 // Leaving a page unfaulted is not free; the page will occupy an empty page table entry.
87 // Make a simple attempt to account for that.
88 size_t numRemainderPages = i & (kNumSystemPagesPerPartitionPage - 1);
89 size_t numUnfaultedPages = numRemainderPages ? (kNumSystemPagesPerPartitionPage - numRemainderPages) : 0;
90 waste += sizeof(void*) * numUnfaultedPages;
91 double wasteRatio = (double) waste / (double) pageSize;
92 if (wasteRatio < bestWasteRatio) {
93 bestWasteRatio = wasteRatio;
97 ASSERT(bestPages > 0);
101 static void parititonAllocBaseInit(PartitionRootBase* root)
103 ASSERT(!root->initialized);
105 spinLockLock(&PartitionRootBase::gInitializedLock);
106 if (!PartitionRootBase::gInitialized) {
107 PartitionRootBase::gInitialized = true;
108 // We mark the seed page as free to make sure it is skipped by our
109 // logic to find a new active page.
110 PartitionRootBase::gPagedBucket.activePagesHead = &PartitionRootGeneric::gSeedPage;
112 spinLockUnlock(&PartitionRootBase::gInitializedLock);
114 root->initialized = true;
115 root->totalSizeOfSuperPages = 0;
116 root->nextSuperPage = 0;
117 root->nextPartitionPage = 0;
118 root->nextPartitionPageEnd = 0;
119 root->firstExtent = 0;
120 root->currentExtent = 0;
122 memset(&root->globalEmptyPageRing, '\0', sizeof(root->globalEmptyPageRing));
123 root->globalEmptyPageRingIndex = 0;
125 // This is a "magic" value so we can test if a root pointer is valid.
126 root->invertedSelf = ~reinterpret_cast<uintptr_t>(root);
129 static void partitionBucketInitBase(PartitionBucket* bucket, PartitionRootBase* root)
131 bucket->activePagesHead = &PartitionRootGeneric::gSeedPage;
132 bucket->freePagesHead = 0;
133 bucket->numFullPages = 0;
134 bucket->numSystemPagesPerSlotSpan = partitionBucketNumSystemPages(bucket->slotSize);
137 void partitionAllocInit(PartitionRoot* root, size_t numBuckets, size_t maxAllocation)
139 parititonAllocBaseInit(root);
141 root->numBuckets = numBuckets;
142 root->maxAllocation = maxAllocation;
144 for (i = 0; i < root->numBuckets; ++i) {
145 PartitionBucket* bucket = &root->buckets()[i];
147 bucket->slotSize = kAllocationGranularity;
149 bucket->slotSize = i << kBucketShift;
150 partitionBucketInitBase(bucket, root);
154 void partitionAllocGenericInit(PartitionRootGeneric* root)
156 parititonAllocBaseInit(root);
160 // Precalculate some shift and mask constants used in the hot path.
161 // Example: malloc(41) == 101001 binary.
162 // Order is 6 (1 << 6-1)==32 is highest bit set.
163 // orderIndex is the next three MSB == 010 == 2.
164 // subOrderIndexMask is a mask for the remaining bits == 11 (masking to 01 for the subOrderIndex).
166 for (order = 0; order <= kBitsPerSizet; ++order) {
167 size_t orderIndexShift;
168 if (order < kGenericNumBucketsPerOrderBits + 1)
171 orderIndexShift = order - (kGenericNumBucketsPerOrderBits + 1);
172 root->orderIndexShifts[order] = orderIndexShift;
173 size_t subOrderIndexMask;
174 if (order == kBitsPerSizet) {
175 // This avoids invoking undefined behavior for an excessive shift.
176 subOrderIndexMask = static_cast<size_t>(-1) >> (kGenericNumBucketsPerOrderBits + 1);
178 subOrderIndexMask = ((1 << order) - 1) >> (kGenericNumBucketsPerOrderBits + 1);
180 root->orderSubIndexMasks[order] = subOrderIndexMask;
183 // Set up the actual usable buckets first.
184 // Note that typical values (i.e. min allocation size of 8) will result in
185 // invalid buckets (size==9 etc. or more generally, size is not a multiple
186 // of the smallest allocation granularity).
187 // We avoid them in the bucket lookup map, but we tolerate them to keep the
188 // code simpler and the structures more generic.
190 size_t currentSize = kGenericSmallestBucket;
191 size_t currentIncrement = kGenericSmallestBucket >> kGenericNumBucketsPerOrderBits;
192 PartitionBucket* bucket = &root->buckets[0];
193 for (i = 0; i < kGenericNumBucketedOrders; ++i) {
194 for (j = 0; j < kGenericNumBucketsPerOrder; ++j) {
195 bucket->slotSize = currentSize;
196 partitionBucketInitBase(bucket, root);
197 // Disable invalid buckets so that touching them faults.
198 if (currentSize % kGenericSmallestBucket)
199 bucket->activePagesHead = 0;
200 currentSize += currentIncrement;
203 currentIncrement <<= 1;
205 ASSERT(currentSize == 1 << kGenericMaxBucketedOrder);
206 ASSERT(bucket == &root->buckets[0] + (kGenericNumBucketedOrders * kGenericNumBucketsPerOrder));
208 // Then set up the fast size -> bucket lookup table.
209 bucket = &root->buckets[0];
210 PartitionBucket** bucketPtr = &root->bucketLookups[0];
211 for (order = 0; order <= kBitsPerSizet; ++order) {
212 for (j = 0; j < kGenericNumBucketsPerOrder; ++j) {
213 if (order < kGenericMinBucketedOrder) {
214 // Use the bucket of finest granularity for malloc(0) etc.
215 *bucketPtr++ = &root->buckets[0];
216 } else if (order > kGenericMaxBucketedOrder) {
217 *bucketPtr++ = &PartitionRootGeneric::gPagedBucket;
219 PartitionBucket* validBucket = bucket;
220 // Skip over invalid buckets.
221 while (validBucket->slotSize % kGenericSmallestBucket)
223 *bucketPtr++ = validBucket;
228 ASSERT(bucket == &root->buckets[0] + (kGenericNumBucketedOrders * kGenericNumBucketsPerOrder));
229 ASSERT(bucketPtr == &root->bucketLookups[0] + ((kBitsPerSizet + 1) * kGenericNumBucketsPerOrder));
230 // And there's one last bucket lookup that will be hit for e.g. malloc(-1),
231 // which tries to overflow to a non-existant order.
232 *bucketPtr = &PartitionRootGeneric::gPagedBucket;
235 static bool partitionAllocShutdownBucket(PartitionBucket* bucket)
237 // Failure here indicates a memory leak.
238 bool noLeaks = !bucket->numFullPages;
239 PartitionPage* page = bucket->activePagesHead;
241 if (page->numAllocatedSlots)
243 page = page->nextPage;
249 static void partitionAllocBaseShutdown(PartitionRootBase* root)
251 ASSERT(root->initialized);
252 root->initialized = false;
254 // Now that we've examined all partition pages in all buckets, it's safe
255 // to free all our super pages. We first collect the super page pointers
256 // on the stack because some of them are themselves store in super pages.
257 char* superPages[kMaxPartitionSize / kSuperPageSize];
258 size_t numSuperPages = 0;
259 PartitionSuperPageExtentEntry* entry = root->firstExtent;
261 char* superPage = entry->superPageBase;
262 while (superPage != entry->superPagesEnd) {
263 superPages[numSuperPages] = superPage;
265 superPage += kSuperPageSize;
269 ASSERT(numSuperPages == root->totalSizeOfSuperPages / kSuperPageSize);
270 for (size_t i = 0; i < numSuperPages; ++i)
271 freePages(superPages[i], kSuperPageSize);
274 bool partitionAllocShutdown(PartitionRoot* root)
278 for (i = 0; i < root->numBuckets; ++i) {
279 PartitionBucket* bucket = &root->buckets()[i];
280 if (!partitionAllocShutdownBucket(bucket))
284 partitionAllocBaseShutdown(root);
288 bool partitionAllocGenericShutdown(PartitionRootGeneric* root)
292 for (i = 0; i < kGenericNumBucketedOrders * kGenericNumBucketsPerOrder; ++i) {
293 PartitionBucket* bucket = &root->buckets[i];
294 if (!partitionAllocShutdownBucket(bucket))
297 partitionAllocBaseShutdown(root);
301 static NEVER_INLINE void partitionOutOfMemory()
306 static NEVER_INLINE void partitionFull()
311 static ALWAYS_INLINE void* partitionAllocPartitionPages(PartitionRootBase* root, size_t numPartitionPages)
313 ASSERT(!(reinterpret_cast<uintptr_t>(root->nextPartitionPage) % kPartitionPageSize));
314 ASSERT(!(reinterpret_cast<uintptr_t>(root->nextPartitionPageEnd) % kPartitionPageSize));
315 RELEASE_ASSERT(numPartitionPages <= kNumPartitionPagesPerSuperPage);
316 size_t totalSize = kPartitionPageSize * numPartitionPages;
317 size_t numPartitionPagesLeft = (root->nextPartitionPageEnd - root->nextPartitionPage) >> kPartitionPageShift;
318 if (LIKELY(numPartitionPagesLeft >= numPartitionPages)) {
319 // In this case, we can still hand out pages from the current super page
321 char* ret = root->nextPartitionPage;
322 root->nextPartitionPage += totalSize;
326 // Need a new super page.
327 root->totalSizeOfSuperPages += kSuperPageSize;
328 if (root->totalSizeOfSuperPages > kMaxPartitionSize)
330 char* requestedAddress = root->nextSuperPage;
331 char* superPage = reinterpret_cast<char*>(allocPages(requestedAddress, kSuperPageSize, kSuperPageSize));
332 // TODO: handle allocation failure here with PartitionAllocReturnNull.
334 partitionOutOfMemory();
335 root->nextSuperPage = superPage + kSuperPageSize;
336 char* ret = superPage + kPartitionPageSize;
337 root->nextPartitionPage = ret + totalSize;
338 root->nextPartitionPageEnd = root->nextSuperPage - kPartitionPageSize;
339 // Make the first partition page in the super page a guard page, but leave a
340 // hole in the middle.
341 // This is where we put page metadata and also a tiny amount of extent
343 setSystemPagesInaccessible(superPage, kSystemPageSize);
344 setSystemPagesInaccessible(superPage + (kSystemPageSize * 2), kPartitionPageSize - (kSystemPageSize * 2));
345 // Also make the last partition page a guard page.
346 setSystemPagesInaccessible(superPage + (kSuperPageSize - kPartitionPageSize), kPartitionPageSize);
348 // If we were after a specific address, but didn't get it, assume that
349 // the system chose a lousy address and re-randomize the next
351 if (requestedAddress && requestedAddress != superPage)
352 root->nextSuperPage = 0;
354 // We allocated a new super page so update super page metadata.
355 // First check if this is a new extent or not.
356 PartitionSuperPageExtentEntry* latestExtent = reinterpret_cast<PartitionSuperPageExtentEntry*>(partitionSuperPageToMetadataArea(superPage));
357 PartitionSuperPageExtentEntry* currentExtent = root->currentExtent;
358 bool isNewExtent = (superPage != requestedAddress);
359 if (UNLIKELY(isNewExtent)) {
360 latestExtent->next = 0;
361 if (UNLIKELY(!currentExtent)) {
362 root->firstExtent = latestExtent;
364 ASSERT(currentExtent->superPageBase);
365 currentExtent->next = latestExtent;
367 root->currentExtent = latestExtent;
368 currentExtent = latestExtent;
369 currentExtent->superPageBase = superPage;
370 currentExtent->superPagesEnd = superPage + kSuperPageSize;
372 // We allocated next to an existing extent so just nudge the size up a little.
373 currentExtent->superPagesEnd += kSuperPageSize;
374 ASSERT(ret >= currentExtent->superPageBase && ret < currentExtent->superPagesEnd);
376 // By storing the root in every extent metadata object, we have a fast way
377 // to go from a pointer within the partition to the root object.
378 latestExtent->root = root;
383 static ALWAYS_INLINE void partitionUnusePage(PartitionPage* page)
385 ASSERT(page->bucket->numSystemPagesPerSlotSpan);
386 void* addr = partitionPageToPointer(page);
387 decommitSystemPages(addr, page->bucket->numSystemPagesPerSlotSpan * kSystemPageSize);
390 static ALWAYS_INLINE size_t partitionBucketSlots(const PartitionBucket* bucket)
392 return (bucket->numSystemPagesPerSlotSpan * kSystemPageSize) / bucket->slotSize;
395 static ALWAYS_INLINE size_t partitionBucketPartitionPages(const PartitionBucket* bucket)
397 return (bucket->numSystemPagesPerSlotSpan + (kNumSystemPagesPerPartitionPage - 1)) / kNumSystemPagesPerPartitionPage;
400 static ALWAYS_INLINE void partitionPageReset(PartitionPage* page, PartitionBucket* bucket)
402 ASSERT(page != &PartitionRootGeneric::gSeedPage);
403 page->numAllocatedSlots = 0;
404 page->numUnprovisionedSlots = partitionBucketSlots(bucket);
405 ASSERT(page->numUnprovisionedSlots);
406 page->bucket = bucket;
408 // NULLing the freelist is not strictly necessary but it makes an ASSERT in partitionPageFillFreelist simpler.
409 page->freelistHead = 0;
410 page->pageOffset = 0;
411 page->freeCacheIndex = -1;
412 size_t numPartitionPages = partitionBucketPartitionPages(bucket);
414 char* pageCharPtr = reinterpret_cast<char*>(page);
415 for (i = 1; i < numPartitionPages; ++i) {
416 pageCharPtr += kPageMetadataSize;
417 PartitionPage* secondaryPage = reinterpret_cast<PartitionPage*>(pageCharPtr);
418 secondaryPage->pageOffset = i;
422 static ALWAYS_INLINE char* partitionPageAllocAndFillFreelist(PartitionPage* page)
424 ASSERT(page != &PartitionRootGeneric::gSeedPage);
425 size_t numSlots = page->numUnprovisionedSlots;
427 PartitionBucket* bucket = page->bucket;
428 // We should only get here when _every_ slot is either used or unprovisioned.
429 // (The third state is "on the freelist". If we have a non-empty freelist, we should not get here.)
430 ASSERT(numSlots + page->numAllocatedSlots == partitionBucketSlots(bucket));
431 // Similarly, make explicitly sure that the freelist is empty.
432 ASSERT(!page->freelistHead);
433 ASSERT(page->numAllocatedSlots >= 0);
435 size_t size = bucket->slotSize;
436 char* base = reinterpret_cast<char*>(partitionPageToPointer(page));
437 char* returnObject = base + (size * page->numAllocatedSlots);
438 char* firstFreelistPointer = returnObject + size;
439 char* firstFreelistPointerExtent = firstFreelistPointer + sizeof(PartitionFreelistEntry*);
440 // Our goal is to fault as few system pages as possible. We calculate the
441 // page containing the "end" of the returned slot, and then allow freelist
442 // pointers to be written up to the end of that page.
443 char* subPageLimit = reinterpret_cast<char*>((reinterpret_cast<uintptr_t>(firstFreelistPointer) + kSystemPageOffsetMask) & kSystemPageBaseMask);
444 char* slotsLimit = returnObject + (size * page->numUnprovisionedSlots);
445 char* freelistLimit = subPageLimit;
446 if (UNLIKELY(slotsLimit < freelistLimit))
447 freelistLimit = slotsLimit;
449 size_t numNewFreelistEntries = 0;
450 if (LIKELY(firstFreelistPointerExtent <= freelistLimit)) {
451 // Only consider used space in the slot span. If we consider wasted
452 // space, we may get an off-by-one when a freelist pointer fits in the
453 // wasted space, but a slot does not.
454 // We know we can fit at least one freelist pointer.
455 numNewFreelistEntries = 1;
456 // Any further entries require space for the whole slot span.
457 numNewFreelistEntries += (freelistLimit - firstFreelistPointerExtent) / size;
460 // We always return an object slot -- that's the +1 below.
461 // We do not neccessarily create any new freelist entries, because we cross sub page boundaries frequently for large bucket sizes.
462 ASSERT(numNewFreelistEntries + 1 <= numSlots);
463 numSlots -= (numNewFreelistEntries + 1);
464 page->numUnprovisionedSlots = numSlots;
465 page->numAllocatedSlots++;
467 if (LIKELY(numNewFreelistEntries)) {
468 char* freelistPointer = firstFreelistPointer;
469 PartitionFreelistEntry* entry = reinterpret_cast<PartitionFreelistEntry*>(freelistPointer);
470 page->freelistHead = entry;
471 while (--numNewFreelistEntries) {
472 freelistPointer += size;
473 PartitionFreelistEntry* nextEntry = reinterpret_cast<PartitionFreelistEntry*>(freelistPointer);
474 entry->next = partitionFreelistMask(nextEntry);
477 entry->next = partitionFreelistMask(0);
479 page->freelistHead = 0;
484 // This helper function scans the active page list for a suitable new active
485 // page, starting at the passed in page.
486 // When it finds a suitable new active page (one that has free slots), it is
487 // set as the new active page and true is returned. If there is no suitable new
488 // active page, false is returned and the current active page is set to null.
489 // As potential pages are scanned, they are tidied up according to their state.
490 // Freed pages are swept on to the free page list and full pages are unlinked
492 static ALWAYS_INLINE bool partitionSetNewActivePage(PartitionPage* page)
494 if (page == &PartitionRootBase::gSeedPage) {
495 ASSERT(!page->nextPage);
499 PartitionPage* nextPage = 0;
500 PartitionBucket* bucket = page->bucket;
502 for (; page; page = nextPage) {
503 nextPage = page->nextPage;
504 ASSERT(page->bucket == bucket);
505 ASSERT(page != bucket->freePagesHead);
506 ASSERT(!bucket->freePagesHead || page != bucket->freePagesHead->nextPage);
508 // Page is usable if it has something on the freelist, or unprovisioned
509 // slots that can be turned into a freelist.
510 if (LIKELY(page->freelistHead != 0) || LIKELY(page->numUnprovisionedSlots)) {
511 bucket->activePagesHead = page;
515 ASSERT(page->numAllocatedSlots >= 0);
516 if (LIKELY(page->numAllocatedSlots == 0)) {
517 ASSERT(page->freeCacheIndex == -1);
518 // We hit a free page, so shepherd it on to the free page list.
519 page->nextPage = bucket->freePagesHead;
520 bucket->freePagesHead = page;
522 // If we get here, we found a full page. Skip over it too, and also
523 // tag it as full (via a negative value). We need it tagged so that
524 // free'ing can tell, and move it back into the active page list.
525 ASSERT(page->numAllocatedSlots == static_cast<int>(partitionBucketSlots(bucket)));
526 page->numAllocatedSlots = -page->numAllocatedSlots;
527 ++bucket->numFullPages;
528 // numFullPages is a uint16_t for efficient packing so guard against
529 // overflow to be safe.
530 RELEASE_ASSERT(bucket->numFullPages);
531 // Not necessary but might help stop accidents.
536 bucket->activePagesHead = 0;
540 struct PartitionDirectMapExtent {
541 size_t mapSize; // Mapped size, not including guard pages and meta-data.
544 static ALWAYS_INLINE PartitionDirectMapExtent* partitionPageToDirectMapExtent(PartitionPage* page)
546 ASSERT(partitionBucketIsDirectMapped(page->bucket));
547 return reinterpret_cast<PartitionDirectMapExtent*>(reinterpret_cast<char*>(page) + 2 * kPageMetadataSize);
550 static ALWAYS_INLINE void* partitionDirectMap(PartitionRootBase* root, int flags, size_t size)
552 size = partitionDirectMapSize(size);
554 // Because we need to fake looking like a super page, We need to allocate
555 // a bunch of system pages more than "size":
556 // - The first few system pages are the partition page in which the super
557 // page metadata is stored. We fault just one system page out of a partition
559 // - We add a trailing guard page.
560 size_t mapSize = size + kPartitionPageSize + kSystemPageSize;
561 // Round up to the allocation granularity.
562 mapSize += kPageAllocationGranularityOffsetMask;
563 mapSize &= kPageAllocationGranularityBaseMask;
565 // TODO: we may want to let the operating system place these allocations
566 // where it pleases. On 32-bit, this might limit address space
567 // fragmentation and on 64-bit, this might have useful savings for TLB
568 // and page table overhead.
569 // TODO: if upsizing realloc()s are common on large sizes, we could
570 // consider over-allocating address space on 64-bit, "just in case".
571 // TODO: consider pre-populating page tables (e.g. MAP_POPULATE on Linux,
572 // MADV_WILLNEED on POSIX).
573 // TODO: these pages will be zero-filled. Consider internalizing an
574 // allocZeroed() API so we can avoid a memset() entirely in this case.
575 char* ptr = reinterpret_cast<char*>(allocPages(0, mapSize, kSuperPageSize));
577 if (flags & PartitionAllocReturnNull)
579 partitionOutOfMemory();
581 char* ret = ptr + kPartitionPageSize;
582 // TODO: due to all the guard paging, this arrangement creates 4 mappings.
583 // We could get it down to three by using read-only for the metadata page,
584 // or perhaps two by leaving out the trailing guard page on 64-bit.
585 setSystemPagesInaccessible(ptr, kSystemPageSize);
586 setSystemPagesInaccessible(ptr + (kSystemPageSize * 2), kPartitionPageSize - (kSystemPageSize * 2));
587 setSystemPagesInaccessible(ret + size, kSystemPageSize);
589 PartitionSuperPageExtentEntry* extent = reinterpret_cast<PartitionSuperPageExtentEntry*>(partitionSuperPageToMetadataArea(ptr));
591 PartitionPage* page = partitionPointerToPageNoAlignmentCheck(ret);
592 PartitionBucket* bucket = reinterpret_cast<PartitionBucket*>(reinterpret_cast<char*>(page) + kPageMetadataSize);
593 page->freelistHead = 0;
595 page->bucket = bucket;
596 page->numAllocatedSlots = 1;
597 page->numUnprovisionedSlots = 0;
598 page->pageOffset = 0;
599 page->freeCacheIndex = 0;
601 bucket->activePagesHead = 0;
602 bucket->freePagesHead = 0;
603 bucket->slotSize = size;
604 bucket->numSystemPagesPerSlotSpan = 0;
605 bucket->numFullPages = 0;
607 PartitionDirectMapExtent* mapExtent = partitionPageToDirectMapExtent(page);
608 mapExtent->mapSize = mapSize - kPartitionPageSize - kSystemPageSize;
613 static ALWAYS_INLINE void partitionDirectUnmap(PartitionPage* page)
615 size_t unmapSize = partitionPageToDirectMapExtent(page)->mapSize;
617 // Add on the size of the trailing guard page and preceeding partition
619 unmapSize += kPartitionPageSize + kSystemPageSize;
621 ASSERT(!(unmapSize & kPageAllocationGranularityOffsetMask));
623 char* ptr = reinterpret_cast<char*>(partitionPageToPointer(page));
624 // Account for the mapping starting a partition page before the actual
625 // allocation address.
626 ptr -= kPartitionPageSize;
628 freePages(ptr, unmapSize);
631 void* partitionAllocSlowPath(PartitionRootBase* root, int flags, size_t size, PartitionBucket* bucket)
633 // The slow path is called when the freelist is empty.
634 ASSERT(!bucket->activePagesHead->freelistHead);
636 // For the partitionAllocGeneric API, we have a bunch of buckets marked
637 // as special cases. We bounce them through to the slow path so that we
638 // can still have a blazing fast hot path due to lack of corner-case
640 bool returnNull = flags & PartitionAllocReturnNull;
641 if (UNLIKELY(partitionBucketIsDirectMapped(bucket))) {
642 ASSERT(size > kGenericMaxBucketed);
643 ASSERT(bucket == &PartitionRootBase::gPagedBucket);
644 if (size > kGenericMaxDirectMapped) {
647 RELEASE_ASSERT(false);
649 return partitionDirectMap(root, flags, size);
652 // First, look for a usable page in the existing active pages list.
653 // Change active page, accepting the current page as a candidate.
654 if (LIKELY(partitionSetNewActivePage(bucket->activePagesHead))) {
655 PartitionPage* newPage = bucket->activePagesHead;
656 if (LIKELY(newPage->freelistHead != 0)) {
657 PartitionFreelistEntry* ret = newPage->freelistHead;
658 newPage->freelistHead = partitionFreelistMask(ret->next);
659 newPage->numAllocatedSlots++;
662 ASSERT(newPage->numUnprovisionedSlots);
663 return partitionPageAllocAndFillFreelist(newPage);
666 // Second, look in our list of freed but reserved pages.
667 PartitionPage* newPage = bucket->freePagesHead;
668 if (LIKELY(newPage != 0)) {
669 ASSERT(newPage != &PartitionRootGeneric::gSeedPage);
670 ASSERT(!newPage->freelistHead);
671 ASSERT(!newPage->numAllocatedSlots);
672 ASSERT(!newPage->numUnprovisionedSlots);
673 ASSERT(newPage->freeCacheIndex == -1);
674 bucket->freePagesHead = newPage->nextPage;
676 // Third. If we get here, we need a brand new page.
677 size_t numPartitionPages = partitionBucketPartitionPages(bucket);
678 void* rawNewPage = partitionAllocPartitionPages(root, numPartitionPages);
679 // Skip the alignment check because it depends on page->bucket, which is not yet set.
680 newPage = partitionPointerToPageNoAlignmentCheck(rawNewPage);
683 partitionPageReset(newPage, bucket);
684 bucket->activePagesHead = newPage;
685 return partitionPageAllocAndFillFreelist(newPage);
688 static ALWAYS_INLINE void partitionFreePage(PartitionPage* page)
690 ASSERT(page->freelistHead);
691 ASSERT(!page->numAllocatedSlots);
692 partitionUnusePage(page);
693 // We actually leave the freed page in the active list. We'll sweep it on
694 // to the free page list when we next walk the active page list. Pulling
695 // this trick enables us to use a singly-linked page list for all cases,
696 // which is critical in keeping the page metadata structure down to 32
698 page->freelistHead = 0;
699 page->numUnprovisionedSlots = 0;
702 static ALWAYS_INLINE void partitionRegisterEmptyPage(PartitionPage* page)
704 PartitionRootBase* root = partitionPageToRoot(page);
705 // If the page is already registered as empty, give it another life.
706 if (page->freeCacheIndex != -1) {
707 ASSERT(page->freeCacheIndex >= 0);
708 ASSERT(static_cast<unsigned>(page->freeCacheIndex) < kMaxFreeableSpans);
709 ASSERT(root->globalEmptyPageRing[page->freeCacheIndex] == page);
710 root->globalEmptyPageRing[page->freeCacheIndex] = 0;
713 size_t currentIndex = root->globalEmptyPageRingIndex;
714 PartitionPage* pageToFree = root->globalEmptyPageRing[currentIndex];
715 // The page might well have been re-activated, filled up, etc. before we get
716 // around to looking at it here.
718 ASSERT(pageToFree != &PartitionRootBase::gSeedPage);
719 ASSERT(pageToFree->freeCacheIndex >= 0);
720 ASSERT(static_cast<unsigned>(pageToFree->freeCacheIndex) < kMaxFreeableSpans);
721 ASSERT(pageToFree == root->globalEmptyPageRing[pageToFree->freeCacheIndex]);
722 if (!pageToFree->numAllocatedSlots && pageToFree->freelistHead) {
723 // The page is still empty, and not freed, so _really_ free it.
724 partitionFreePage(pageToFree);
726 pageToFree->freeCacheIndex = -1;
729 // We put the empty slot span on our global list of "pages that were once
730 // empty". thus providing it a bit of breathing room to get re-used before
731 // we really free it. This improves performance, particularly on Mac OS X
732 // which has subpar memory management performance.
733 root->globalEmptyPageRing[currentIndex] = page;
734 page->freeCacheIndex = currentIndex;
736 if (currentIndex == kMaxFreeableSpans)
738 root->globalEmptyPageRingIndex = currentIndex;
741 void partitionFreeSlowPath(PartitionPage* page)
743 PartitionBucket* bucket = page->bucket;
744 ASSERT(page != &PartitionRootGeneric::gSeedPage);
745 ASSERT(bucket->activePagesHead != &PartitionRootGeneric::gSeedPage);
746 if (LIKELY(page->numAllocatedSlots == 0)) {
747 // Page became fully unused.
748 if (UNLIKELY(partitionBucketIsDirectMapped(bucket))) {
749 partitionDirectUnmap(page);
752 // If it's the current page, attempt to change it. We'd prefer to leave
753 // the page empty as a gentle force towards defragmentation.
754 if (LIKELY(page == bucket->activePagesHead) && page->nextPage) {
755 if (partitionSetNewActivePage(page->nextPage)) {
756 ASSERT(bucket->activePagesHead != page);
757 // Link the empty page back in after the new current page, to
758 // avoid losing a reference to it.
759 // TODO: consider walking the list to link the empty page after
760 // all non-empty pages?
761 PartitionPage* currentPage = bucket->activePagesHead;
762 page->nextPage = currentPage->nextPage;
763 currentPage->nextPage = page;
765 bucket->activePagesHead = page;
769 partitionRegisterEmptyPage(page);
771 // Ensure that the page is full. That's the only valid case if we
773 ASSERT(page->numAllocatedSlots < 0);
774 // A transition of numAllocatedSlots from 0 to -1 is not legal, and
775 // likely indicates a double-free.
776 RELEASE_ASSERT(page->numAllocatedSlots != -1);
777 page->numAllocatedSlots = -page->numAllocatedSlots - 2;
778 ASSERT(page->numAllocatedSlots == static_cast<int>(partitionBucketSlots(bucket) - 1));
779 // Fully used page became partially used. It must be put back on the
780 // non-full page list. Also make it the current page to increase the
781 // chances of it being filled up again. The old current page will be
783 page->nextPage = bucket->activePagesHead;
784 bucket->activePagesHead = page;
785 --bucket->numFullPages;
786 // Special case: for a partition page with just a single slot, it may
787 // now be empty and we want to run it through the empty logic.
788 if (UNLIKELY(page->numAllocatedSlots == 0))
789 partitionFreeSlowPath(page);
793 bool partitionReallocDirectMappedInPlace(PartitionRootGeneric* root, PartitionPage* page, size_t newSize)
795 ASSERT(partitionBucketIsDirectMapped(page->bucket));
797 newSize = partitionCookieSizeAdjustAdd(newSize);
799 // Note that the new size might be a bucketed size; this function is called
800 // whenever we're reallocating a direct mapped allocation.
801 newSize = partitionDirectMapSize(newSize);
802 if (newSize < kGenericMinDirectMappedDownsize)
805 // bucket->slotSize is the current size of the allocation.
806 size_t currentSize = page->bucket->slotSize;
807 if (newSize == currentSize)
810 char* charPtr = static_cast<char*>(partitionPageToPointer(page));
812 if (newSize < currentSize) {
813 size_t mapSize = partitionPageToDirectMapExtent(page)->mapSize;
815 // Don't reallocate in-place if new size is less than 80 % of the full
816 // map size, to avoid holding on to too much unused address space.
817 if ((newSize / kSystemPageSize) * 5 < (mapSize / kSystemPageSize) * 4)
820 // Shrink by decommitting unneeded pages and making them inaccessible.
821 size_t decommitSize = currentSize - newSize;
822 decommitSystemPages(charPtr + newSize, decommitSize);
823 setSystemPagesInaccessible(charPtr + newSize, decommitSize);
824 } else if (newSize <= partitionPageToDirectMapExtent(page)->mapSize) {
825 // Grow within the actually allocated memory. Just need to make the
826 // pages accessible again.
827 size_t recommitSize = newSize - currentSize;
828 setSystemPagesAccessible(charPtr + currentSize, recommitSize);
831 memset(charPtr + currentSize, kUninitializedByte, recommitSize);
834 // We can't perform the realloc in-place.
835 // TODO: support this too when possible.
840 // Write a new trailing cookie.
841 partitionCookieWriteValue(charPtr + newSize - kCookieSize);
844 page->bucket->slotSize = newSize;
848 void* partitionReallocGeneric(PartitionRootGeneric* root, void* ptr, size_t newSize)
850 #if defined(MEMORY_TOOL_REPLACES_ALLOCATOR)
851 return realloc(ptr, newSize);
854 return partitionAllocGeneric(root, newSize);
855 if (UNLIKELY(!newSize)) {
856 partitionFreeGeneric(root, ptr);
860 RELEASE_ASSERT(newSize <= kGenericMaxDirectMapped);
862 ASSERT(partitionPointerIsValid(partitionCookieFreePointerAdjust(ptr)));
864 PartitionPage* page = partitionPointerToPage(partitionCookieFreePointerAdjust(ptr));
866 if (UNLIKELY(partitionBucketIsDirectMapped(page->bucket))) {
867 // We may be able to perform the realloc in place by changing the
868 // accessibility of memory pages and, if reducing the size, decommitting
870 if (partitionReallocDirectMappedInPlace(root, page, newSize))
874 size_t actualNewSize = partitionAllocActualSize(root, newSize);
875 size_t actualOldSize = partitionAllocGetSize(ptr);
877 // TODO: note that tcmalloc will "ignore" a downsizing realloc() unless the
878 // new size is a significant percentage smaller. We could do the same if we
879 // determine it is a win.
880 if (actualNewSize == actualOldSize) {
881 // Trying to allocate a block of size newSize would give us a block of
882 // the same size as the one we've already got, so no point in doing
887 // This realloc cannot be resized in-place. Sadness.
888 void* ret = partitionAllocGeneric(root, newSize);
889 size_t copySize = actualOldSize;
890 if (newSize < copySize)
893 memcpy(ret, ptr, copySize);
894 partitionFreeGeneric(root, ptr);
901 void partitionDumpStats(const PartitionRoot& root)
904 size_t totalLive = 0;
905 size_t totalResident = 0;
906 size_t totalFreeable = 0;
907 for (i = 0; i < root.numBuckets; ++i) {
908 const PartitionBucket& bucket = root.buckets()[i];
909 if (bucket.activePagesHead == &PartitionRootGeneric::gSeedPage && !bucket.freePagesHead && !bucket.numFullPages) {
910 // Empty bucket with no freelist or full pages. Skip reporting it.
913 size_t numFreePages = 0;
914 PartitionPage* freePages = bucket.freePagesHead;
917 freePages = freePages->nextPage;
919 size_t bucketSlotSize = bucket.slotSize;
920 size_t bucketNumSlots = partitionBucketSlots(&bucket);
921 size_t bucketUsefulStorage = bucketSlotSize * bucketNumSlots;
922 size_t bucketPageSize = bucket.numSystemPagesPerSlotSpan * kSystemPageSize;
923 size_t bucketWaste = bucketPageSize - bucketUsefulStorage;
924 size_t numActiveBytes = bucket.numFullPages * bucketUsefulStorage;
925 size_t numResidentBytes = bucket.numFullPages * bucketPageSize;
926 size_t numFreeableBytes = 0;
927 size_t numActivePages = 0;
928 const PartitionPage* page = bucket.activePagesHead;
930 if (page != &PartitionRootGeneric::gSeedPage) {
932 numActiveBytes += (page->numAllocatedSlots * bucketSlotSize);
933 size_t pageBytesResident = (bucketNumSlots - page->numUnprovisionedSlots) * bucketSlotSize;
934 // Round up to system page size.
935 pageBytesResident = (pageBytesResident + kSystemPageOffsetMask) & kSystemPageBaseMask;
936 numResidentBytes += pageBytesResident;
937 if (!page->numAllocatedSlots)
938 numFreeableBytes += pageBytesResident;
940 page = page->nextPage;
941 } while (page != bucket.activePagesHead);
942 totalLive += numActiveBytes;
943 totalResident += numResidentBytes;
944 totalFreeable += numFreeableBytes;
945 printf("bucket size %zu (pageSize %zu waste %zu): %zu alloc/%zu commit/%zu freeable bytes, %zu/%zu/%zu full/active/free pages\n", bucketSlotSize, bucketPageSize, bucketWaste, numActiveBytes, numResidentBytes, numFreeableBytes, static_cast<size_t>(bucket.numFullPages), numActivePages, numFreePages);
947 printf("total live: %zu bytes\n", totalLive);
948 printf("total resident: %zu bytes\n", totalResident);
949 printf("total freeable: %zu bytes\n", totalFreeable);