Debian Codegraph @

src/core/lib/resource_quota/arena.h

raw
1 /*
2 *
3 * Copyright 2017 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 // \file Arena based allocator
20 // Allows very fast allocation of memory, but that memory cannot be freed until
21 // the arena as a whole is freed
22 // Tracks the total memory allocated against it, so that future arenas can
23 // pre-allocate the right amount of memory
24
25 #ifndef GRPC_CORE_LIB_RESOURCE_QUOTA_ARENA_H
26 #define GRPC_CORE_LIB_RESOURCE_QUOTA_ARENA_H
27
28 #include <grpc/support/port_platform.h>
29
30 #include <stddef.h>
31
32 #include <atomic>
33 #include <memory>
34 #include <new>
35 #include <utility>
36
37 #include "absl/meta/type_traits.h"
38 #include "absl/utility/utility.h"
39
40 #include <grpc/event_engine/memory_allocator.h>
41
42 #include "src/core/lib/gpr/alloc.h"
43 #include "src/core/lib/gprpp/construct_destruct.h"
44 #include "src/core/lib/promise/context.h"
45 #include "src/core/lib/resource_quota/memory_quota.h"
46
47 namespace grpc_core {
48
49 namespace arena_detail {
50
51 template <typename Void, size_t kIndex, size_t kObjectSize,
52 size_t... kBucketSize>
53 struct PoolIndexForSize;
54
55 template <size_t kObjectSize, size_t kIndex, size_t kSmallestRemainingBucket,
56 size_t... kBucketSizes>
57 struct PoolIndexForSize<
58 absl::enable_if_t<kObjectSize <= kSmallestRemainingBucket>, kIndex,
59 kObjectSize, kSmallestRemainingBucket, kBucketSizes...> {
60 static constexpr size_t kPool = kIndex;
61 static constexpr size_t kSize = kSmallestRemainingBucket;
62 };
63
64 template <size_t kObjectSize, size_t kIndex, size_t kSmallestRemainingBucket,
65 size_t... kBucketSizes>
66 struct PoolIndexForSize<
67 absl::enable_if_t<(kObjectSize > kSmallestRemainingBucket)>, kIndex,
68 kObjectSize, kSmallestRemainingBucket, kBucketSizes...>
69 : public PoolIndexForSize<void, kIndex + 1, kObjectSize, kBucketSizes...> {
70 };
71
72 template <size_t kObjectSize, size_t... kBucketSizes>
73 constexpr size_t PoolFromObjectSize(
74 absl::integer_sequence<size_t, kBucketSizes...>) {
75 return PoolIndexForSize<void, 0, kObjectSize, kBucketSizes...>::kPool;
76 }
77
78 template <size_t kObjectSize, size_t... kBucketSizes>
79 constexpr size_t AllocationSizeFromObjectSize(
80 absl::integer_sequence<size_t, kBucketSizes...>) {
81 return PoolIndexForSize<void, 0, kObjectSize, kBucketSizes...>::kSize;
82 }
83
84 } // namespace arena_detail
85
86 class Arena {
87 using PoolSizes = absl::integer_sequence<size_t, 256, 512, 768>;
88
89 public:
90 // Create an arena, with \a initial_size bytes in the first allocated buffer.
91 static Arena* Create(size_t initial_size, MemoryAllocator* memory_allocator);
92
93 // Create an arena, with \a initial_size bytes in the first allocated buffer,
94 // and return both a void pointer to the returned arena and a void* with the
95 // first allocation.
96 static std::pair<Arena*, void*> CreateWithAlloc(
97 size_t initial_size, size_t alloc_size,
98 MemoryAllocator* memory_allocator);
99
100 // Destroy an arena, returning the total number of bytes allocated.
101 size_t Destroy();
102 // Allocate \a size bytes from the arena.
103 void* Alloc(size_t size) {
104 static constexpr size_t base_size =
105 GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(Arena));
106 size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(size);
107 size_t begin = total_used_.fetch_add(size, std::memory_order_relaxed);
108 if (begin + size <= initial_zone_size_) {
109 return reinterpret_cast<char*>(this) + base_size + begin;
110 } else {
111 return AllocZone(size);
112 }
113 }
114
115 // TODO(roth): We currently assume that all callers need alignment of 16
116 // bytes, which may be wrong in some cases. When we have time, we should
117 // change this to instead use the alignment of the type being allocated by
118 // this method.
119 template <typename T, typename... Args>
120 T* New(Args&&... args) {
121 T* t = static_cast<T*>(Alloc(sizeof(T)));
122 Construct(t, std::forward<Args>(args)...);
123 return t;
124 }
125
126 // Like New, but has the arena call p->~T() at arena destruction time.
127 template <typename T, typename... Args>
128 T* ManagedNew(Args&&... args) {
129 auto* p = New<ManagedNewImpl<T>>(std::forward<Args>(args)...);
130 p->Link(&managed_new_head_);
131 return &p->t;
132 }
133
134 class PooledDeleter {
135 public:
136 explicit PooledDeleter(Arena* arena) : arena_(arena) {}
137 PooledDeleter() = default;
138 template <typename T>
139 void operator()(T* p) {
140 // TODO(ctiller): promise based filter hijacks ownership of some pointers
141 // to make them appear as PoolPtr without really transferring ownership,
142 // by setting the arena to nullptr.
143 // This is a transitional hack and should be removed once promise based
144 // filter is removed.
145 if (arena_ != nullptr) arena_->DeletePooled(p);
146 }
147
148 private:
149 Arena* arena_;
150 };
151
152 template <typename T>
153 using PoolPtr = std::unique_ptr<T, PooledDeleter>;
154
155 template <typename T, typename... Args>
156 PoolPtr<T> MakePooled(Args&&... args) {
157 return PoolPtr<T>(
158 new (AllocPooled(
159 arena_detail::AllocationSizeFromObjectSize<sizeof(T)>(PoolSizes()),
160 &pools_[arena_detail::PoolFromObjectSize<sizeof(T)>(PoolSizes())]))
161 T(std::forward<Args>(args)...),
162 PooledDeleter(this));
163 }
164
165 private:
166 struct Zone {
167 Zone* prev;
168 };
169
170 struct ManagedNewObject {
171 ManagedNewObject* next = nullptr;
172 void Link(std::atomic<ManagedNewObject*>* head);
173 virtual ~ManagedNewObject() = default;
174 };
175
176 template <typename T>
177 struct ManagedNewImpl : public ManagedNewObject {
178 T t;
179 template <typename... Args>
180 explicit ManagedNewImpl(Args&&... args) : t(std::forward<Args>(args)...) {}
181 };
182
183 // Initialize an arena.
184 // Parameters:
185 // initial_size: The initial size of the whole arena in bytes. These bytes
186 // are contained within 'zone 0'. If the arena user ends up requiring more
187 // memory than the arena contains in zone 0, subsequent zones are allocated
188 // on demand and maintained in a tail-linked list.
189 //
190 // initial_alloc: Optionally, construct the arena as though a call to
191 // Alloc() had already been made for initial_alloc bytes. This provides a
192 // quick optimization (avoiding an atomic fetch-add) for the common case
193 // where we wish to create an arena and then perform an immediate
194 // allocation.
195 explicit Arena(size_t initial_size, size_t initial_alloc,
196 MemoryAllocator* memory_allocator)
197 : total_used_(GPR_ROUND_UP_TO_ALIGNMENT_SIZE(initial_alloc)),
198 initial_zone_size_(initial_size),
199 memory_allocator_(memory_allocator) {}
200
201 ~Arena();
202
203 void* AllocZone(size_t size);
204
205 template <typename T>
206 void DeletePooled(T* p) {
207 p->~T();
208 FreePooled(
209 p, &pools_[arena_detail::PoolFromObjectSize<sizeof(T)>(PoolSizes())]);
210 }
211
212 struct FreePoolNode {
213 FreePoolNode* next;
214 };
215
216 void* AllocPooled(size_t alloc_size, std::atomic<FreePoolNode*>* head);
217 static void FreePooled(void* p, std::atomic<FreePoolNode*>* head);
218
219 // Keep track of the total used size. We use this in our call sizing
220 // hysteresis.
221 std::atomic<size_t> total_used_{0};
222 std::atomic<size_t> total_allocated_{0};
223 const size_t initial_zone_size_;
224 // If the initial arena allocation wasn't enough, we allocate additional zones
225 // in a reverse linked list. Each additional zone consists of (1) a pointer to
226 // the zone added before this zone (null if this is the first additional zone)
227 // and (2) the allocated memory. The arena itself maintains a pointer to the
228 // last zone; the zone list is reverse-walked during arena destruction only.
229 std::atomic<Zone*> last_zone_{nullptr};
230 std::atomic<ManagedNewObject*> managed_new_head_{nullptr};
231 std::atomic<FreePoolNode*> pools_[PoolSizes::size()]{};
232 // The backing memory quota
233 MemoryAllocator* const memory_allocator_;
234 };
235
236 // Smart pointer for arenas when the final size is not required.
237 struct ScopedArenaDeleter {
238 void operator()(Arena* arena) { arena->Destroy(); }
239 };
240 using ScopedArenaPtr = std::unique_ptr<Arena, ScopedArenaDeleter>;
241 inline ScopedArenaPtr MakeScopedArena(size_t initial_size,
242 MemoryAllocator* memory_allocator) {
243 return ScopedArenaPtr(Arena::Create(initial_size, memory_allocator));
244 }
245
246 // Arenas form a context for activities
247 template <>
248 struct ContextType<Arena> {};
249
250 } // namespace grpc_core
251
252 #endif /* GRPC_CORE_LIB_RESOURCE_QUOTA_ARENA_H */