Debian Codegraph @

crt/aws-c-s3/source/s3_default_buffer_pool.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/s3/private/s3_default_buffer_pool.h>
7
8 #include <aws/common/array_list.h>
9 #include <aws/common/ref_count.h>
10 #include <aws/common/system_info.h>
11 #include <aws/io/future.h>
12 #include <aws/s3/private/s3_util.h>
13
14 #include <inttypes.h>
15
16 /*
17 * S3 Buffer Pool.
18 * Fairly trivial implementation of "arena" style allocator.
19 * Note: current implementation is not optimized and instead tries to be
20 * as straightforward as possible. Given that pool manages a small number
21 * of big allocations, performance impact is not that bad, but something we need
22 * to look into on the next iteration.
23 *
24 * Basic approach is to divide acquires into primary and secondary.
25 * User provides chunk size during construction. Acquires below 4 * chunks_size
26 * are done from primary and the rest are from secondary.
27 *
28 * Primary storage consists of blocks that are each s_chunks_per_block *
29 * chunk_size in size. blocks are created on demand as needed.
30 * Acquire operation from primary basically works by determining how many chunks
31 * are needed and then finding available space in existing blocks or creating a
32 * new block. Acquire will always take over the whole chunk, so some space is
33 * likely wasted.
34 * Ex. say chunk_size is 8mb and s_chunks_per_block is 16, which makes block size 128mb.
35 * acquires up to 32mb will be done from primary. So 1 block can hold 4 buffers
36 * of 32mb (4 chunks) or 16 buffers of 8mb (1 chunk). If requested buffer size
37 * is 12mb, 2 chunks are used for acquire and 4mb will be wasted.
38 * Secondary storage delegates directly to system allocator.
39 *
40 * One complication is "forced" buffers. A forced buffer is one that
41 * comes from primary or secondary storage as usual, but it is allowed to exceed
42 * the memory limit. This is only used when we want to use memory from
43 * the pool, but waiting for a normal ticket reservation could cause deadlock.
44 */
45
46 struct aws_s3_default_buffer_pool;
47
48 struct aws_s3_default_buffer_ticket {
49 size_t size;
50 uint8_t *ptr;
51 size_t chunks_used;
52 bool forced;
53 struct aws_s3_buffer_pool *pool;
54 enum aws_s3_default_buffer_pool_reserved_from reserved_from; /* which area ticket was reserved from */
55 };
56
57 /* Default size for blocks array. Note: this is just for meta info, blocks
58 * themselves are not preallocated. */
59 static size_t s_block_list_initial_capacity = 5;
60
61 /* Amount of mem reserved for use outside of buffer pool.
62 * This is an optimistic upper bound on mem used as we dont track it.
63 * Covers both usage outside of pool, i.e. all allocations done as part of s3
64 * client as well as any allocations overruns due to memory waste in the pool. */
65 static const size_t s_buffer_pool_reserved_mem = MB_TO_BYTES(128);
66
67 /*
68 * How many chunks make up a block in primary storage.
69 */
70 static const size_t s_chunks_per_block = 16;
71
72 /*
73 * Max size of chunks in primary.
74 * Effectively if client part size is above the following number, primary
75 * storage along with buffer reuse is disabled and all buffers are allocated
76 * directly using allocator.
77 */
78 static const size_t s_max_chunk_size_for_buffer_reuse = MB_TO_BYTES(64);
79
80 /* Forced buffers only count against the memory limit up to a certain percent.
81 * For example: if mem_limit is 10GiB, and forced_use is 11GiB, and THIS number is 90(%),
82 * we still consider 1GiB available for normal buffer usage. */
83 static const size_t s_max_impact_of_forced_buffers_on_memory_limit_as_percentage = 80;
84
85 /*
86 * primary min cut off. below this number buffers are not allocated from primary and instead use
87 * secondary.
88 */
89 static const size_t s_primary_min_cutoff = KB_TO_BYTES(512);
90
91 /*
92 * Sets n bits at position starting with LSB.
93 * Note: n must be at most 8, but in practice will always be at most 4.
94 * position + n should at most be 16
95 */
96 static inline uint16_t s_set_bits(uint16_t num, size_t position, size_t n) {
97 AWS_PRECONDITION(n <= 8);
98 AWS_PRECONDITION(position + n <= 16);
99 uint16_t mask = ((uint16_t)0x00FF) >> (8 - n);
100 return num | (mask << position);
101 }
102
103 /*
104 * Clears n bits at position starting with LSB.
105 * Note: n must be at most 8, but in practice will always be at most 4.
106 * position + n should at most be 16
107 */
108 static inline uint16_t s_clear_bits(uint16_t num, size_t position, size_t n) {
109 AWS_PRECONDITION(n <= 8);
110 AWS_PRECONDITION(position + n <= 16);
111 uint16_t mask = ((uint16_t)0x00FF) >> (8 - n);
112 return num & ~(mask << position);
113 }
114
115 /*
116 * Checks whether n bits are set at position starting with LSB.
117 * Note: n must be at most 8, but in practice will always be at most 4.
118 * position + n should at most be 16
119 */
120 static inline bool s_check_bits(uint16_t num, size_t position, size_t n) {
121 AWS_PRECONDITION(n <= 8);
122 AWS_PRECONDITION(position + n <= 16);
123 uint16_t mask = ((uint16_t)0x00FF) >> (8 - n);
124 return (num >> position) & mask;
125 }
126
127 static void s_aws_ticket_wrapper_destroy(void *data);
128
129 struct aws_byte_buf s_default_ticket_claim(struct aws_s3_buffer_ticket *ticket_wrapper) {
130 struct aws_s3_default_buffer_ticket *ticket = ticket_wrapper->impl;
131 return aws_s3_default_buffer_pool_acquire_buffer(ticket->pool, ticket);
132 }
133
134 static struct aws_s3_buffer_ticket_vtable s_default_ticket_vtable = {.claim = s_default_ticket_claim};
135
136 struct aws_s3_buffer_ticket *s_wrap_default_ticket(struct aws_s3_default_buffer_ticket *ticket) {
137 struct aws_s3_default_buffer_pool *pool = ticket->pool->impl;
138 struct aws_s3_buffer_ticket *ticket_wrapper =
139 aws_mem_calloc(pool->base_allocator, 1, sizeof(struct aws_s3_buffer_ticket));
140
141 ticket_wrapper->impl = ticket;
142 ticket_wrapper->vtable = &s_default_ticket_vtable;
143 aws_ref_count_init(
144 &ticket_wrapper->ref_count, ticket_wrapper, (aws_simple_completion_callback *)s_aws_ticket_wrapper_destroy);
145
146 return ticket_wrapper;
147 }
148
149 struct aws_future_s3_buffer_ticket *s_default_pool_reserve(
150 struct aws_s3_buffer_pool *pool,
151 struct aws_s3_buffer_pool_reserve_meta meta) {
152
153 return aws_s3_default_buffer_pool_reserve(pool, meta);
154 }
155
156 void s_default_pool_trim(struct aws_s3_buffer_pool *pool) {
157 aws_s3_default_buffer_pool_trim(pool);
158 }
159
160 static int s_default_pool_add_special_size(struct aws_s3_buffer_pool *buffer_pool_wrapper, size_t buffer_size);
161 static void s_default_pool_release_special_size(struct aws_s3_buffer_pool *buffer_pool_wrapper, size_t buffer_size);
162 static uint64_t s_default_pool_derive_aligned_buffer_size(
163 struct aws_s3_buffer_pool *buffer_pool_wrapper,
164 uint64_t size);
165
166 static struct aws_s3_buffer_pool_vtable s_default_pool_vtable = {
167 .reserve = s_default_pool_reserve,
168 .trim = s_default_pool_trim,
169 .add_special_size = s_default_pool_add_special_size,
170 .release_special_size = s_default_pool_release_special_size,
171 .derive_aligned_buffer_size = s_default_pool_derive_aligned_buffer_size,
172 };
173
174 static void s_destroy_special_block_list(void *val) {
175 struct s3_special_block_list *special_list = val;
176
177 /* Free all allocated blocks */
178 for (size_t i = 0; i < aws_array_list_length(&special_list->blocks); ++i) {
179 struct s3_buffer_pool_block *block;
180 aws_array_list_get_at_ptr(&special_list->blocks, (void **)&block, i);
181 aws_mem_release(special_list->allocator, block->block_ptr);
182 }
183
184 aws_array_list_clean_up(&special_list->blocks);
185 aws_mem_release(special_list->allocator, special_list);
186 }
187
188 struct aws_s3_buffer_pool *aws_s3_default_buffer_pool_new(
189 struct aws_allocator *allocator,
190 struct aws_s3_buffer_pool_config config) {
191 (void)allocator;
192
193 size_t chunk_size = config.part_size;
194
195 if (config.memory_limit < GB_TO_BYTES(1)) {
196 AWS_LOGF_ERROR(
197 AWS_LS_S3_CLIENT,
198 "Failed to initialize buffer pool. "
199 "Minimum supported value for Memory Limit is 1GB.");
200 aws_raise_error(AWS_ERROR_S3_INVALID_MEMORY_LIMIT_CONFIG);
201 return NULL;
202 }
203
204 if (chunk_size < (1024) || chunk_size % (4 * 1024) != 0) {
205 AWS_LOGF_WARN(
206 AWS_LS_S3_CLIENT,
207 "Part size specified on the client can lead to suboptimal performance. "
208 "Consider specifying size in multiples of 4KiB. Ideal part size for most transfers is "
209 "1MiB multiple between 8MiB and 16MiB. Note: the client will automatically scale part size "
210 "if its not sufficient to transfer data within the maximum number of parts");
211 }
212
213 size_t adjusted_mem_lim = config.memory_limit - s_buffer_pool_reserved_mem;
214
215 if (config.max_part_size > adjusted_mem_lim) {
216 AWS_LOGF_ERROR(
217 AWS_LS_S3_CLIENT,
218 "Cannot create client from client_config; configured max part size should not exceed memory limit."
219 "size.");
220 aws_raise_error(AWS_ERROR_S3_INVALID_MEMORY_LIMIT_CONFIG);
221 return NULL;
222 }
223
224 /*
225 * TODO: There is several things we can consider tweaking here:
226 * - if chunk size is a weird number of bytes, force it to the closest page size?
227 * - grow chunk size max based on overall mem lim (ex. for 4gb it might be
228 * 64mb, but for 8gb it can be 128mb)
229 * - align chunk size to better fill available mem? some chunk sizes can
230 * result in memory being wasted because overall limit does not divide
231 * nicely into chunks
232 */
233 if (chunk_size > s_max_chunk_size_for_buffer_reuse || chunk_size * s_chunks_per_block > adjusted_mem_lim) {
234 AWS_LOGF_WARN(
235 AWS_LS_S3_CLIENT,
236 "Part size specified on the client is too large for automatic buffer reuse. "
237 "Consider specifying a smaller part size to improve performance and memory utilization");
238 chunk_size = 0;
239 }
240
241 /*
242 * Determine the min cutoff. At high level this tries to avoid using buffer pool if requests
243 * are small compared to primary (ex. 512 req buffer compared to 8mb buffer size).
244 * How that is done is fairly arbitrary. System allocator tends to be a bit better on tiny allocations.
245 * And we want to avoid wasting mem in that case.
246 * Note this is not the answer for wasting mem, but it does improve some corner cases.
247 */
248 size_t min_primary_size = 0;
249 if (4 * chunk_size >= s_primary_min_cutoff) {
250 min_primary_size = s_primary_min_cutoff;
251 } else {
252 min_primary_size = 0;
253 }
254
255 size_t page_size = aws_system_info_page_size();
256 /* TODO: if people override their allocator, this will not wrap their allocator at all. eg: mem-tracing allocator
257 * will be ignored. */
258 struct aws_allocator *aligned_allocator = aws_explicit_aligned_allocator_new(page_size);
259 struct aws_s3_default_buffer_pool *buffer_pool =
260 aws_mem_calloc(aligned_allocator, 1, sizeof(struct aws_s3_default_buffer_pool));
261
262 AWS_FATAL_ASSERT(buffer_pool != NULL);
263
264 buffer_pool->base_allocator = aligned_allocator;
265 buffer_pool->chunk_size = chunk_size;
266 buffer_pool->block_size = s_chunks_per_block * chunk_size;
267 /* Somewhat arbitrary number.
268 * Tries to balance between how many allocations use buffer and buffer space
269 * being wasted. */
270 buffer_pool->primary_size_cutoff = chunk_size * 4;
271 buffer_pool->primary_size_min_cutoff = min_primary_size;
272 buffer_pool->mem_limit = adjusted_mem_lim;
273
274 int mutex_error = aws_mutex_init(&buffer_pool->mutex);
275 AWS_FATAL_ASSERT(mutex_error == AWS_OP_SUCCESS);
276
277 aws_array_list_init_dynamic(
278 &buffer_pool->blocks,
279 buffer_pool->base_allocator,
280 s_block_list_initial_capacity,
281 sizeof(struct s3_buffer_pool_block));
282
283 aws_linked_list_init(&buffer_pool->pending_reserves);
284
285 /* Initialize special blocks hash table */
286 aws_hash_table_init(
287 &buffer_pool->special_blocks,
288 buffer_pool->base_allocator,
289 0, /* initial capacity */
290 aws_hash_ptr,
291 aws_ptr_eq,
292 NULL,
293 s_destroy_special_block_list);
294
295 struct aws_s3_buffer_pool *pool = aws_mem_calloc(buffer_pool->base_allocator, 1, sizeof(struct aws_s3_buffer_pool));
296 pool->impl = buffer_pool;
297 pool->vtable = &s_default_pool_vtable;
298 aws_ref_count_init(&pool->ref_count, pool, (aws_simple_completion_callback *)aws_s3_default_buffer_pool_destroy);
299
300 return pool;
301 }
302
303 void aws_s3_default_buffer_pool_destroy(struct aws_s3_buffer_pool *buffer_pool_wrapper) {
304 if (buffer_pool_wrapper == NULL) {
305 return;
306 }
307 AWS_FATAL_ASSERT(buffer_pool_wrapper->impl);
308
309 struct aws_s3_default_buffer_pool *buffer_pool = buffer_pool_wrapper->impl;
310 aws_mem_release(buffer_pool->base_allocator, buffer_pool_wrapper);
311
312 for (size_t i = 0; i < aws_array_list_length(&buffer_pool->blocks); ++i) {
313 struct s3_buffer_pool_block *block;
314 aws_array_list_get_at_ptr(&buffer_pool->blocks, (void **)&block, i);
315
316 AWS_FATAL_ASSERT(block->alloc_bit_mask == 0 && "Allocator still has outstanding blocks");
317 aws_mem_release(buffer_pool->base_allocator, block->block_ptr);
318 }
319
320 aws_array_list_clean_up(&buffer_pool->blocks);
321
322 while (!aws_linked_list_empty(&buffer_pool->pending_reserves)) {
323 struct aws_linked_list_node *node = aws_linked_list_front(&buffer_pool->pending_reserves);
324 struct s3_pending_reserve *pending = AWS_CONTAINER_OF(node, struct s3_pending_reserve, node);
325 AWS_FATAL_ASSERT(aws_future_s3_buffer_ticket_is_done(pending->ticket_future));
326 aws_future_s3_buffer_ticket_release(pending->ticket_future);
327 aws_linked_list_pop_front(&buffer_pool->pending_reserves);
328 aws_mem_release(buffer_pool->base_allocator, pending);
329 }
330
331 /* Clean up special blocks */
332 aws_hash_table_clean_up(&buffer_pool->special_blocks);
333
334 aws_mutex_clean_up(&buffer_pool->mutex);
335 struct aws_allocator *base = buffer_pool->base_allocator;
336 aws_mem_release(base, buffer_pool);
337 aws_explicit_aligned_allocator_destroy(base);
338 }
339
340 static void s_buffer_pool_trim_special_blocks_synced(struct aws_s3_default_buffer_pool *buffer_pool) {
341 /* Trim special blocks */
342 for (struct aws_hash_iter iter = aws_hash_iter_begin(&buffer_pool->special_blocks); !aws_hash_iter_done(&iter);
343 aws_hash_iter_next(&iter)) {
344 struct s3_special_block_list *special_list = iter.element.value;
345
346 for (size_t i = 0; i < aws_array_list_length(&special_list->blocks);) {
347 struct s3_buffer_pool_block *block;
348 aws_array_list_get_at_ptr(&special_list->blocks, (void **)&block, i);
349
350 if (block->alloc_bit_mask == 0) {
351 /* If the block is marked as not being used, free it. */
352 buffer_pool->special_blocks_allocated -= block->block_size;
353 aws_mem_release(buffer_pool->base_allocator, block->block_ptr);
354 aws_array_list_erase(&special_list->blocks, i);
355 /* do not increment since we just released element */
356 } else {
357 ++i;
358 }
359 }
360 if (aws_array_list_length(&special_list->blocks) == 0 && buffer_pool->special_blocks_reserved == 0 &&
361 !buffer_pool->force_keeping_special_blocks) {
362 /* Remove the element iter points to as it's not being used. */
363 aws_hash_iter_delete(&iter, true);
364 }
365 }
366 }
367
368 static void s_buffer_pool_trim_synced(struct aws_s3_default_buffer_pool *buffer_pool) {
369 /* Trim primary blocks */
370 for (size_t i = 0; i < aws_array_list_length(&buffer_pool->blocks);) {
371 struct s3_buffer_pool_block *block;
372 aws_array_list_get_at_ptr(&buffer_pool->blocks, (void **)&block, i);
373
374 if (block->alloc_bit_mask == 0) {
375 /* If the block is marked as not being used, free it. */
376 buffer_pool->primary_allocated -= block->block_size;
377 aws_mem_release(buffer_pool->base_allocator, block->block_ptr);
378 aws_array_list_erase(&buffer_pool->blocks, i);
379 /* do not increment since we just released element */
380 } else {
381 ++i;
382 }
383 }
384 s_buffer_pool_trim_special_blocks_synced(buffer_pool);
385 }
386
387 void aws_s3_default_buffer_pool_trim(struct aws_s3_buffer_pool *buffer_pool) {
388 struct aws_s3_default_buffer_pool *pool = buffer_pool->impl;
389 aws_mutex_lock(&pool->mutex);
390 s_buffer_pool_trim_synced(pool);
391 aws_mutex_unlock(&pool->mutex);
392 }
393
394 struct aws_s3_default_buffer_ticket *s_try_reserve_synced(
395 struct aws_s3_buffer_pool *buffer_pool,
396 struct aws_s3_buffer_pool_reserve_meta meta);
397
398 static void s_aws_ticket_wrapper_destroy(void *data) {
399 struct aws_s3_buffer_ticket *ticket_wrapper = data;
400 struct aws_s3_default_buffer_ticket *ticket = ticket_wrapper->impl;
401 struct aws_s3_buffer_pool *pool = ticket->pool;
402 struct aws_s3_default_buffer_pool *buffer_pool = pool->impl;
403
404 /* Initialize lists for pending reserve management */
405 struct aws_linked_list pending_reserves_to_remove;
406 aws_linked_list_init(&pending_reserves_to_remove);
407
408 struct aws_linked_list pending_reserves_to_complete;
409 aws_linked_list_init(&pending_reserves_to_complete);
410 struct aws_linked_list_node *node = NULL;
411
412 /* BEGIN CRITICAL SECTION */
413 {
414 aws_mutex_lock(&buffer_pool->mutex);
415 struct s3_special_block_list *special_list = NULL;
416
417 if (ticket->ptr == NULL) {
418 /* Ticket was never used, make sure to clean up reserved count. */
419 switch (ticket->reserved_from) {
420 case AWS_S3_BUFFER_POOL_RESERVED_FROM_SPECIAL:
421 buffer_pool->special_blocks_reserved -= ticket->size;
422 break;
423 case AWS_S3_BUFFER_POOL_RESERVED_FROM_PRIMARY:
424 buffer_pool->primary_reserved -= ticket->size;
425 break;
426 case AWS_S3_BUFFER_POOL_RESERVED_FROM_SECONDARY:
427 buffer_pool->secondary_reserved -= ticket->size;
428 break;
429 default:
430 AWS_ASSERT(false); /* someone forgot to update this after adding new member. */
431 }
432 } else {
433 /* Handle special block returns */
434 if (ticket->reserved_from == AWS_S3_BUFFER_POOL_RESERVED_FROM_SPECIAL) {
435 struct aws_hash_element *elem = NULL;
436 aws_hash_table_find(&buffer_pool->special_blocks, (void *)ticket->size, &elem);
437 if (elem) {
438 special_list = elem->value;
439
440 bool found = false;
441 for (size_t i = 0; i < aws_array_list_length(&special_list->blocks); ++i) {
442 struct s3_buffer_pool_block *block;
443 aws_array_list_get_at_ptr(&special_list->blocks, (void **)&block, i);
444 if (block->block_ptr == ticket->ptr) {
445 /* Make sure the block is marked as used. */
446 if (block->alloc_bit_mask == UINT16_MAX) {
447 block->alloc_bit_mask = 0;
448 found = true;
449 break;
450 }
451 }
452 }
453 /* Make sure we do find where the ticket buffer from the list. */
454 if (found) {
455 buffer_pool->special_blocks_used -= ticket->size;
456 }
457 }
458 } else if (ticket->reserved_from == AWS_S3_BUFFER_POOL_RESERVED_FROM_PRIMARY) {
459
460 size_t chunks_used = ticket->size / buffer_pool->chunk_size;
461 if (ticket->size % buffer_pool->chunk_size != 0) {
462 ++chunks_used; /* round up */
463 }
464
465 bool found = false;
466 for (size_t i = 0; i < aws_array_list_length(&buffer_pool->blocks); ++i) {
467 struct s3_buffer_pool_block *block;
468 aws_array_list_get_at_ptr(&buffer_pool->blocks, (void **)&block, i);
469
470 if (block->block_ptr <= ticket->ptr && block->block_ptr + block->block_size > ticket->ptr) {
471 size_t alloc_i = (ticket->ptr - block->block_ptr) / buffer_pool->chunk_size;
472
473 block->alloc_bit_mask = s_clear_bits(block->alloc_bit_mask, alloc_i, chunks_used);
474 buffer_pool->primary_used -= ticket->size;
475
476 found = true;
477 break;
478 }
479 }
480
481 AWS_FATAL_ASSERT(found);
482
483 if (ticket->forced) {
484 buffer_pool->forced_used -= ticket->size;
485 }
486 } else if (ticket->reserved_from == AWS_S3_BUFFER_POOL_RESERVED_FROM_SECONDARY) {
487 aws_mem_release(buffer_pool->base_allocator, ticket->ptr);
488 buffer_pool->secondary_used -= ticket->size;
489
490 if (ticket->forced) {
491 buffer_pool->forced_used -= ticket->size;
492 }
493 } else {
494 AWS_ASSERT(false); /* someone forgot to update this after adding new member. */
495 }
496 }
497 aws_mem_release(buffer_pool->base_allocator, ticket);
498 aws_mem_release(buffer_pool->base_allocator, ticket_wrapper);
499
500 /* Capture all the pending reserves that are done (currently can only happen when request is canceled, which
501 * cancels pending futures) */
502 node = aws_linked_list_begin(&buffer_pool->pending_reserves);
503 while (node != aws_linked_list_end(&buffer_pool->pending_reserves)) {
504 struct s3_pending_reserve *pending_reserve = AWS_CONTAINER_OF(node, struct s3_pending_reserve, node);
505 struct aws_linked_list_node *current_node = node;
506 node = aws_linked_list_next(node);
507 if (aws_future_s3_buffer_ticket_is_done(pending_reserve->ticket_future)) {
508 AWS_FATAL_ASSERT(
509 aws_future_s3_buffer_ticket_get_error(pending_reserve->ticket_future) != AWS_OP_SUCCESS);
510 aws_linked_list_remove(current_node);
511 aws_linked_list_push_back(&pending_reserves_to_remove, current_node);
512 }
513 }
514 /* Capture all the pending reserves that can be completed. They will actually be completed once outside the
515 * mutex.
516 */
517 while (!aws_linked_list_empty(&buffer_pool->pending_reserves)) {
518 node = aws_linked_list_front(&buffer_pool->pending_reserves);
519 struct s3_pending_reserve *pending_reserve = AWS_CONTAINER_OF(node, struct s3_pending_reserve, node);
520
521 pending_reserve->ticket = s_try_reserve_synced(pool, pending_reserve->meta);
522
523 if (pending_reserve->ticket != NULL) {
524 aws_linked_list_pop_front(&buffer_pool->pending_reserves);
525 aws_linked_list_push_back(&pending_reserves_to_complete, node);
526 } else {
527 break;
528 }
529 }
530
531 aws_mutex_unlock(&buffer_pool->mutex);
532 }
533 /* END CRITICAL SECTION */
534
535 /* release completed pending nodes outside of lock to avoid any deadlocks */
536 while (!aws_linked_list_empty(&pending_reserves_to_remove)) {
537 node = aws_linked_list_front(&pending_reserves_to_remove);
538 struct s3_pending_reserve *pending = AWS_CONTAINER_OF(node, struct s3_pending_reserve, node);
539 aws_future_s3_buffer_ticket_release(pending->ticket_future);
540 aws_linked_list_pop_front(&pending_reserves_to_remove);
541 aws_mem_release(buffer_pool->base_allocator, pending);
542 }
543
544 /* fill the next pending future */
545 while (!aws_linked_list_empty(&pending_reserves_to_complete)) {
546 node = aws_linked_list_front(&pending_reserves_to_complete);
547 struct s3_pending_reserve *pending = AWS_CONTAINER_OF(node, struct s3_pending_reserve, node);
548
549 struct aws_s3_buffer_ticket *new_ticket_wrapper = s_wrap_default_ticket(pending->ticket);
550 aws_future_s3_buffer_ticket_set_result_by_move(pending->ticket_future, &new_ticket_wrapper);
551
552 aws_future_s3_buffer_ticket_release(pending->ticket_future);
553 aws_linked_list_pop_front(&pending_reserves_to_complete);
554 aws_mem_release(buffer_pool->base_allocator, pending);
555 }
556 }
557
558 static bool s_should_trim_for_reserve_synced(
559 bool from_special,
560 size_t to_reserve,
561 struct aws_s3_default_buffer_pool *buffer_pool,
562 size_t overall_taken) {
563 if (from_special || to_reserve <= buffer_pool->primary_size_cutoff) {
564 /* Only trim when it will be allocated from secondary, which is directly from malloc. */
565 return false;
566 }
567
568 size_t total_allocation_needs = 0;
569 if (aws_add_size_checked(overall_taken, to_reserve, &total_allocation_needs)) {
570 /* Will overflow, ignores it, which should not happen. */
571 return false;
572 }
573 if (total_allocation_needs < buffer_pool->mem_limit) {
574 /* No need to trim as we still have space to allocate the new block. */
575 return false;
576 }
577
578 size_t primary_overallocation = aws_sub_size_saturating(buffer_pool->primary_allocated, buffer_pool->primary_used);
579 /* Reserved can be more tha allocated */
580 primary_overallocation = aws_sub_size_saturating(primary_overallocation, buffer_pool->primary_reserved);
581 size_t special_overallocation =
582 aws_sub_size_saturating(buffer_pool->special_blocks_allocated, buffer_pool->special_blocks_used);
583 /* Reserved can be more tha allocated */
584 special_overallocation = aws_sub_size_saturating(special_overallocation, buffer_pool->special_blocks_reserved);
585
586 size_t total_overallocation = aws_add_size_saturating(special_overallocation, primary_overallocation);
587 if (total_overallocation < to_reserve) {
588 /* If the overallocation is less than the new block, trim it won't help, skip trimming. */
589 return false;
590 }
591
592 return true;
593 }
594
595 struct aws_s3_default_buffer_ticket *s_try_reserve_synced(
596 struct aws_s3_buffer_pool *buffer_pool_wrapper,
597 struct aws_s3_buffer_pool_reserve_meta meta) {
598
599 struct aws_s3_default_buffer_ticket *ticket = NULL;
600 struct aws_s3_default_buffer_pool *buffer_pool = buffer_pool_wrapper->impl;
601
602 size_t overall_taken = buffer_pool->primary_used + buffer_pool->primary_reserved + buffer_pool->secondary_used +
603 buffer_pool->secondary_reserved + buffer_pool->special_blocks_reserved +
604 buffer_pool->special_blocks_used;
605 struct aws_hash_element *elem = NULL;
606 aws_hash_table_find(&buffer_pool->special_blocks, (void *)meta.size, &elem);
607 bool from_special = elem != NULL;
608
609 /*
610 * If we are allocating from secondary and there is unused space in
611 * the blocks, trim the blocks in hopes we can free up enough memory.
612 * TODO: something smarter, like partial trim?
613 */
614 if (s_should_trim_for_reserve_synced(from_special, meta.size, buffer_pool, overall_taken)) {
615 s_buffer_pool_trim_synced(buffer_pool);
616 overall_taken = buffer_pool->primary_used + buffer_pool->primary_reserved + buffer_pool->secondary_used +
617 buffer_pool->secondary_reserved + buffer_pool->special_blocks_reserved +
618 buffer_pool->special_blocks_used;
619 }
620
621 /* Don't let forced buffers account for 100% of the memory limit */
622 const size_t max_impact_of_forced_on_limit =
623 (size_t)(buffer_pool->mem_limit * (s_max_impact_of_forced_buffers_on_memory_limit_as_percentage / 100.0));
624 if (buffer_pool->forced_used > max_impact_of_forced_on_limit) {
625 overall_taken = (overall_taken - buffer_pool->forced_used) + max_impact_of_forced_on_limit;
626 }
627
628 if ((meta.size + overall_taken) <= buffer_pool->mem_limit) {
629 ticket = aws_mem_calloc(buffer_pool->base_allocator, 1, sizeof(struct aws_s3_default_buffer_ticket));
630 ticket->size = meta.size;
631 ticket->pool = buffer_pool_wrapper;
632
633 /* Check if this is a special-sized allocation */
634 if (from_special) {
635 ticket->reserved_from = AWS_S3_BUFFER_POOL_RESERVED_FROM_SPECIAL;
636 buffer_pool->special_blocks_reserved += meta.size;
637 } else if (meta.size <= buffer_pool->primary_size_cutoff) {
638 /* This needs to be smarter. Currently if primary req size is below limit, it will allocate full block,
639 which can be above limit. */
640 if (meta.size <= buffer_pool->primary_size_min_cutoff) {
641 ticket->reserved_from = AWS_S3_BUFFER_POOL_RESERVED_FROM_SECONDARY;
642 buffer_pool->secondary_reserved += meta.size;
643 } else {
644 if ((buffer_pool->primary_used + buffer_pool->primary_reserved + meta.size) >
645 buffer_pool->primary_allocated &&
646 (overall_taken + buffer_pool->block_size) > buffer_pool->mem_limit) {
647 /* allocating this from primary would result in exceeding mem limit if new block is created,
648 so allocate from secondary instead. */
649 ticket->reserved_from = AWS_S3_BUFFER_POOL_RESERVED_FROM_SECONDARY;
650 buffer_pool->secondary_reserved += meta.size;
651 } else {
652 ticket->reserved_from = AWS_S3_BUFFER_POOL_RESERVED_FROM_PRIMARY;
653 buffer_pool->primary_reserved += meta.size;
654 }
655 }
656 } else {
657 ticket->reserved_from = AWS_S3_BUFFER_POOL_RESERVED_FROM_SECONDARY;
658 buffer_pool->secondary_reserved += meta.size;
659 }
660 }
661
662 return ticket;
663 }
664
665 struct aws_future_s3_buffer_ticket *aws_s3_default_buffer_pool_reserve(
666 struct aws_s3_buffer_pool *buffer_pool_wrapper,
667 struct aws_s3_buffer_pool_reserve_meta meta) {
668 AWS_PRECONDITION(buffer_pool_wrapper);
669
670 struct aws_s3_default_buffer_pool *buffer_pool = buffer_pool_wrapper->impl;
671
672 AWS_FATAL_ASSERT(meta.size != 0);
673 AWS_FATAL_ASSERT(meta.size <= buffer_pool->mem_limit);
674
675 aws_mutex_lock(&buffer_pool->mutex);
676
677 struct aws_s3_default_buffer_ticket *ticket = NULL;
678 if (meta.can_block) {
679 ticket = aws_mem_calloc(buffer_pool->base_allocator, 1, sizeof(struct aws_s3_default_buffer_ticket));
680 ticket->size = meta.size;
681 ticket->forced = true;
682 ticket->pool = buffer_pool_wrapper;
683
684 if (meta.size <= buffer_pool->primary_size_cutoff && meta.size >= buffer_pool->primary_size_min_cutoff) {
685 ticket->reserved_from = AWS_S3_BUFFER_POOL_RESERVED_FROM_PRIMARY;
686 } else {
687 ticket->reserved_from = AWS_S3_BUFFER_POOL_RESERVED_FROM_SECONDARY;
688 }
689
690 } else {
691 ticket = s_try_reserve_synced(buffer_pool_wrapper, meta);
692 }
693
694 struct aws_future_s3_buffer_ticket *future = aws_future_s3_buffer_ticket_new(buffer_pool->base_allocator);
695 if (ticket != NULL) {
696 struct aws_s3_buffer_ticket *ticket_wrapper = s_wrap_default_ticket(ticket);
697 aws_future_s3_buffer_ticket_set_result_by_move(future, &ticket_wrapper);
698 } else {
699 struct s3_pending_reserve *pending_reserve =
700 aws_mem_calloc(buffer_pool->base_allocator, 1, sizeof(struct s3_pending_reserve));
701
702 pending_reserve->meta = meta;
703 pending_reserve->ticket_future = future;
704 aws_future_s3_buffer_ticket_acquire(pending_reserve->ticket_future);
705
706 aws_linked_list_push_back(&buffer_pool->pending_reserves, &pending_reserve->node);
707 }
708
709 aws_mutex_unlock(&buffer_pool->mutex);
710
711 return future;
712 }
713
714 static uint8_t *s_primary_acquire_synced(
715 struct aws_s3_default_buffer_pool *buffer_pool,
716 struct aws_s3_default_buffer_ticket *ticket) {
717
718 uint8_t *alloc_ptr = NULL;
719
720 size_t chunks_needed = ticket->size / buffer_pool->chunk_size;
721 if (ticket->size % buffer_pool->chunk_size != 0) {
722 ++chunks_needed; /* round up */
723 }
724 ticket->chunks_used = chunks_needed;
725
726 /* Look for space in existing blocks */
727 for (size_t i = 0; i < aws_array_list_length(&buffer_pool->blocks); ++i) {
728 struct s3_buffer_pool_block *block;
729 aws_array_list_get_at_ptr(&buffer_pool->blocks, (void **)&block, i);
730
731 for (size_t chunk_i = 0; chunk_i < s_chunks_per_block - chunks_needed + 1; ++chunk_i) {
732 if (!s_check_bits(block->alloc_bit_mask, chunk_i, chunks_needed)) {
733 alloc_ptr = block->block_ptr + chunk_i * buffer_pool->chunk_size;
734 block->alloc_bit_mask = s_set_bits(block->alloc_bit_mask, chunk_i, chunks_needed);
735 AWS_LOGF_INFO(AWS_LS_S3_CLIENT, "Reusing existing primary block %zu", i);
736 goto on_allocated;
737 }
738 }
739 }
740
741 /* No space available. Allocate new block. */
742 struct s3_buffer_pool_block block;
743 block.alloc_bit_mask = s_set_bits(0, 0, chunks_needed);
744 block.block_ptr = aws_mem_acquire(buffer_pool->base_allocator, buffer_pool->block_size);
745 block.block_size = buffer_pool->block_size;
746 aws_array_list_push_back(&buffer_pool->blocks, &block);
747 alloc_ptr = block.block_ptr;
748
749 AWS_LOGF_INFO(
750 AWS_LS_S3_CLIENT,
751 "Allocated primary block: size=%zu, total_allocated=%zu",
752 buffer_pool->block_size,
753 buffer_pool->primary_allocated);
754
755 buffer_pool->primary_allocated += buffer_pool->block_size;
756
757 on_allocated:
758 buffer_pool->primary_used += ticket->size;
759
760 /* forced buffers acquire immediately, without reserving first */
761 if (ticket->forced == false) {
762 buffer_pool->primary_reserved -= ticket->size;
763 }
764
765 return alloc_ptr;
766 }
767
768 static struct aws_byte_buf s_acquire_buffer_synced(
769 struct aws_s3_default_buffer_pool *buffer_pool_wrapper,
770 struct aws_s3_default_buffer_ticket *ticket);
771
772 struct aws_byte_buf aws_s3_default_buffer_pool_acquire_buffer(
773 struct aws_s3_buffer_pool *buffer_pool_wrapper,
774 struct aws_s3_default_buffer_ticket *ticket) {
775
776 AWS_PRECONDITION(buffer_pool_wrapper);
777 AWS_PRECONDITION(ticket);
778
779 struct aws_s3_default_buffer_pool *buffer_pool = buffer_pool_wrapper->impl;
780
781 if (ticket->ptr != NULL) {
782 return aws_byte_buf_from_empty_array(ticket->ptr, ticket->size);
783 }
784
785 aws_mutex_lock(&buffer_pool->mutex);
786 struct aws_byte_buf buf = s_acquire_buffer_synced(buffer_pool, ticket);
787 aws_mutex_unlock(&buffer_pool->mutex);
788
789 return buf;
790 }
791
792 static struct aws_byte_buf s_acquire_buffer_synced(
793 struct aws_s3_default_buffer_pool *buffer_pool,
794 struct aws_s3_default_buffer_ticket *ticket) {
795
796 AWS_PRECONDITION(ticket->ptr == NULL);
797
798 AWS_LOGF_INFO(
799 AWS_LS_S3_CLIENT, "s_acquire_buffer_synced: size=%zu, reserved_from=%u", ticket->size, ticket->reserved_from);
800
801 /* Check if this is a special-sized allocation */
802 if (ticket->reserved_from == AWS_S3_BUFFER_POOL_RESERVED_FROM_SPECIAL) {
803 struct aws_hash_element *elem = NULL;
804 aws_hash_table_find(&buffer_pool->special_blocks, (void *)ticket->size, &elem);
805 AWS_FATAL_ASSERT(elem != NULL);
806 struct s3_special_block_list *special_list = elem->value;
807 AWS_LOGF_INFO(
808 AWS_LS_S3_CLIENT,
809 "Special block acquire: size=%zu, num_blocks=%zu",
810 ticket->size,
811 aws_array_list_length(&special_list->blocks));
812 /* Look for space in existing blocks */
813 for (size_t i = 0; i < aws_array_list_length(&special_list->blocks); ++i) {
814 struct s3_buffer_pool_block *block;
815 aws_array_list_get_at_ptr(&special_list->blocks, (void **)&block, i);
816 AWS_LOGF_INFO(AWS_LS_S3_CLIENT, "Checking special block %zu: alloc_bit_mask=%u", i, block->alloc_bit_mask);
817 /* Try to find if any block in the list is not used. */
818 if (block->alloc_bit_mask == 0) {
819 block->alloc_bit_mask = UINT16_MAX;
820 ticket->ptr = block->block_ptr;
821 AWS_ASSERT(ticket->size == block->block_size);
822 AWS_LOGF_INFO(AWS_LS_S3_CLIENT, "Reusing existing special block %zu", i);
823 break;
824 }
825 }
826 if (!ticket->ptr) {
827 /* No available blocks, allocate a new one. */
828 struct s3_buffer_pool_block block;
829 block.alloc_bit_mask = UINT16_MAX;
830 block.block_ptr = aws_mem_acquire(buffer_pool->base_allocator, special_list->buffer_size);
831 block.block_size = special_list->buffer_size;
832 aws_array_list_push_back(&special_list->blocks, &block);
833 ticket->ptr = block.block_ptr;
834 buffer_pool->special_blocks_allocated += special_list->buffer_size;
835 AWS_LOGF_INFO(
836 AWS_LS_S3_CLIENT,
837 "Allocated special block: size=%zu, total_allocated=%zu",
838 special_list->buffer_size,
839 buffer_pool->special_blocks_allocated);
840 }
841 buffer_pool->special_blocks_used += ticket->size;
842 buffer_pool->special_blocks_reserved -= ticket->size;
843 } else if (ticket->reserved_from == AWS_S3_BUFFER_POOL_RESERVED_FROM_PRIMARY) {
844 ticket->ptr = s_primary_acquire_synced(buffer_pool, ticket);
845 } else {
846 AWS_ASSERT(ticket->reserved_from == AWS_S3_BUFFER_POOL_RESERVED_FROM_SECONDARY);
847 ticket->ptr = aws_mem_acquire(buffer_pool->base_allocator, ticket->size);
848 buffer_pool->secondary_used += ticket->size;
849
850 /* forced buffers acquire immediately, without reserving first */
851 if (ticket->forced == false) {
852 buffer_pool->secondary_reserved -= ticket->size;
853 }
854 }
855
856 if (ticket->forced) {
857 buffer_pool->forced_used += ticket->size;
858 }
859
860 return aws_byte_buf_from_empty_array(ticket->ptr, ticket->size);
861 }
862
863 struct aws_s3_default_buffer_pool_usage_stats aws_s3_default_buffer_pool_get_usage(
864 struct aws_s3_buffer_pool *buffer_pool_wrapper) {
865
866 struct aws_s3_default_buffer_pool *buffer_pool = buffer_pool_wrapper->impl;
867 aws_mutex_lock(&buffer_pool->mutex);
868
869 struct aws_s3_default_buffer_pool_usage_stats ret = (struct aws_s3_default_buffer_pool_usage_stats){
870 .mem_limit = buffer_pool->mem_limit,
871 .primary_cutoff = buffer_pool->primary_size_cutoff,
872 .primary_min_cutoff = buffer_pool->primary_size_min_cutoff,
873 .primary_allocated = buffer_pool->primary_allocated,
874 .primary_used = buffer_pool->primary_used,
875 .primary_reserved = buffer_pool->primary_reserved,
876 .primary_num_blocks = aws_array_list_length(&buffer_pool->blocks),
877 .secondary_used = buffer_pool->secondary_used,
878 .secondary_reserved = buffer_pool->secondary_reserved,
879 .special_blocks_allocated = buffer_pool->special_blocks_allocated,
880 .special_blocks_num = aws_hash_table_get_entry_count(&buffer_pool->special_blocks),
881 .special_blocks_reserved = buffer_pool->special_blocks_reserved,
882 .special_blocks_used = buffer_pool->special_blocks_used,
883 .forced_used = buffer_pool->forced_used,
884 };
885
886 aws_mutex_unlock(&buffer_pool->mutex);
887 return ret;
888 }
889
890 static int s_default_pool_add_special_size(struct aws_s3_buffer_pool *buffer_pool_wrapper, size_t buffer_size) {
891 AWS_PRECONDITION(buffer_pool_wrapper);
892
893 struct aws_s3_default_buffer_pool *buffer_pool = buffer_pool_wrapper->impl;
894
895 if (buffer_size <= buffer_pool->primary_size_cutoff) {
896 /* For size that can fit in the primary allocation, there is no needs for a special list. */
897 AWS_LOGF_WARN(
898 AWS_LS_S3_CLIENT,
899 "skip creating the special size list, use the primary allocation will meet the requirement.");
900 return AWS_OP_SUCCESS;
901 }
902 aws_mutex_lock(&buffer_pool->mutex);
903
904 /* Check if this size already exists */
905 struct aws_hash_element *elem = NULL;
906 aws_hash_table_find(&buffer_pool->special_blocks, (void *)buffer_size, &elem);
907
908 if (elem != NULL) {
909 /* Already exists, nothing to do */
910 aws_mutex_unlock(&buffer_pool->mutex);
911 return AWS_OP_SUCCESS;
912 }
913
914 /* Create new special block list */
915 struct s3_special_block_list *special_list =
916 aws_mem_calloc(buffer_pool->base_allocator, 1, sizeof(struct s3_special_block_list));
917 special_list->allocator = buffer_pool->base_allocator;
918 special_list->buffer_size = buffer_size;
919
920 /* Initialize blocks array and pending reserves list */
921 if (aws_array_list_init_dynamic(
922 &special_list->blocks, buffer_pool->base_allocator, 0, sizeof(struct s3_buffer_pool_block))) {
923 aws_mem_release(buffer_pool->base_allocator, special_list);
924 aws_mutex_unlock(&buffer_pool->mutex);
925 return AWS_OP_ERR;
926 }
927
928 /* Add to hash table */
929 if (aws_hash_table_put(&buffer_pool->special_blocks, (void *)buffer_size, special_list, NULL)) {
930 aws_array_list_clean_up(&special_list->blocks);
931 aws_mem_release(buffer_pool->base_allocator, special_list);
932 aws_mutex_unlock(&buffer_pool->mutex);
933 return AWS_OP_ERR;
934 }
935
936 aws_mutex_unlock(&buffer_pool->mutex);
937
938 AWS_LOGF_INFO(AWS_LS_S3_CLIENT, "Added special block size: %zu bytes", buffer_size);
939
940 return AWS_OP_SUCCESS;
941 }
942
943 static void s_default_pool_release_special_size(struct aws_s3_buffer_pool *buffer_pool_wrapper, size_t buffer_size) {
944 AWS_LOGF_INFO(AWS_LS_S3_CLIENT, "Released special block size: %zu bytes. Trigger trim.", buffer_size);
945 /* Rely on trim to clean up instead of force it. */
946 /* TODO: maybe a better lifetime management. */
947 struct aws_s3_default_buffer_pool *pool = buffer_pool_wrapper->impl;
948 aws_mutex_lock(&pool->mutex);
949 /* Instead of trim the whole pool, just trim for the special blocks. */
950 s_buffer_pool_trim_special_blocks_synced(pool);
951 aws_mutex_unlock(&pool->mutex);
952 }
953
954 static uint64_t s_default_pool_derive_aligned_buffer_size(
955 struct aws_s3_buffer_pool *buffer_pool_wrapper,
956 uint64_t size) {
957 AWS_PRECONDITION(buffer_pool_wrapper);
958
959 struct aws_s3_default_buffer_pool *buffer_pool = buffer_pool_wrapper->impl;
960
961 /* If chunk_size is 0, buffer reuse is disabled, return size unchanged */
962 if (buffer_pool->chunk_size == 0) {
963 return size;
964 }
965
966 uint64_t chunks_needed = size / buffer_pool->chunk_size;
967 if (size % buffer_pool->chunk_size != 0) {
968 ++chunks_needed; /* round up */
969 }
970 /* Return the aligned size */
971 return chunks_needed * buffer_pool->chunk_size;
972 }
973
974 enum aws_s3_default_buffer_pool_reserved_from aws_s3_default_buffer_pool_get_ticket_reserved_from(
975 struct aws_s3_default_buffer_ticket *ticket) {
976 AWS_FATAL_ASSERT(ticket);
977 return ticket->reserved_from;
978 }