Debian Codegraph @

crt/aws-c-common/source/allocator_sba.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/common/allocator.h>
7 #include <aws/common/array_list.h>
8 #include <aws/common/assert.h>
9 #include <aws/common/macros.h>
10 #include <aws/common/mutex.h>
11
12 /*
13 * Small Block Allocator
14 * This is a fairly standard approach, the idea is to always allocate aligned pages of memory so that for
15 * any address you can round to the nearest page boundary to find the bookkeeping data. The idea is to reduce
16 * overhead per alloc and greatly improve runtime speed by doing as little actual allocation work as possible,
17 * preferring instead to re-use (hopefully still cached) chunks in FIFO order, or chunking up a page if there's
18 * no free chunks. When all chunks in a page are freed, the page is returned to the OS.
19 *
20 * The allocator itself is simply an array of bins, each representing a power of 2 size from 32 - N (512 tends to be
21 * a good upper bound). Thread safety is guaranteed by a mutex per bin, and locks are only necessary around the
22 * lowest level alloc and free operations.
23 *
24 * Note: this allocator gets its internal memory for data structures from the parent allocator, but does not
25 * use the parent to allocate pages. Pages are allocated directly from the OS-specific aligned malloc implementation,
26 * which allows the OS to do address re-mapping for us instead of over-allocating to fulfill alignment.
27 */
28
29 #ifdef _WIN32
30 # include <malloc.h>
31 #elif __linux__ || __APPLE__
32 # include <stdlib.h>
33 #endif
34
35 #if !defined(AWS_SBA_PAGE_SIZE)
36 # if defined(PAGE_SIZE)
37 # define AWS_SBA_PAGE_SIZE ((uintptr_t)(PAGE_SIZE))
38 # else
39 # define AWS_SBA_PAGE_SIZE ((uintptr_t)(4096))
40 # endif
41 #endif
42
43 #define AWS_SBA_PAGE_MASK ((uintptr_t) ~(AWS_SBA_PAGE_SIZE - 1))
44 #define AWS_SBA_TAG_VALUE 0x736f6d6570736575ULL
45
46 /* list of sizes of bins, must be powers of 2, and less than AWS_SBA_PAGE_SIZE * 0.5 */
47 enum { AWS_SBA_BIN_COUNT = 5 };
48 static const size_t s_bin_sizes[AWS_SBA_BIN_COUNT] = {32, 64, 128, 256, 512};
49 static const size_t s_max_bin_size = 512;
50
51 struct sba_bin {
52 size_t size; /* size of allocs in this bin */
53 struct aws_mutex mutex; /* lock protecting this bin */
54 uint8_t *page_cursor; /* pointer to working page, currently being chunked from */
55 struct aws_array_list active_pages; /* all pages in use by this bin, could be optimized at scale by being a set */
56 struct aws_array_list free_chunks; /* free chunks available in this bin */
57 };
58
59 /* Header stored at the base of each page.
60 * As long as this is under 32 bytes, all is well.
61 * Above that, there's potentially more waste per page */
62 struct page_header {
63 uint64_t tag; /* marker to identify/validate pages */
64 struct sba_bin *bin; /* bin this page belongs to */
65 uint32_t alloc_count; /* number of outstanding allocs from this page */
66 uint64_t tag2;
67 };
68
69 /* This is the impl for the aws_allocator */
70 struct small_block_allocator {
71 struct aws_allocator *allocator; /* parent allocator, for large allocs */
72 struct sba_bin bins[AWS_SBA_BIN_COUNT];
73 int (*lock)(struct aws_mutex *);
74 int (*unlock)(struct aws_mutex *);
75 };
76
77 static int s_null_lock(struct aws_mutex *mutex) {
78 (void)mutex;
79 /* NO OP */
80 return 0;
81 }
82
83 static int s_null_unlock(struct aws_mutex *mutex) {
84 (void)mutex;
85 /* NO OP */
86 return 0;
87 }
88
89 static int s_mutex_lock(struct aws_mutex *mutex) {
90 return aws_mutex_lock(mutex);
91 }
92
93 static int s_mutex_unlock(struct aws_mutex *mutex) {
94 return aws_mutex_unlock(mutex);
95 }
96
97 static void *s_page_base(const void *addr) {
98 /* mask off the address to round it to page alignment */
99 uint8_t *page_base = (uint8_t *)(((uintptr_t)addr) & AWS_SBA_PAGE_MASK);
100 return page_base;
101 }
102
103 static void *s_page_bind(void *addr, struct sba_bin *bin) {
104 /* insert the header at the base of the page and advance past it */
105 struct page_header *page = (struct page_header *)addr;
106 page->tag = page->tag2 = AWS_SBA_TAG_VALUE;
107 page->bin = bin;
108 page->alloc_count = 0;
109 return (uint8_t *)addr + sizeof(struct page_header);
110 }
111
112 /* Wraps OS-specific aligned malloc implementation */
113 static void *s_aligned_alloc(size_t size, size_t align) {
114 #ifdef _WIN32
115 return _aligned_malloc(size, align);
116 #else
117 void *mem = NULL;
118 int return_code = posix_memalign(&mem, align, size);
119 if (return_code) {
120 aws_raise_error(AWS_ERROR_OOM);
121 return NULL;
122 }
123 return mem;
124 #endif
125 }
126
127 /* wraps OS-specific aligned free implementation */
128 static void s_aligned_free(void *addr) {
129 #ifdef _WIN32
130 _aligned_free(addr);
131 #else
132 free(addr);
133 #endif
134 }
135
136 /* aws_allocator vtable template */
137 static void *s_sba_mem_acquire(struct aws_allocator *allocator, size_t size);
138 static void s_sba_mem_release(struct aws_allocator *allocator, void *ptr);
139 static void *s_sba_mem_realloc(struct aws_allocator *allocator, void *old_ptr, size_t old_size, size_t new_size);
140 static void *s_sba_mem_calloc(struct aws_allocator *allocator, size_t num, size_t size);
141
142 static struct aws_allocator s_sba_allocator = {
143 .mem_acquire = s_sba_mem_acquire,
144 .mem_release = s_sba_mem_release,
145 .mem_realloc = s_sba_mem_realloc,
146 .mem_calloc = s_sba_mem_calloc,
147 };
148
149 static int s_sba_init(struct small_block_allocator *sba, struct aws_allocator *allocator, bool multi_threaded) {
150 sba->allocator = allocator;
151 AWS_ZERO_ARRAY(sba->bins);
152 sba->lock = multi_threaded ? s_mutex_lock : s_null_lock;
153 sba->unlock = multi_threaded ? s_mutex_unlock : s_null_unlock;
154
155 for (unsigned idx = 0; idx < AWS_SBA_BIN_COUNT; ++idx) {
156 struct sba_bin *bin = &sba->bins[idx];
157 bin->size = s_bin_sizes[idx];
158 if (multi_threaded && aws_mutex_init(&bin->mutex)) {
159 goto cleanup;
160 }
161 if (aws_array_list_init_dynamic(&bin->active_pages, sba->allocator, 16, sizeof(void *))) {
162 goto cleanup;
163 }
164 /* start with enough chunks for 1 page */
165 if (aws_array_list_init_dynamic(
166 &bin->free_chunks, sba->allocator, aws_max_size(AWS_SBA_PAGE_SIZE / bin->size, 16), sizeof(void *))) {
167 goto cleanup;
168 }
169 }
170
171 return AWS_OP_SUCCESS;
172
173 cleanup:
174 for (unsigned idx = 0; idx < AWS_SBA_BIN_COUNT; ++idx) {
175 struct sba_bin *bin = &sba->bins[idx];
176 aws_mutex_clean_up(&bin->mutex);
177 aws_array_list_clean_up(&bin->active_pages);
178 aws_array_list_clean_up(&bin->free_chunks);
179 }
180 return AWS_OP_ERR;
181 }
182
183 static void s_sba_clean_up(struct small_block_allocator *sba) {
184 /* free all known pages, then free the working page */
185 for (unsigned idx = 0; idx < AWS_SBA_BIN_COUNT; ++idx) {
186 struct sba_bin *bin = &sba->bins[idx];
187 for (size_t page_idx = 0; page_idx < bin->active_pages.length; ++page_idx) {
188 void *page_addr = NULL;
189 aws_array_list_get_at(&bin->active_pages, &page_addr, page_idx);
190 struct page_header *page = page_addr;
191 AWS_ASSERT(page->alloc_count == 0 && "Memory still allocated in aws_sba_allocator (bin)");
192 s_aligned_free(page);
193 }
194 if (bin->page_cursor) {
195 void *page_addr = s_page_base(bin->page_cursor);
196 struct page_header *page = page_addr;
197 AWS_ASSERT(page->alloc_count == 0 && "Memory still allocated in aws_sba_allocator (page)");
198 s_aligned_free(page);
199 }
200
201 aws_array_list_clean_up(&bin->active_pages);
202 aws_array_list_clean_up(&bin->free_chunks);
203 aws_mutex_clean_up(&bin->mutex);
204 }
205 }
206
207 struct aws_allocator *aws_small_block_allocator_new(struct aws_allocator *allocator, bool multi_threaded) {
208 struct small_block_allocator *sba = NULL;
209 struct aws_allocator *sba_allocator = NULL;
210 aws_mem_acquire_many(
211 allocator, 2, &sba, sizeof(struct small_block_allocator), &sba_allocator, sizeof(struct aws_allocator));
212
213 if (!sba || !sba_allocator) {
214 return NULL;
215 }
216
217 AWS_ZERO_STRUCT(*sba);
218 AWS_ZERO_STRUCT(*sba_allocator);
219
220 /* copy the template vtable */
221 *sba_allocator = s_sba_allocator;
222 sba_allocator->impl = sba;
223
224 if (s_sba_init(sba, allocator, multi_threaded)) {
225 s_sba_clean_up(sba);
226 aws_mem_release(allocator, sba);
227 return NULL;
228 }
229 return sba_allocator;
230 }
231
232 void aws_small_block_allocator_destroy(struct aws_allocator *sba_allocator) {
233 if (!sba_allocator) {
234 return;
235 }
236 struct small_block_allocator *sba = sba_allocator->impl;
237 if (!sba) {
238 return;
239 }
240
241 struct aws_allocator *allocator = sba->allocator;
242 s_sba_clean_up(sba);
243 aws_mem_release(allocator, sba);
244 }
245
246 size_t aws_small_block_allocator_bytes_active(struct aws_allocator *sba_allocator) {
247 AWS_FATAL_ASSERT(sba_allocator && "aws_small_block_allocator_bytes_used requires a non-null allocator");
248 struct small_block_allocator *sba = sba_allocator->impl;
249 AWS_FATAL_ASSERT(sba && "aws_small_block_allocator_bytes_used: supplied allocator has invalid SBA impl");
250
251 size_t used = 0;
252 for (unsigned idx = 0; idx < AWS_SBA_BIN_COUNT; ++idx) {
253 struct sba_bin *bin = &sba->bins[idx];
254 sba->lock(&bin->mutex);
255 for (size_t page_idx = 0; page_idx < bin->active_pages.length; ++page_idx) {
256 void *page_addr = NULL;
257 aws_array_list_get_at(&bin->active_pages, &page_addr, page_idx);
258 struct page_header *page = page_addr;
259 used += page->alloc_count * bin->size;
260 }
261 if (bin->page_cursor) {
262 void *page_addr = s_page_base(bin->page_cursor);
263 struct page_header *page = page_addr;
264 used += page->alloc_count * bin->size;
265 }
266 sba->unlock(&bin->mutex);
267 }
268
269 return used;
270 }
271
272 size_t aws_small_block_allocator_bytes_reserved(struct aws_allocator *sba_allocator) {
273 AWS_FATAL_ASSERT(sba_allocator && "aws_small_block_allocator_bytes_used requires a non-null allocator");
274 struct small_block_allocator *sba = sba_allocator->impl;
275 AWS_FATAL_ASSERT(sba && "aws_small_block_allocator_bytes_used: supplied allocator has invalid SBA impl");
276
277 size_t used = 0;
278 for (unsigned idx = 0; idx < AWS_SBA_BIN_COUNT; ++idx) {
279 struct sba_bin *bin = &sba->bins[idx];
280 sba->lock(&bin->mutex);
281 used += (bin->active_pages.length + (bin->page_cursor != NULL)) * AWS_SBA_PAGE_SIZE;
282 sba->unlock(&bin->mutex);
283 }
284
285 return used;
286 }
287
288 size_t aws_small_block_allocator_page_size(struct aws_allocator *sba_allocator) {
289 (void)sba_allocator;
290 return AWS_SBA_PAGE_SIZE;
291 }
292
293 size_t aws_small_block_allocator_page_size_available(struct aws_allocator *sba_allocator) {
294 (void)sba_allocator;
295 return AWS_SBA_PAGE_SIZE - sizeof(struct page_header);
296 }
297
298 /* NOTE: Expects the mutex to be held by the caller */
299 static void *s_sba_alloc_from_bin(struct sba_bin *bin) {
300 /* check the free list, hand chunks out in FIFO order */
301 if (bin->free_chunks.length > 0) {
302 void *chunk = NULL;
303 if (aws_array_list_back(&bin->free_chunks, &chunk)) {
304 return NULL;
305 }
306 if (aws_array_list_pop_back(&bin->free_chunks)) {
307 return NULL;
308 }
309
310 AWS_ASSERT(chunk);
311 struct page_header *page = s_page_base(chunk);
312 page->alloc_count++;
313 return chunk;
314 }
315
316 /* If there is a working page to chunk from, use it */
317 if (bin->page_cursor) {
318 struct page_header *page = s_page_base(bin->page_cursor);
319 AWS_ASSERT(page);
320 size_t space_left = AWS_SBA_PAGE_SIZE - (bin->page_cursor - (uint8_t *)page);
321 if (space_left >= bin->size) {
322 void *chunk = bin->page_cursor;
323 page->alloc_count++;
324 bin->page_cursor += bin->size;
325 space_left -= bin->size;
326 if (space_left < bin->size) {
327 aws_array_list_push_back(&bin->active_pages, &page);
328 bin->page_cursor = NULL;
329 }
330 return chunk;
331 }
332 }
333
334 /* Nothing free to use, allocate a page and restart */
335 uint8_t *new_page = s_aligned_alloc(AWS_SBA_PAGE_SIZE, AWS_SBA_PAGE_SIZE);
336 new_page = s_page_bind(new_page, bin);
337 bin->page_cursor = new_page;
338 return s_sba_alloc_from_bin(bin);
339 }
340
341 /* NOTE: Expects the mutex to be held by the caller */
342 static void s_sba_free_to_bin(struct sba_bin *bin, void *addr) {
343 AWS_PRECONDITION(addr);
344 struct page_header *page = s_page_base(addr);
345 AWS_ASSERT(page->bin == bin);
346 page->alloc_count--;
347 if (page->alloc_count == 0 && page != s_page_base(bin->page_cursor)) { /* empty page, free it */
348 uint8_t *page_start = (uint8_t *)page + sizeof(struct page_header);
349 uint8_t *page_end = page_start + AWS_SBA_PAGE_SIZE;
350 /* Remove all chunks in the page from the free list */
351 intptr_t chunk_idx = (intptr_t)bin->free_chunks.length;
352 for (; chunk_idx >= 0; --chunk_idx) {
353 uint8_t *chunk = NULL;
354 aws_array_list_get_at(&bin->free_chunks, &chunk, chunk_idx);
355 if (chunk >= page_start && chunk < page_end) {
356 aws_array_list_swap(&bin->free_chunks, chunk_idx, bin->free_chunks.length - 1);
357 aws_array_list_pop_back(&bin->free_chunks);
358 }
359 }
360
361 /* Find page in pages list and remove it */
362 for (size_t page_idx = 0; page_idx < bin->active_pages.length; ++page_idx) {
363 void *page_addr = NULL;
364 aws_array_list_get_at(&bin->active_pages, &page_addr, page_idx);
365 if (page_addr == page) {
366 aws_array_list_swap(&bin->active_pages, page_idx, bin->active_pages.length - 1);
367 aws_array_list_pop_back(&bin->active_pages);
368 break;
369 }
370 }
371 /* ensure that the page tag is erased, in case nearby memory is re-used */
372 page->tag = page->tag2 = 0;
373 s_aligned_free(page);
374 return;
375 }
376
377 aws_array_list_push_back(&bin->free_chunks, &addr);
378 }
379
380 /* No lock required for this function, it's all read-only access to constant data */
381 static struct sba_bin *s_sba_find_bin(struct small_block_allocator *sba, size_t size) {
382 AWS_PRECONDITION(size <= s_max_bin_size);
383
384 /* map bits 5(32) to 9(512) to indices 0-4 */
385 size_t next_pow2 = 0;
386 aws_round_up_to_power_of_two(size, &next_pow2);
387 size_t lz = aws_clz_i32((int32_t)next_pow2);
388 size_t idx = aws_sub_size_saturating(31 - lz, 5);
389 AWS_ASSERT(idx <= 4);
390 struct sba_bin *bin = &sba->bins[idx];
391 AWS_ASSERT(bin->size >= size);
392 return bin;
393 }
394
395 static void *s_sba_alloc(struct small_block_allocator *sba, size_t size) {
396 if (size <= s_max_bin_size) {
397 struct sba_bin *bin = s_sba_find_bin(sba, size);
398 AWS_FATAL_ASSERT(bin);
399 /* BEGIN CRITICAL SECTION */
400 sba->lock(&bin->mutex);
401 void *mem = s_sba_alloc_from_bin(bin);
402 sba->unlock(&bin->mutex);
403 /* END CRITICAL SECTION */
404 return mem;
405 }
406 return aws_mem_acquire(sba->allocator, size);
407 }
408
409 AWS_SUPPRESS_ASAN AWS_SUPPRESS_TSAN static void s_sba_free(struct small_block_allocator *sba, void *addr) {
410 if (!addr) {
411 return;
412 }
413
414 struct page_header *page = (struct page_header *)s_page_base(addr);
415 /* Check to see if this page is tagged by the sba */
416 /* this check causes a read of (possibly) memory we didn't allocate, but it will always be
417 * heap memory, so should not cause any issues. TSan will see this as a data race, but it
418 * is not, that's a false positive
419 */
420 if (page->tag == AWS_SBA_TAG_VALUE && page->tag2 == AWS_SBA_TAG_VALUE) {
421 struct sba_bin *bin = page->bin;
422 /* BEGIN CRITICAL SECTION */
423 sba->lock(&bin->mutex);
424 s_sba_free_to_bin(bin, addr);
425 sba->unlock(&bin->mutex);
426 /* END CRITICAL SECTION */
427 return;
428 }
429 /* large alloc, give back to underlying allocator */
430 aws_mem_release(sba->allocator, addr);
431 }
432
433 static void *s_sba_mem_acquire(struct aws_allocator *allocator, size_t size) {
434 struct small_block_allocator *sba = allocator->impl;
435 return s_sba_alloc(sba, size);
436 }
437
438 static void s_sba_mem_release(struct aws_allocator *allocator, void *ptr) {
439 struct small_block_allocator *sba = allocator->impl;
440 s_sba_free(sba, ptr);
441 }
442
443 static void *s_sba_mem_realloc(struct aws_allocator *allocator, void *old_ptr, size_t old_size, size_t new_size) {
444 struct small_block_allocator *sba = allocator->impl;
445 /* If both allocations come from the parent, let the parent do it */
446 if (old_size > s_max_bin_size && new_size > s_max_bin_size) {
447 void *ptr = old_ptr;
448 if (aws_mem_realloc(sba->allocator, &ptr, old_size, new_size)) {
449 return NULL;
450 }
451 return ptr;
452 }
453
454 if (new_size == 0) {
455 s_sba_free(sba, old_ptr);
456 return NULL;
457 }
458
459 if (old_size > new_size) {
460 return old_ptr;
461 }
462
463 void *new_mem = s_sba_alloc(sba, new_size);
464 if (old_ptr && old_size) {
465 memcpy(new_mem, old_ptr, old_size);
466 s_sba_free(sba, old_ptr);
467 }
468
469 return new_mem;
470 }
471
472 static void *s_sba_mem_calloc(struct aws_allocator *allocator, size_t num, size_t size) {
473 struct small_block_allocator *sba = allocator->impl;
474 void *mem = s_sba_alloc(sba, size * num);
475 memset(mem, 0, size * num);
476 return mem;
477 }