1 // Copyright 2018 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 #pragma once
15 
16 #include "aemu/base/Allocator.h"
17 
18 #include <unordered_set>
19 
20 #include <inttypes.h>
21 #include <stddef.h>
22 #include <string.h>
23 
24 namespace gfxstream {
25 namespace guest {
26 
27 // Class to make it easier to set up memory regions where it is fast
28 // to allocate/deallocate buffers that have size within
29 // the specified range.
30 class Pool : public Allocator {
31 public:
32     // minSize/maxSize: the target range of sizes for which we want to
33     // make allocations fast. the greater the range, the more space
34     // traded off.
35     // chunksPerSize: the target maximum number of live objects of
36     // each size that are expected. the higher it is, the more space
37     // traded off.
38     //
39     // Rough space cost formula:
40     // O(chunksPerSize * log2(maxSize / minSize) * maxSize)
41     Pool(size_t minSize = 4,
42          size_t maxSize = 4096,
43          size_t chunksPerSize = 1024);
44 
45     // All memory allocated by this pool
46     // is automatically deleted when the pool
47     // is deconstructed.
48     ~Pool();
49 
50     void* alloc(size_t wantedSize) override;
51     void free(void* ptr);
52 
53     // Convenience function to free everything currently allocated.
54     void freeAll();
55 
56 private:
57     class Impl;
58     Impl* mImpl = nullptr;
59 
60     std::unordered_set<void*> mFallbackPtrs;
61 };
62 
63 } // namespace base
64 } // namespace android
65