Unreviewed, rolling out r197955.
[WebKit-https.git] / Source / bmalloc / bmalloc / Heap.cpp
1 /*
2  * Copyright (C) 2014-2016 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "Heap.h"
27 #include "BumpAllocator.h"
28 #include "LargeChunk.h"
29 #include "LargeObject.h"
30 #include "PerProcess.h"
31 #include "SmallChunk.h"
32 #include "SmallLine.h"
33 #include "SmallPage.h"
34 #include <thread>
35
36 namespace bmalloc {
37
38 Heap::Heap(std::lock_guard<StaticMutex>&)
39     : m_largeObjects(VMState::HasPhysical::True)
40     , m_isAllocatingPages(false)
41     , m_scavenger(*this, &Heap::concurrentScavenge)
42 {
43     initializeLineMetadata();
44 }
45
46 void Heap::initializeLineMetadata()
47 {
48     // We assume that m_smallLineMetadata is zero-filled.
49
50     for (size_t size = alignment; size <= smallMax; size += alignment) {
51         size_t sizeClass = bmalloc::sizeClass(size);
52         auto& metadata = m_smallLineMetadata[sizeClass];
53
54         size_t object = 0;
55         size_t line = 0;
56         while (object < vmPageSize) {
57             line = object / smallLineSize;
58             size_t leftover = object % smallLineSize;
59
60             size_t objectCount;
61             size_t remainder;
62             divideRoundingUp(smallLineSize - leftover, size, objectCount, remainder);
63
64             metadata[line] = { static_cast<unsigned short>(leftover), static_cast<unsigned short>(objectCount) };
65
66             object += objectCount * size;
67         }
68
69         // Don't allow the last object in a page to escape the page.
70         if (object > vmPageSize) {
71             BASSERT(metadata[line].objectCount);
72             --metadata[line].objectCount;
73         }
74     }
75 }
76
77 void Heap::concurrentScavenge()
78 {
79     std::unique_lock<StaticMutex> lock(PerProcess<Heap>::mutex());
80     scavenge(lock, scavengeSleepDuration);
81 }
82
83 void Heap::scavenge(std::unique_lock<StaticMutex>& lock, std::chrono::milliseconds sleepDuration)
84 {
85     waitUntilFalse(lock, sleepDuration, m_isAllocatingPages);
86
87     scavengeSmallPages(lock, sleepDuration);
88     scavengeLargeObjects(lock, sleepDuration);
89     scavengeXLargeObjects(lock, sleepDuration);
90
91     sleep(lock, sleepDuration);
92 }
93
94 void Heap::scavengeSmallPages(std::unique_lock<StaticMutex>& lock, std::chrono::milliseconds sleepDuration)
95 {
96     while (!m_smallPages.isEmpty()) {
97         m_vmHeap.deallocateSmallPage(lock, m_smallPages.pop());
98         waitUntilFalse(lock, sleepDuration, m_isAllocatingPages);
99     }
100 }
101
102 void Heap::scavengeLargeObjects(std::unique_lock<StaticMutex>& lock, std::chrono::milliseconds sleepDuration)
103 {
104     while (LargeObject largeObject = m_largeObjects.takeGreedy()) {
105         m_vmHeap.deallocateLargeObject(lock, largeObject);
106         waitUntilFalse(lock, sleepDuration, m_isAllocatingPages);
107     }
108 }
109
110 void Heap::scavengeXLargeObjects(std::unique_lock<StaticMutex>& lock, std::chrono::milliseconds sleepDuration)
111 {
112     while (XLargeRange range = m_xLargeMap.takePhysical()) {
113         lock.unlock();
114         vmDeallocatePhysicalPagesSloppy(range.begin(), range.size());
115         lock.lock();
116         
117         range.setVMState(VMState::Virtual);
118         m_xLargeMap.addVirtual(range);
119
120         waitUntilFalse(lock, sleepDuration, m_isAllocatingPages);
121     }
122
123     m_xLargeMap.shrinkToFit();
124 }
125
126 void Heap::allocateSmallBumpRanges(std::lock_guard<StaticMutex>& lock, size_t sizeClass, BumpAllocator& allocator, BumpRangeCache& rangeCache)
127 {
128     BASSERT(!rangeCache.size());
129     SmallPage* page = allocateSmallPage(lock, sizeClass);
130     SmallLine* lines = page->begin();
131     BASSERT(page->hasFreeLines(lock));
132
133     // Find a free line.
134     for (size_t lineNumber = 0; lineNumber < smallLineCount; ++lineNumber) {
135         if (lines[lineNumber].refCount(lock))
136             continue;
137
138         LineMetadata& lineMetadata = m_smallLineMetadata[sizeClass][lineNumber];
139         if (!lineMetadata.objectCount)
140             continue;
141
142         // In a fragmented page, some free ranges might not fit in the cache.
143         if (rangeCache.size() == rangeCache.capacity()) {
144             m_smallPagesWithFreeLines[sizeClass].push(page);
145             BASSERT(allocator.canAllocate());
146             return;
147         }
148
149         char* begin = lines[lineNumber].begin() + lineMetadata.startOffset;
150         unsigned short objectCount = lineMetadata.objectCount;
151         lines[lineNumber].ref(lock, lineMetadata.objectCount);
152         page->ref(lock);
153
154         // Merge with subsequent free lines.
155         while (++lineNumber < smallLineCount) {
156             if (lines[lineNumber].refCount(lock))
157                 break;
158
159             LineMetadata& lineMetadata = m_smallLineMetadata[sizeClass][lineNumber];
160             if (!lineMetadata.objectCount)
161                 continue;
162
163             objectCount += lineMetadata.objectCount;
164             lines[lineNumber].ref(lock, lineMetadata.objectCount);
165             page->ref(lock);
166         }
167
168         if (!allocator.canAllocate())
169             allocator.refill({ begin, objectCount });
170         else
171             rangeCache.push({ begin, objectCount });
172     }
173
174     BASSERT(allocator.canAllocate());
175     page->setHasFreeLines(lock, false);
176 }
177
178 SmallPage* Heap::allocateSmallPage(std::lock_guard<StaticMutex>& lock, size_t sizeClass)
179 {
180     if (!m_smallPagesWithFreeLines[sizeClass].isEmpty())
181         return m_smallPagesWithFreeLines[sizeClass].pop();
182
183     SmallPage* page = [this, &lock]() {
184         if (!m_smallPages.isEmpty())
185             return m_smallPages.pop();
186
187         m_isAllocatingPages = true;
188         SmallPage* page = m_vmHeap.allocateSmallPage(lock);
189         return page;
190     }();
191
192     page->setSizeClass(sizeClass);
193     return page;
194 }
195
196 void Heap::deallocateSmallLine(std::lock_guard<StaticMutex>& lock, SmallLine* line)
197 {
198     BASSERT(!line->refCount(lock));
199     SmallPage* page = SmallPage::get(line);
200     page->deref(lock);
201
202     if (!page->hasFreeLines(lock)) {
203         page->setHasFreeLines(lock, true);
204         m_smallPagesWithFreeLines[page->sizeClass()].push(page);
205
206         BASSERT(page->refCount(lock));
207         return;
208     }
209
210     if (page->refCount(lock))
211         return;
212
213     m_smallPagesWithFreeLines[page->sizeClass()].remove(page);
214     m_smallPages.push(page);
215     m_scavenger.run();
216 }
217
218 inline LargeObject& Heap::splitAndAllocate(LargeObject& largeObject, size_t size)
219 {
220     BASSERT(largeObject.isFree());
221
222     LargeObject nextLargeObject;
223
224     if (largeObject.size() - size > largeMin) {
225         std::pair<LargeObject, LargeObject> split = largeObject.split(size);
226         largeObject = split.first;
227         nextLargeObject = split.second;
228     }
229
230     largeObject.setFree(false);
231
232     if (nextLargeObject) {
233         BASSERT(!nextLargeObject.nextCanMerge());
234         m_largeObjects.insert(nextLargeObject);
235     }
236
237     return largeObject;
238 }
239
240 inline LargeObject& Heap::splitAndAllocate(LargeObject& largeObject, size_t alignment, size_t size)
241 {
242     LargeObject prevLargeObject;
243     LargeObject nextLargeObject;
244
245     size_t alignmentMask = alignment - 1;
246     if (test(largeObject.begin(), alignmentMask)) {
247         size_t prefixSize = roundUpToMultipleOf(alignment, largeObject.begin() + largeMin) - largeObject.begin();
248         std::pair<LargeObject, LargeObject> pair = largeObject.split(prefixSize);
249         prevLargeObject = pair.first;
250         largeObject = pair.second;
251     }
252
253     BASSERT(largeObject.isFree());
254
255     if (largeObject.size() - size > largeMin) {
256         std::pair<LargeObject, LargeObject> split = largeObject.split(size);
257         largeObject = split.first;
258         nextLargeObject = split.second;
259     }
260
261     largeObject.setFree(false);
262
263     if (prevLargeObject) {
264         LargeObject merged = prevLargeObject.merge();
265         m_largeObjects.insert(merged);
266     }
267
268     if (nextLargeObject) {
269         LargeObject merged = nextLargeObject.merge();
270         m_largeObjects.insert(merged);
271     }
272
273     return largeObject;
274 }
275
276 void* Heap::allocateLarge(std::lock_guard<StaticMutex>& lock, size_t size)
277 {
278     BASSERT(size <= largeMax);
279     BASSERT(size >= largeMin);
280     BASSERT(size == roundUpToMultipleOf<largeAlignment>(size));
281
282     LargeObject largeObject = m_largeObjects.take(size);
283     if (!largeObject)
284         largeObject = m_vmHeap.allocateLargeObject(lock, size);
285
286     if (largeObject.vmState().hasVirtual()) {
287         m_isAllocatingPages = true;
288         // We commit before we split in order to avoid split/merge commit/decommit churn.
289         vmAllocatePhysicalPagesSloppy(largeObject.begin(), largeObject.size());
290         largeObject.setVMState(VMState::Physical);
291     }
292
293     largeObject = splitAndAllocate(largeObject, size);
294
295     return largeObject.begin();
296 }
297
298 void* Heap::allocateLarge(std::lock_guard<StaticMutex>& lock, size_t alignment, size_t size, size_t unalignedSize)
299 {
300     BASSERT(size <= largeMax);
301     BASSERT(size >= largeMin);
302     BASSERT(size == roundUpToMultipleOf<largeAlignment>(size));
303     BASSERT(unalignedSize <= largeMax);
304     BASSERT(unalignedSize >= largeMin);
305     BASSERT(unalignedSize == roundUpToMultipleOf<largeAlignment>(unalignedSize));
306     BASSERT(alignment <= largeChunkSize / 2);
307     BASSERT(alignment >= largeAlignment);
308     BASSERT(isPowerOfTwo(alignment));
309
310     LargeObject largeObject = m_largeObjects.take(alignment, size, unalignedSize);
311     if (!largeObject)
312         largeObject = m_vmHeap.allocateLargeObject(lock, alignment, size, unalignedSize);
313
314     if (largeObject.vmState().hasVirtual()) {
315         m_isAllocatingPages = true;
316         // We commit before we split in order to avoid split/merge commit/decommit churn.
317         vmAllocatePhysicalPagesSloppy(largeObject.begin(), largeObject.size());
318         largeObject.setVMState(VMState::Physical);
319     }
320
321     largeObject = splitAndAllocate(largeObject, alignment, size);
322
323     return largeObject.begin();
324 }
325
326 void Heap::deallocateLarge(std::lock_guard<StaticMutex>&, const LargeObject& largeObject)
327 {
328     BASSERT(!largeObject.isFree());
329     largeObject.setFree(true);
330     
331     LargeObject merged = largeObject.merge();
332     m_largeObjects.insert(merged);
333     m_scavenger.run();
334 }
335
336 void Heap::deallocateLarge(std::lock_guard<StaticMutex>& lock, void* object)
337 {
338     LargeObject largeObject(object);
339     deallocateLarge(lock, largeObject);
340 }
341
342 void* Heap::allocateXLarge(std::lock_guard<StaticMutex>& lock, size_t alignment, size_t size)
343 {
344     void* result = tryAllocateXLarge(lock, alignment, size);
345     RELEASE_BASSERT(result);
346     return result;
347 }
348
349 void* Heap::allocateXLarge(std::lock_guard<StaticMutex>& lock, size_t size)
350 {
351     return allocateXLarge(lock, alignment, size);
352 }
353
354 XLargeRange Heap::splitAndAllocate(XLargeRange& range, size_t alignment, size_t size)
355 {
356     XLargeRange prev;
357     XLargeRange next;
358
359     size_t alignmentMask = alignment - 1;
360     if (test(range.begin(), alignmentMask)) {
361         size_t prefixSize = roundUpToMultipleOf(alignment, range.begin()) - range.begin();
362         std::pair<XLargeRange, XLargeRange> pair = range.split(prefixSize);
363         prev = pair.first;
364         range = pair.second;
365     }
366
367     if (range.size() - size >= xLargeAlignment) {
368         size_t alignedSize = roundUpToMultipleOf<xLargeAlignment>(size);
369         std::pair<XLargeRange, XLargeRange> pair = range.split(alignedSize);
370         range = pair.first;
371         next = pair.second;
372     }
373
374     // At this point our range might contain an unused tail fragment. This is
375     // common. We can't allocate the tail fragment because it's aligned to less
376     // than xLargeAlignment. So, we pair the allocation with its tail fragment
377     // in the allocated list. This is an important optimization because it
378     // keeps the free list short, speeding up allocation and merging.
379
380     std::pair<XLargeRange, XLargeRange> allocated = range.split(roundUpToMultipleOf<vmPageSize>(size));
381     if (allocated.first.vmState().hasVirtual()) {
382         vmAllocatePhysicalPagesSloppy(allocated.first.begin(), allocated.first.size());
383         allocated.first.setVMState(VMState::Physical);
384     }
385
386     m_xLargeMap.addAllocated(prev, allocated, next);
387     return allocated.first;
388 }
389
390 void* Heap::tryAllocateXLarge(std::lock_guard<StaticMutex>&, size_t alignment, size_t size)
391 {
392     BASSERT(isPowerOfTwo(alignment));
393     BASSERT(alignment < xLargeMax);
394
395     m_isAllocatingPages = true;
396
397     alignment = roundUpToMultipleOf<xLargeAlignment>(alignment);
398
399     XLargeRange range = m_xLargeMap.takeFree(alignment, size);
400     if (!range) {
401         // We allocate VM in aligned multiples to increase the chances that
402         // the OS will provide contiguous ranges that we can merge.
403         size_t alignedSize = roundUpToMultipleOf<xLargeAlignment>(size);
404
405         void* begin = tryVMAllocate(alignment, alignedSize);
406         if (!begin)
407             return nullptr;
408         range = XLargeRange(begin, alignedSize, VMState::Virtual);
409     }
410
411     return splitAndAllocate(range, alignment, size).begin();
412 }
413
414 size_t Heap::xLargeSize(std::unique_lock<StaticMutex>&, void* object)
415 {
416     return m_xLargeMap.getAllocated(object).size();
417 }
418
419 void Heap::shrinkXLarge(std::unique_lock<StaticMutex>&, const Range& object, size_t newSize)
420 {
421     BASSERT(object.size() > newSize);
422
423     if (object.size() - newSize < vmPageSize)
424         return;
425     
426     XLargeRange range = m_xLargeMap.takeAllocated(object.begin());
427     splitAndAllocate(range, xLargeAlignment, newSize);
428
429     m_scavenger.run();
430 }
431
432 void Heap::deallocateXLarge(std::unique_lock<StaticMutex>&, void* object)
433 {
434     XLargeRange range = m_xLargeMap.takeAllocated(object);
435     m_xLargeMap.addFree(range);
436     
437     m_scavenger.run();
438 }
439
440 } // namespace bmalloc