xref: /aosp_15_r20/external/mesa3d/src/gfxstream/aemu/include/BumpPool.h (revision 6104692788411f58d303aa86923a9ff6ecaded22)
1 /*
2  * Copyright 2019 Google
3  * SPDX-License-Identifier: MIT
4  */
5 #pragma once
6 
7 #include <inttypes.h>
8 
9 #include <unordered_set>
10 #include <vector>
11 
12 #include "AlignedBuf.h"
13 #include "Allocator.h"
14 
15 namespace gfxstream {
16 namespace aemu {
17 
18 // Class to make it easier to set up memory regions where it is fast
19 // to allocate buffers AND we don't care about freeing individual pieces,
20 // BUT it's necessary to preserve previous pointer values in between the first
21 // alloc() after a freeAll(), and the freeAll() itself, allowing some sloppy use of
22 // malloc in the first pass while we find out how much data was needed.
23 class BumpPool : public Allocator {
24    public:
25     BumpPool(size_t startingBytes = 4096) : mStorage(startingBytes / sizeof(uint64_t)) {}
26     // All memory allocated by this pool
27     // is automatically deleted when the pool
28     // is deconstructed.
~BumpPool()29     ~BumpPool() { freeAll(); }
30 
alloc(size_t wantedSize)31     void* alloc(size_t wantedSize) override {
32         size_t wantedSizeRoundedUp =
33             sizeof(uint64_t) * ((wantedSize + sizeof(uint64_t) - 1) / (sizeof(uint64_t)));
34 
35         mTotalWantedThisGeneration += wantedSizeRoundedUp;
36         if (mAllocPos + wantedSizeRoundedUp > mStorage.size() * sizeof(uint64_t)) {
37             mNeedRealloc = true;
38             void* fallbackPtr = malloc(wantedSizeRoundedUp);
39             mFallbackPtrs.insert(fallbackPtr);
40             return fallbackPtr;
41         }
42         void* allocPtr = (void*)(((unsigned char*)mStorage.data()) + mAllocPos);
43         mAllocPos += wantedSizeRoundedUp;
44         return allocPtr;
45     }
46 
freeAll()47     void freeAll() {
48         mAllocPos = 0;
49         if (mNeedRealloc) {
50             mStorage.resize((mTotalWantedThisGeneration * 2) / sizeof(uint64_t));
51             mNeedRealloc = false;
52             for (auto ptr : mFallbackPtrs) {
53                 free(ptr);
54             }
55             mFallbackPtrs.clear();
56         }
57         mTotalWantedThisGeneration = 0;
58     }
59 
60    private:
61     AlignedBuf<uint64_t, 8> mStorage;
62     std::unordered_set<void*> mFallbackPtrs;
63     size_t mAllocPos = 0;
64     size_t mTotalWantedThisGeneration = 0;
65     bool mNeedRealloc = false;
66 };
67 
68 }  // namespace aemu
69 }  // namespace gfxstream
70