1/*
2 * Copyright 2020 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#ifndef GrBlockAllocator_DEFINED
9#define GrBlockAllocator_DEFINED
10
11#include "include/private/GrTypesPriv.h"
12#include "include/private/SkNoncopyable.h"
13
14#include <memory> // std::unique_ptr
15#include <cstddef> // max_align_t
16
17/**
18 * GrBlockAllocator provides low-level support for a block allocated arena with a dynamic tail that
19 * tracks space reservations within each block. Its APIs provide the ability to reserve space,
20 * resize reservations, and release reservations. It will automatically create new blocks if needed
21 * and destroy all remaining blocks when it is destructed. It assumes that anything allocated within
22 * its blocks has its destructors called externally. It is recommended that GrBlockAllocator is
23 * wrapped by a higher-level allocator that uses the low-level APIs to implement a simpler,
24 * purpose-focused API w/o having to worry as much about byte-level concerns.
25 *
26 * GrBlockAllocator has no limit to its total size, but each allocation is limited to 512MB (which
27 * should be sufficient for Ganesh's use cases). This upper allocation limit allows all internal
28 * operations to be performed using 'int' and avoid many overflow checks. Static asserts are used
29 * to ensure that those operations would not overflow when using the largest possible values.
30 *
31 * Possible use modes:
32 * 1. No upfront allocation, either on the stack or as a field
33 * GrBlockAllocator allocator(policy, heapAllocSize);
34 *
35 * 2. In-place new'd
36 * void* mem = operator new(totalSize);
37 * GrBlockAllocator* allocator = new (mem) GrBlockAllocator(policy, heapAllocSize,
38 * totalSize- sizeof(GrBlockAllocator));
39 * delete allocator;
40 *
41 * 3. Use GrSBlockAllocator to increase the preallocation size
42 * GrSBlockAllocator<1024> allocator(policy, heapAllocSize);
43 * sizeof(allocator) == 1024;
44 */
45class GrBlockAllocator final : SkNoncopyable {
46public:
47 // Largest size that can be requested from allocate(), chosen because it's the largest pow-2
48 // that is less than int32_t::max()/2.
49 static constexpr int kMaxAllocationSize = 1 << 29;
50
51 enum class GrowthPolicy : int {
52 kFixed, // Next block size = N
53 kLinear, // = #blocks * N
54 kFibonacci, // = fibonacci(#blocks) * N
55 kExponential, // = 2^#blocks * N
56 kLast = kExponential
57 };
58 static constexpr int kGrowthPolicyCount = static_cast<int>(GrowthPolicy::kLast) + 1;
59
60 class Block;
61
62 // Tuple representing a range of bytes, marking the unaligned start, the first aligned point
63 // after any padding, and the upper limit depending on requested size.
64 struct ByteRange {
65 Block* fBlock; // Owning block
66 int fStart; // Inclusive byte lower limit of byte range
67 int fAlignedOffset; // >= start, matching alignment requirement (i.e. first real byte)
68 int fEnd; // Exclusive upper limit of byte range
69 };
70
71 class Block final {
72 public:
73 ~Block();
74 void operator delete(void* p) { ::operator delete(p); }
75
76 // Return the maximum allocation size with the given alignment that can fit in this block.
77 template <size_t Align = 1, size_t Padding = 0>
78 int avail() const { return std::max(0, fSize - this->cursor<Align, Padding>()); }
79
80 // Return the aligned offset of the first allocation, assuming it was made with the
81 // specified Align, and Padding. The returned offset does not mean a valid allocation
82 // starts at that offset, this is a utility function for classes built on top to manage
83 // indexing into a block effectively.
84 template <size_t Align = 1, size_t Padding = 0>
85 int firstAlignedOffset() const { return this->alignedOffset<Align, Padding>(kDataStart); }
86
87 // Convert an offset into this block's storage into a usable pointer.
88 void* ptr(int offset) {
89 SkASSERT(offset >= kDataStart && offset < fSize);
90 return reinterpret_cast<char*>(this) + offset;
91 }
92 const void* ptr(int offset) const { return const_cast<Block*>(this)->ptr(offset); }
93
94 // Every block has an extra 'int' for clients to use however they want. It will start
95 // at 0 when a new block is made, or when the head block is reset.
96 int metadata() const { return fMetadata; }
97 void setMetadata(int value) { fMetadata = value; }
98
99 /**
100 * Release the byte range between offset 'start' (inclusive) and 'end' (exclusive). This
101 * will return true if those bytes were successfully reclaimed, i.e. a subsequent allocation
102 * request could occupy the space. Regardless of return value, the provided byte range that
103 * [start, end) represents should not be used until it's re-allocated with allocate<...>().
104 */
105 inline bool release(int start, int end);
106
107 /**
108 * Resize a previously reserved byte range of offset 'start' (inclusive) to 'end'
109 * (exclusive). 'deltaBytes' is the SIGNED change to length of the reservation.
110 *
111 * When negative this means the reservation is shrunk and the new length is (end - start -
112 * |deltaBytes|). If this new length would be 0, the byte range can no longer be used (as if
113 * it were released instead). Asserts that it would not shrink the reservation below 0.
114 *
115 * If 'deltaBytes' is positive, the allocator attempts to increase the length of the
116 * reservation. If 'deltaBytes' is less than or equal to avail() and it was the last
117 * allocation in the block, it can be resized. If there is not enough available bytes to
118 * accommodate the increase in size, or another allocation is blocking the increase in size,
119 * then false will be returned and the reserved byte range is unmodified.
120 */
121 inline bool resize(int start, int end, int deltaBytes);
122
123 private:
124 friend class GrBlockAllocator;
125
126 Block(Block* prev, int allocationSize);
127
128 // Get fCursor, but aligned such that ptr(rval) satisfies Align.
129 template <size_t Align, size_t Padding>
130 int cursor() const { return this->alignedOffset<Align, Padding>(fCursor); }
131
132 template <size_t Align, size_t Padding>
133 int alignedOffset(int offset) const;
134
135 bool isScratch() const { return fCursor < 0; }
136 void markAsScratch() { fCursor = -1; }
137
138 SkDEBUGCODE(int fSentinel;) // known value to check for bad back pointers to blocks
139
140 Block* fNext; // doubly-linked list of blocks
141 Block* fPrev;
142
143 // Each block tracks its own cursor because as later blocks are released, an older block
144 // may become the active tail again.
145 int fSize; // includes the size of the BlockHeader and requested metadata
146 int fCursor; // (this + fCursor) points to next available allocation
147 int fMetadata;
148
149 // On release builds, a Block's other 2 pointers and 3 int fields leaves 4 bytes of padding
150 // for 8 and 16 aligned systems. Currently this is only manipulated in the head block for
151 // an allocator-level metadata and is explicitly not reset when the head block is "released"
152 // Down the road we could instead choose to offer multiple metadata slots per block.
153 int fAllocatorMetadata;
154 };
155
156 // The size of the head block is determined by 'additionalPreallocBytes'. Subsequent heap blocks
157 // are determined by 'policy' and 'blockIncrementBytes', although 'blockIncrementBytes' will be
158 // aligned to std::max_align_t.
159 //
160 // When 'additionalPreallocBytes' > 0, the allocator assumes that many extra bytes immediately
161 // after the allocator can be used by its inline head block. This is useful when the allocator
162 // is in-place new'ed into a larger block of memory, but it should remain set to 0 if stack
163 // allocated or if the class layout does not guarantee that space is present.
164 GrBlockAllocator(GrowthPolicy policy, size_t blockIncrementBytes,
165 size_t additionalPreallocBytes = 0);
166
167 ~GrBlockAllocator() { this->reset(); }
168 void operator delete(void* p) { ::operator delete(p); }
169
170 /**
171 * Helper to calculate the minimum number of bytes needed for heap block size, under the
172 * assumption that Align will be the requested alignment of the first call to allocate().
173 * Ex. To store N instances of T in a heap block, the 'blockIncrementBytes' should be set to
174 * BlockOverhead<alignof(T)>() + N * sizeof(T) when making the GrBlockAllocator.
175 */
176 template<size_t Align = 1, size_t Padding = 0>
177 static constexpr size_t BlockOverhead();
178
179 /**
180 * Helper to calculate the minimum number of bytes needed for a preallocation, under the
181 * assumption that Align will be the requested alignment of the first call to allocate().
182 * Ex. To preallocate a GrSBlockAllocator to hold N instances of T, its arge should be
183 * Overhead<alignof(T)>() + N * sizeof(T)
184 */
185 template<size_t Align = 1, size_t Padding = 0>
186 static constexpr size_t Overhead();
187
188 /**
189 * Return the total number of bytes of the allocator, including its instance overhead, per-block
190 * overhead and space used for allocations.
191 */
192 size_t totalSize() const;
193 /**
194 * Return the total number of bytes usable for allocations. This includes bytes that have
195 * been reserved already by a call to allocate() and bytes that are still available. It is
196 * totalSize() minus all allocator and block-level overhead.
197 */
198 size_t totalUsableSpace() const;
199 /**
200 * Return the total number of usable bytes that have been reserved by allocations. This will
201 * be less than or equal to totalUsableSpace().
202 */
203 size_t totalSpaceInUse() const;
204
205 /**
206 * Return the total number of bytes that were pre-allocated for the GrBlockAllocator. This will
207 * include 'additionalPreallocBytes' passed to the constructor, and represents what the total
208 * size would become after a call to reset().
209 */
210 size_t preallocSize() const {
211 // Don't double count fHead's Block overhead in both sizeof(GrBlockAllocator) and fSize.
212 return sizeof(GrBlockAllocator) + fHead.fSize - BaseHeadBlockSize();
213 }
214 /**
215 * Return the usable size of the inline head block; this will be equal to
216 * 'additionalPreallocBytes' plus any alignment padding that the system had to add to Block.
217 * The returned value represents what could be allocated before a heap block is be created.
218 */
219 size_t preallocUsableSpace() const {
220 return fHead.fSize - kDataStart;
221 }
222
223 /**
224 * Get the current value of the allocator-level metadata (a user-oriented slot). This is
225 * separate from any block-level metadata, but can serve a similar purpose to compactly support
226 * data collections on top of GrBlockAllocator.
227 */
228 int metadata() const { return fHead.fAllocatorMetadata; }
229
230 /**
231 * Set the current value of the allocator-level metadata.
232 */
233 void setMetadata(int value) { fHead.fAllocatorMetadata = value; }
234
235 /**
236 * Reserve space that will hold 'size' bytes. This will automatically allocate a new block if
237 * there is not enough available space in the current block to provide 'size' bytes. The
238 * returned ByteRange tuple specifies the Block owning the reserved memory, the full byte range,
239 * and the aligned offset within that range to use for the user-facing pointer. The following
240 * invariants hold:
241 *
242 * 1. block->ptr(alignedOffset) is aligned to Align
243 * 2. end - alignedOffset == size
244 * 3. Padding <= alignedOffset - start <= Padding + Align - 1
245 *
246 * Invariant #3, when Padding > 0, allows intermediate allocators to embed metadata along with
247 * the allocations. If the Padding bytes are used for some 'struct Meta', then
248 * ptr(alignedOffset - sizeof(Meta)) can be safely used as a Meta* if Meta's alignment
249 * requirements are less than or equal to the alignment specified in allocate<>. This can be
250 * easily guaranteed by using the pattern:
251 *
252 * allocate<max(UserAlign, alignof(Meta)), sizeof(Meta)>(userSize);
253 *
254 * This ensures that ptr(alignedOffset) will always satisfy UserAlign and
255 * ptr(alignedOffset - sizeof(Meta)) will always satisfy alignof(Meta). Alternatively, memcpy
256 * can be used to read and write values between start and alignedOffset without worrying about
257 * alignment requirements of the metadata.
258 *
259 * For over-aligned allocations, the alignedOffset (as an int) may not be a multiple of Align,
260 * but the result of ptr(alignedOffset) will be a multiple of Align.
261 */
262 template <size_t Align, size_t Padding = 0>
263 ByteRange allocate(size_t size);
264
265 enum ReserveFlags : unsigned {
266 // If provided to reserve(), the input 'size' will be rounded up to the next size determined
267 // by the growth policy of the GrBlockAllocator. If not, 'size' will be aligned to max_align
268 kIgnoreGrowthPolicy_Flag = 0b01,
269 // If provided to reserve(), the number of available bytes of the current block will not
270 // be used to satisfy the reservation (assuming the contiguous range was long enough to
271 // begin with).
272 kIgnoreExistingBytes_Flag = 0b10,
273
274 kNo_ReserveFlags = 0b00
275 };
276
277 /**
278 * Ensure the block allocator has 'size' contiguous available bytes. After calling this
279 * function, currentBlock()->avail<Align, Padding>() may still report less than 'size' if the
280 * reserved space was added as a scratch block. This is done so that anything remaining in
281 * the current block can still be used if a smaller-than-size allocation is requested. If 'size'
282 * is requested by a subsequent allocation, the scratch block will automatically be activated
283 * and the request will not itself trigger any malloc.
284 *
285 * The optional 'flags' controls how the input size is allocated; by default it will attempt
286 * to use available contiguous bytes in the current block and will respect the growth policy
287 * of the allocator.
288 */
289 template <size_t Align = 1, size_t Padding = 0>
290 void reserve(size_t size, ReserveFlags flags = kNo_ReserveFlags);
291
292 /**
293 * Return a pointer to the start of the current block. This will never be null.
294 */
295 const Block* currentBlock() const { return fTail; }
296 Block* currentBlock() { return fTail; }
297
298 const Block* headBlock() const { return &fHead; }
299 Block* headBlock() { return &fHead; }
300
301 /**
302 * Return the block that owns the allocated 'ptr'. Assuming that earlier, an allocation was
303 * returned as {b, start, alignedOffset, end}, and 'p = b->ptr(alignedOffset)', then a call
304 * to 'owningBlock<Align, Padding>(p, start) == b'.
305 *
306 * If calling code has already made a pointer to their metadata, i.e. 'm = p - Padding', then
307 * 'owningBlock<Align, 0>(m, start)' will also return b, allowing you to recover the block from
308 * the metadata pointer.
309 *
310 * If calling code has access to the original alignedOffset, this function should not be used
311 * since the owning block is just 'p - alignedOffset', regardless of original Align or Padding.
312 */
313 template <size_t Align, size_t Padding = 0>
314 Block* owningBlock(const void* ptr, int start);
315
316 template <size_t Align, size_t Padding = 0>
317 const Block* owningBlock(const void* ptr, int start) const {
318 return const_cast<GrBlockAllocator*>(this)->owningBlock<Align, Padding>(ptr, start);
319 }
320
321 /**
322 * Find the owning block of the allocated pointer, 'p'. Without any additional information this
323 * is O(N) on the number of allocated blocks.
324 */
325 Block* findOwningBlock(const void* ptr);
326 const Block* findOwningBlock(const void* ptr) const {
327 return const_cast<GrBlockAllocator*>(this)->findOwningBlock(ptr);
328 }
329
330 /**
331 * Explicitly free an entire block, invalidating any remaining allocations from the block.
332 * GrBlockAllocator will release all alive blocks automatically when it is destroyed, but this
333 * function can be used to reclaim memory over the lifetime of the allocator. The provided
334 * 'block' pointer must have previously come from a call to currentBlock() or allocate().
335 *
336 * If 'block' represents the inline-allocated head block, its cursor and metadata are instead
337 * reset to their defaults.
338 *
339 * If the block is not the head block, it may be kept as a scratch block to be reused for
340 * subsequent allocation requests, instead of making an entirely new block. A scratch block is
341 * not visible when iterating over blocks but is reported in the total size of the allocator.
342 */
343 void releaseBlock(Block* block);
344
345 /**
346 * Detach every heap-allocated block owned by 'other' and concatenate them to this allocator's
347 * list of blocks. This memory is now managed by this allocator. Since this only transfers
348 * ownership of a Block, and a Block itself does not move, any previous allocations remain
349 * valid and associated with their original Block instances. GrBlockAllocator-level functions
350 * that accept allocated pointers (e.g. findOwningBlock), must now use this allocator and not
351 * 'other' for these allocations.
352 *
353 * The head block of 'other' cannot be stolen, so higher-level allocators and memory structures
354 * must handle that data differently.
355 */
356 void stealHeapBlocks(GrBlockAllocator* other);
357
358 /**
359 * Explicitly free all blocks (invalidating all allocations), and resets the head block to its
360 * default state. The allocator-level metadata is reset to 0 as well.
361 */
362 void reset();
363
364 /**
365 * Remove any reserved scratch space, either from calling reserve() or releaseBlock().
366 */
367 void resetScratchSpace();
368
369 template <bool Forward, bool Const> class BlockIter;
370
371 /**
372 * Clients can iterate over all active Blocks in the GrBlockAllocator using for loops:
373 *
374 * Forward iteration from head to tail block (or non-const variant):
375 * for (const Block* b : this->blocks()) { }
376 * Reverse iteration from tail to head block:
377 * for (const Block* b : this->rblocks()) { }
378 *
379 * It is safe to call releaseBlock() on the active block while looping.
380 */
381 inline BlockIter<true, false> blocks();
382 inline BlockIter<true, true> blocks() const;
383 inline BlockIter<false, false> rblocks();
384 inline BlockIter<false, true> rblocks() const;
385
386#ifdef SK_DEBUG
387 static constexpr int kAssignedMarker = 0xBEEFFACE;
388 static constexpr int kFreedMarker = 0xCAFEBABE;
389
390 void validate() const;
391#endif
392
393#if GR_TEST_UTILS
394 int testingOnly_scratchBlockSize() const { return this->scratchBlockSize(); }
395#endif
396
397private:
398 static constexpr int kDataStart = sizeof(Block);
399 #ifdef SK_FORCE_8_BYTE_ALIGNMENT
400 // This is an issue for WASM builds using emscripten, which had std::max_align_t = 16, but
401 // was returning pointers only aligned to 8 bytes.
402 // https://github.com/emscripten-core/emscripten/issues/10072
403 //
404 // Setting this to 8 will let GrBlockAllocator properly correct for the pointer address if
405 // a 16-byte aligned allocation is requested in wasm (unlikely since we don't use long
406 // doubles).
407 static constexpr size_t kAddressAlign = 8;
408 #else
409 // The alignment Block addresses will be at when created using operator new
410 // (spec-compliant is pointers are aligned to max_align_t).
411 static constexpr size_t kAddressAlign = alignof(std::max_align_t);
412 #endif
413
414 // Calculates the size of a new Block required to store a kMaxAllocationSize request for the
415 // given alignment and padding bytes. Also represents maximum valid fCursor value in a Block.
416 template<size_t Align, size_t Padding>
417 static constexpr size_t MaxBlockSize();
418
419 static constexpr int BaseHeadBlockSize() {
420 return sizeof(GrBlockAllocator) - offsetof(GrBlockAllocator, fHead);
421 }
422
423 // Append a new block to the end of the block linked list, updating fTail. 'minSize' must
424 // have enough room for sizeof(Block). 'maxSize' is the upper limit of fSize for the new block
425 // that will preserve the static guarantees GrBlockAllocator makes.
426 void addBlock(int minSize, int maxSize);
427
428 int scratchBlockSize() const { return fHead.fPrev ? fHead.fPrev->fSize : 0; }
429
430 Block* fTail; // All non-head blocks are heap allocated; tail will never be null.
431
432 // All remaining state is packed into 64 bits to keep GrBlockAllocator at 16 bytes + head block
433 // (on a 64-bit system).
434
435 // Growth of the block size is controlled by four factors: BlockIncrement, N0 and N1, and a
436 // policy defining how N0 is updated. When a new block is needed, we calculate N1' = N0 + N1.
437 // Depending on the policy, N0' = N0 (no growth or linear growth), or N0' = N1 (Fibonacci), or
438 // N0' = N1' (exponential). The size of the new block is N1' * BlockIncrement * MaxAlign,
439 // after which fN0 and fN1 store N0' and N1' clamped into 23 bits. With current bit allocations,
440 // N1' is limited to 2^24, and assuming MaxAlign=16, then BlockIncrement must be '2' in order to
441 // eventually reach the hard 2^29 size limit of GrBlockAllocator.
442
443 // Next heap block size = (fBlockIncrement * alignof(std::max_align_t) * (fN0 + fN1))
444 uint64_t fBlockIncrement : 16;
445 uint64_t fGrowthPolicy : 2; // GrowthPolicy
446 uint64_t fN0 : 23; // = 1 for linear/exp.; = 0 for fixed/fibonacci, initially
447 uint64_t fN1 : 23; // = 1 initially
448
449 // Inline head block, must be at the end so that it can utilize any additional reserved space
450 // from the initial allocation.
451 // The head block's prev pointer may be non-null, which signifies a scratch block that may be
452 // reused instead of allocating an entirely new block (this helps when allocate+release calls
453 // bounce back and forth across the capacity of a block).
454 alignas(kAddressAlign) Block fHead;
455
456 static_assert(kGrowthPolicyCount <= 4);
457};
458
459// A wrapper around GrBlockAllocator that includes preallocated storage for the head block.
460// N will be the preallocSize() reported by the allocator.
461template<size_t N>
462class GrSBlockAllocator : SkNoncopyable {
463public:
464 using GrowthPolicy = GrBlockAllocator::GrowthPolicy;
465
466 GrSBlockAllocator() {
467 new (fStorage) GrBlockAllocator(GrowthPolicy::kFixed, N, N - sizeof(GrBlockAllocator));
468 }
469 explicit GrSBlockAllocator(GrowthPolicy policy) {
470 new (fStorage) GrBlockAllocator(policy, N, N - sizeof(GrBlockAllocator));
471 }
472
473 GrSBlockAllocator(GrowthPolicy policy, size_t blockIncrementBytes) {
474 new (fStorage) GrBlockAllocator(policy, blockIncrementBytes, N - sizeof(GrBlockAllocator));
475 }
476
477 ~GrSBlockAllocator() {
478 this->allocator()->~GrBlockAllocator();
479 }
480
481 GrBlockAllocator* operator->() { return this->allocator(); }
482 const GrBlockAllocator* operator->() const { return this->allocator(); }
483
484 GrBlockAllocator* allocator() { return reinterpret_cast<GrBlockAllocator*>(fStorage); }
485 const GrBlockAllocator* allocator() const {
486 return reinterpret_cast<const GrBlockAllocator*>(fStorage);
487 }
488
489private:
490 static_assert(N >= sizeof(GrBlockAllocator));
491
492 // Will be used to placement new the allocator
493 alignas(GrBlockAllocator) char fStorage[N];
494};
495
496///////////////////////////////////////////////////////////////////////////////////////////////////
497// Template and inline implementations
498
499GR_MAKE_BITFIELD_OPS(GrBlockAllocator::ReserveFlags)
500
501template<size_t Align, size_t Padding>
502constexpr size_t GrBlockAllocator::BlockOverhead() {
503 static_assert(GrAlignTo(kDataStart + Padding, Align) >= sizeof(Block));
504 return GrAlignTo(kDataStart + Padding, Align);
505}
506
507template<size_t Align, size_t Padding>
508constexpr size_t GrBlockAllocator::Overhead() {
509 // NOTE: On most platforms, GrBlockAllocator is packed; this is not the case on debug builds
510 // due to extra fields, or on WASM due to 4byte pointers but 16byte max align.
511 return std::max(sizeof(GrBlockAllocator),
512 offsetof(GrBlockAllocator, fHead) + BlockOverhead<Align, Padding>());
513}
514
515template<size_t Align, size_t Padding>
516constexpr size_t GrBlockAllocator::MaxBlockSize() {
517 // Without loss of generality, assumes 'align' will be the largest encountered alignment for the
518 // allocator (if it's not, the largest align will be encountered by the compiler and pass/fail
519 // the same set of static asserts).
520 return BlockOverhead<Align, Padding>() + kMaxAllocationSize;
521}
522
523template<size_t Align, size_t Padding>
524void GrBlockAllocator::reserve(size_t size, ReserveFlags flags) {
525 if (size > kMaxAllocationSize) {
526 SK_ABORT("Allocation too large (%zu bytes requested)", size);
527 }
528 int iSize = (int) size;
529 if ((flags & kIgnoreExistingBytes_Flag) ||
530 this->currentBlock()->avail<Align, Padding>() < iSize) {
531
532 int blockSize = BlockOverhead<Align, Padding>() + iSize;
533 int maxSize = (flags & kIgnoreGrowthPolicy_Flag) ? blockSize
534 : MaxBlockSize<Align, Padding>();
535 SkASSERT((size_t) maxSize <= (MaxBlockSize<Align, Padding>()));
536
537 SkDEBUGCODE(auto oldTail = fTail;)
538 this->addBlock(blockSize, maxSize);
539 SkASSERT(fTail != oldTail);
540 // Releasing the just added block will move it into scratch space, allowing the original
541 // tail's bytes to be used first before the scratch block is activated.
542 this->releaseBlock(fTail);
543 }
544}
545
546template <size_t Align, size_t Padding>
547GrBlockAllocator::ByteRange GrBlockAllocator::allocate(size_t size) {
548 // Amount of extra space for a new block to make sure the allocation can succeed.
549 static constexpr int kBlockOverhead = (int) BlockOverhead<Align, Padding>();
550
551 // Ensures 'offset' and 'end' calculations will be valid
552 static_assert((kMaxAllocationSize + GrAlignTo(MaxBlockSize<Align, Padding>(), Align))
553 <= (size_t) std::numeric_limits<int32_t>::max());
554 // Ensures size + blockOverhead + addBlock's alignment operations will be valid
555 static_assert(kMaxAllocationSize + kBlockOverhead + ((1 << 12) - 1) // 4K align for large blocks
556 <= std::numeric_limits<int32_t>::max());
557
558 if (size > kMaxAllocationSize) {
559 SK_ABORT("Allocation too large (%zu bytes requested)", size);
560 }
561
562 int iSize = (int) size;
563 int offset = fTail->cursor<Align, Padding>();
564 int end = offset + iSize;
565 if (end > fTail->fSize) {
566 this->addBlock(iSize + kBlockOverhead, MaxBlockSize<Align, Padding>());
567 offset = fTail->cursor<Align, Padding>();
568 end = offset + iSize;
569 }
570
571 // Check invariants
572 SkASSERT(end <= fTail->fSize);
573 SkASSERT(end - offset == iSize);
574 SkASSERT(offset - fTail->fCursor >= (int) Padding &&
575 offset - fTail->fCursor <= (int) (Padding + Align - 1));
576 SkASSERT(reinterpret_cast<uintptr_t>(fTail->ptr(offset)) % Align == 0);
577
578 int start = fTail->fCursor;
579 fTail->fCursor = end;
580 return {fTail, start, offset, end};
581}
582
583template <size_t Align, size_t Padding>
584GrBlockAllocator::Block* GrBlockAllocator::owningBlock(const void* p, int start) {
585 // 'p' was originally formed by aligning 'block + start + Padding', producing the inequality:
586 // block + start + Padding <= p <= block + start + Padding + Align-1
587 // Rearranging this yields:
588 // block <= p - start - Padding <= block + Align-1
589 // Masking these terms by ~(Align-1) reconstructs 'block' if the alignment of the block is
590 // greater than or equal to Align (since block & ~(Align-1) == (block + Align-1) & ~(Align-1)
591 // in that case). Overalignment does not reduce to inequality unfortunately.
592 if /* constexpr */ (Align <= kAddressAlign) {
593 Block* block = reinterpret_cast<Block*>(
594 (reinterpret_cast<uintptr_t>(p) - start - Padding) & ~(Align - 1));
595 SkASSERT(block->fSentinel == kAssignedMarker);
596 return block;
597 } else {
598 // There's not a constant-time expression available to reconstruct the block from 'p',
599 // but this is unlikely to happen frequently.
600 return this->findOwningBlock(p);
601 }
602}
603
604template <size_t Align, size_t Padding>
605int GrBlockAllocator::Block::alignedOffset(int offset) const {
606 static_assert(SkIsPow2(Align));
607 // Aligning adds (Padding + Align - 1) as an intermediate step, so ensure that can't overflow
608 static_assert(MaxBlockSize<Align, Padding>() + Padding + Align - 1
609 <= (size_t) std::numeric_limits<int32_t>::max());
610
611 if /* constexpr */ (Align <= kAddressAlign) {
612 // Same as GrAlignTo, but operates on ints instead of size_t
613 return (offset + Padding + Align - 1) & ~(Align - 1);
614 } else {
615 // Must take into account that 'this' may be starting at a pointer that doesn't satisfy the
616 // larger alignment request, so must align the entire pointer, not just offset
617 uintptr_t blockPtr = reinterpret_cast<uintptr_t>(this);
618 uintptr_t alignedPtr = (blockPtr + offset + Padding + Align - 1) & ~(Align - 1);
619 SkASSERT(alignedPtr - blockPtr <= (uintptr_t) std::numeric_limits<int32_t>::max());
620 return (int) (alignedPtr - blockPtr);
621 }
622}
623
624bool GrBlockAllocator::Block::resize(int start, int end, int deltaBytes) {
625 SkASSERT(fSentinel == kAssignedMarker);
626 SkASSERT(start >= kDataStart && end <= fSize && start < end);
627
628 if (deltaBytes > kMaxAllocationSize || deltaBytes < -kMaxAllocationSize) {
629 // Cannot possibly satisfy the resize and could overflow subsequent math
630 return false;
631 }
632 if (fCursor == end) {
633 int nextCursor = end + deltaBytes;
634 SkASSERT(nextCursor >= start);
635 // We still check nextCursor >= start for release builds that wouldn't assert.
636 if (nextCursor <= fSize && nextCursor >= start) {
637 fCursor = nextCursor;
638 return true;
639 }
640 }
641 return false;
642}
643
644// NOTE: release is equivalent to resize(start, end, start - end), and the compiler can optimize
645// most of the operations away, but it wasn't able to remove the unnecessary branch comparing the
646// new cursor to the block size or old start, so release() gets a specialization.
647bool GrBlockAllocator::Block::release(int start, int end) {
648 SkASSERT(fSentinel == kAssignedMarker);
649 SkASSERT(start >= kDataStart && end <= fSize && start < end);
650 if (fCursor == end) {
651 fCursor = start;
652 return true;
653 } else {
654 return false;
655 }
656}
657
658///////// Block iteration
659template <bool Forward, bool Const>
660class GrBlockAllocator::BlockIter {
661private:
662 using BlockT = typename std::conditional<Const, const Block, Block>::type;
663 using AllocatorT =
664 typename std::conditional<Const, const GrBlockAllocator, GrBlockAllocator>::type;
665
666public:
667 BlockIter(AllocatorT* allocator) : fAllocator(allocator) {}
668
669 class Item {
670 public:
671 bool operator!=(const Item& other) const { return fBlock != other.fBlock; }
672
673 BlockT* operator*() const { return fBlock; }
674
675 Item& operator++() {
676 this->advance(fNext);
677 return *this;
678 }
679
680 private:
681 friend BlockIter;
682
683 Item(BlockT* block) { this->advance(block); }
684
685 void advance(BlockT* block) {
686 fBlock = block;
687 fNext = block ? (Forward ? block->fNext : block->fPrev) : nullptr;
688 if (!Forward && fNext && fNext->isScratch()) {
689 // For reverse-iteration only, we need to stop at the head, not the scratch block
690 // possibly stashed in head->prev.
691 fNext = nullptr;
692 }
693 SkASSERT(!fNext || !fNext->isScratch());
694 }
695
696 BlockT* fBlock;
697 // Cache this before operator++ so that fBlock can be released during iteration
698 BlockT* fNext;
699 };
700
701 Item begin() const { return Item(Forward ? &fAllocator->fHead : fAllocator->fTail); }
702 Item end() const { return Item(nullptr); }
703
704private:
705 AllocatorT* fAllocator;
706};
707
708GrBlockAllocator::BlockIter<true, false> GrBlockAllocator::blocks() {
709 return BlockIter<true, false>(this);
710}
711GrBlockAllocator::BlockIter<true, true> GrBlockAllocator::blocks() const {
712 return BlockIter<true, true>(this);
713}
714GrBlockAllocator::BlockIter<false, false> GrBlockAllocator::rblocks() {
715 return BlockIter<false, false>(this);
716}
717GrBlockAllocator::BlockIter<false, true> GrBlockAllocator::rblocks() const {
718 return BlockIter<false, true>(this);
719}
720
721#endif // GrBlockAllocator_DEFINED
722