-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathPool.h
430 lines (376 loc) · 13 KB
/
Pool.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
* Copyright (c) 2020 Project CHIP Authors
* Copyright (c) 2013 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Defines memory pool classes.
*/
#pragma once
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <system/SystemConfig.h>
#include <lib/support/Iterators.h>
#include <atomic>
#include <limits>
#include <new>
#include <stddef.h>
#include <utility>
namespace chip {
namespace internal {
class Statistics
{
public:
Statistics() : mAllocated(0), mHighWaterMark(0) {}
size_t Allocated() const { return mAllocated; }
size_t HighWaterMark() const { return mHighWaterMark; }
void IncreaseUsage()
{
if (++mAllocated > mHighWaterMark)
{
mHighWaterMark = mAllocated;
}
}
void DecreaseUsage() { --mAllocated; }
protected:
size_t mAllocated;
size_t mHighWaterMark;
};
class StaticAllocatorBase : public Statistics
{
public:
StaticAllocatorBase(size_t capacity) : mCapacity(capacity) {}
size_t Capacity() const { return mCapacity; }
bool Exhausted() const { return mAllocated == mCapacity; }
protected:
const size_t mCapacity;
};
class StaticAllocatorBitmap : public internal::StaticAllocatorBase
{
protected:
/**
* Use the largest data type supported by `std::atomic`. Putting multiple atomic inside a single cache line won't improve
* concurrency, while the use of larger data type can improve the performance by reducing the number of outer loop iterations.
*/
using tBitChunkType = unsigned long;
static constexpr const tBitChunkType kBit1 = 1; // make sure bitshifts produce the right type
static constexpr const size_t kBitChunkSize = std::numeric_limits<tBitChunkType>::digits;
static_assert(ATOMIC_LONG_LOCK_FREE, "StaticAllocatorBitmap is not lock free");
public:
StaticAllocatorBitmap(void * storage, std::atomic<tBitChunkType> * usage, size_t capacity, size_t elementSize);
protected:
void * Allocate();
void Deallocate(void * element);
void * At(size_t index) { return static_cast<uint8_t *>(mElements) + mElementSize * index; }
size_t IndexOf(void * element);
using Lambda = Loop (*)(void * context, void * object);
Loop ForEachActiveObjectInner(void * context, Lambda lambda);
Loop ForEachActiveObjectInner(void * context, Loop lambda(void * context, const void * object)) const
{
return const_cast<StaticAllocatorBitmap *>(this)->ForEachActiveObjectInner(context, reinterpret_cast<Lambda>(lambda));
}
private:
void * mElements;
const size_t mElementSize;
std::atomic<tBitChunkType> * mUsage;
};
template <class T>
class PoolCommon
{
public:
template <typename... Args>
void ResetObject(T * element, Args &&... args)
{
element->~T();
new (element) T(std::forward<Args>(args)...);
}
};
template <typename T, typename Function>
class LambdaProxy
{
public:
LambdaProxy(Function && function) : mFunction(std::move(function)) {}
static Loop Call(void * context, void * target)
{
return static_cast<LambdaProxy *>(context)->mFunction(static_cast<T *>(target));
}
static Loop ConstCall(void * context, const void * target)
{
return static_cast<LambdaProxy *>(context)->mFunction(static_cast<const T *>(target));
}
private:
Function mFunction;
};
#if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP
struct HeapObjectListNode
{
void Remove()
{
mNext->mPrev = mPrev;
mPrev->mNext = mNext;
}
void * mObject;
HeapObjectListNode * mNext;
HeapObjectListNode * mPrev;
};
struct HeapObjectList : HeapObjectListNode
{
HeapObjectList() : mIterationDepth(0) { mNext = mPrev = this; }
void Append(HeapObjectListNode * node)
{
node->mNext = this;
node->mPrev = mPrev;
mPrev->mNext = node;
mPrev = node;
}
HeapObjectListNode * FindNode(void * object) const;
using Lambda = Loop (*)(void *, void *);
Loop ForEachNode(void * context, Lambda lambda);
Loop ForEachNode(void * context, Loop lambda(void * context, const void * object)) const
{
return const_cast<HeapObjectList *>(this)->ForEachNode(context, reinterpret_cast<Lambda>(lambda));
}
size_t mIterationDepth;
};
#endif // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP
} // namespace internal
/**
* @class ObjectPool
*
* Depending on build configuration, ObjectPool is either a fixed-size static pool or a heap-allocated pool.
*
* @tparam T Type of element to be allocated.
* @tparam N Number of elements in the pool, in the fixed-size case.
*
* @fn CreateObject
* @memberof ObjectPool
*
* Create an object from the pool. Forwards its arguments to construct a T.
*
* @fn ReleaseObject
* @memberof ObjectPool
* @param object Pointer to object to release (or return to the pool). Its destructor runs.
*
* @fn ForEachActiveObject
* @memberof ObjectPool
* @param visitor A function that takes a T* and returns Loop::Continue to continue iterating or Loop::Break to stop iterating.
* @returns Loop::Break if a visitor call returned Loop::Break, Loop::Finish otherwise.
*
* Iteration may be nested. ReleaseObject() can be called during iteration, on the current object or any other.
* CreateObject() can be called, but it is undefined whether or not a newly created object will be visited.
*/
/**
* A class template used for allocating objects from a fixed-size static pool.
*
* @tparam T type of element to be allocated.
* @tparam N a positive integer max number of elements the pool provides.
*/
template <class T, size_t N>
class BitMapObjectPool : public internal::StaticAllocatorBitmap, public internal::PoolCommon<T>
{
public:
BitMapObjectPool() : StaticAllocatorBitmap(mData.mMemory, mUsage, N, sizeof(T)) {}
~BitMapObjectPool() { VerifyOrDie(Allocated() == 0); }
template <typename... Args>
T * CreateObject(Args &&... args)
{
T * element = static_cast<T *>(Allocate());
if (element != nullptr)
return new (element) T(std::forward<Args>(args)...);
else
return nullptr;
}
void ReleaseObject(T * element)
{
if (element == nullptr)
return;
element->~T();
Deallocate(element);
}
void ReleaseAll() { ForEachActiveObjectInner(this, ReleaseObject); }
/**
* @brief
* Run a functor for each active object in the pool
*
* @param function The functor of type `Loop (*)(T*)`, return Loop::Break to break the iteration
* @return Loop Returns Break or Finish according to the iteration
*
* caution
* this function is not thread-safe, make sure all usage of the
* pool is protected by a lock, or else avoid using this function
*/
template <typename Function>
Loop ForEachActiveObject(Function && function)
{
static_assert(std::is_same<Loop, decltype(function(std::declval<T *>()))>::value,
"The function must take T* and return Loop");
internal::LambdaProxy<T, Function> proxy(std::forward<Function>(function));
return ForEachActiveObjectInner(&proxy, &internal::LambdaProxy<T, Function>::Call);
}
template <typename Function>
Loop ForEachActiveObject(Function && function) const
{
static_assert(std::is_same<Loop, decltype(function(std::declval<const T *>()))>::value,
"The function must take const T* and return Loop");
internal::LambdaProxy<T, Function> proxy(std::forward<Function>(function));
return ForEachActiveObjectInner(&proxy, &internal::LambdaProxy<T, Function>::ConstCall);
}
private:
static Loop ReleaseObject(void * context, void * object)
{
static_cast<BitMapObjectPool *>(context)->ReleaseObject(static_cast<T *>(object));
return Loop::Continue;
}
std::atomic<tBitChunkType> mUsage[(N + kBitChunkSize - 1) / kBitChunkSize];
union Data
{
Data() {}
~Data() {}
alignas(alignof(T)) uint8_t mMemory[N * sizeof(T)];
T mMemoryViewForDebug[N]; // Just for debugger
} mData;
};
#if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP
/**
* A class template used for allocating objects from the heap.
*
* @tparam T type to be allocated.
*/
template <class T>
class HeapObjectPool : public internal::Statistics, public internal::PoolCommon<T>
{
public:
HeapObjectPool() {}
~HeapObjectPool()
{
#ifndef __SANITIZE_ADDRESS__
#ifdef __clang__
#if __has_feature(address_sanitizer)
#define __SANITIZE_ADDRESS__ 1
#endif
#endif
#endif
#if __SANITIZE_ADDRESS__
// Free all remaining objects so that ASAN can catch specific use-after-free cases.
ReleaseAll();
#else // __SANITIZE_ADDRESS__
// Verify that no live objects remain, to prevent potential use-after-free.
VerifyOrDie(Allocated() == 0);
#endif // __SANITIZE_ADDRESS__
}
template <typename... Args>
T * CreateObject(Args &&... args)
{
T * object = Platform::New<T>(std::forward<Args>(args)...);
if (object != nullptr)
{
auto node = Platform::New<internal::HeapObjectListNode>();
if (node != nullptr)
{
node->mObject = object;
mObjects.Append(node);
IncreaseUsage();
return object;
}
}
return nullptr;
}
/*
* This method exists purely to line up with the static allocator version.
* Consequently, return a nonsensically large number to normalize comparison
* operations that act on this value.
*/
size_t Capacity() const { return SIZE_MAX; }
void ReleaseObject(T * object)
{
if (object != nullptr)
{
internal::HeapObjectListNode * node = mObjects.FindNode(object);
if (node != nullptr)
{
// Note that the node is not removed here; that is deferred until the end of the next pool iteration.
node->mObject = nullptr;
Platform::Delete(object);
DecreaseUsage();
}
}
}
void ReleaseAll() { mObjects.ForEachNode(this, ReleaseObject); }
/**
* @brief
* Run a functor for each active object in the pool
*
* @param function The functor of type `Loop (*)(T*)`, return Loop::Break to break the iteration
* @return Loop Returns Break or Finish according to the iteration
*/
template <typename Function>
Loop ForEachActiveObject(Function && function)
{
static_assert(std::is_same<Loop, decltype(function(std::declval<T *>()))>::value,
"The function must take T* and return Loop");
internal::LambdaProxy<T, Function> proxy(std::forward<Function>(function));
return mObjects.ForEachNode(&proxy, &internal::LambdaProxy<T, Function>::Call);
}
template <typename Function>
Loop ForEachActiveObject(Function && function) const
{
static_assert(std::is_same<Loop, decltype(function(std::declval<const T *>()))>::value,
"The function must take const T* and return Loop");
internal::LambdaProxy<const T, Function> proxy(std::forward<Function>(function));
return mObjects.ForEachNode(&proxy, &internal::LambdaProxy<const T, Function>::ConstCall);
}
private:
static Loop ReleaseObject(void * context, void * object)
{
static_cast<HeapObjectPool *>(context)->ReleaseObject(static_cast<T *>(object));
return Loop::Continue;
}
internal::HeapObjectList mObjects;
};
#endif // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP
/**
* Specify ObjectPool storage allocation.
*/
enum class ObjectPoolMem
{
/**
* Use storage inside the containing scope for both objects and pool management state.
*/
kInline,
#if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP
/**
* Allocate objects from the heap, with only pool management state in the containing scope.
*
* For this case, the ObjectPool size parameter is ignored.
*/
kHeap,
kDefault = kHeap
#else // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP
kDefault = kInline
#endif // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP
};
template <typename T, size_t N, ObjectPoolMem P = ObjectPoolMem::kDefault>
class ObjectPool;
template <typename T, size_t N>
class ObjectPool<T, N, ObjectPoolMem::kInline> : public BitMapObjectPool<T, N>
{
};
#if CHIP_SYSTEM_CONFIG_POOL_USE_HEAP
template <typename T, size_t N>
class ObjectPool<T, N, ObjectPoolMem::kHeap> : public HeapObjectPool<T>
{
};
#endif // CHIP_SYSTEM_CONFIG_POOL_USE_HEAP
} // namespace chip