-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathpool.rs
More file actions
3179 lines (2831 loc) · 123 KB
/
pool.rs
File metadata and controls
3179 lines (2831 loc) · 123 KB
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Buffer pool for efficient I/O operations.
//!
//! Provides pooled, aligned buffers that can be reused to reduce allocation
//! overhead. Buffer alignment is configurable: use page alignment for storage I/O
//! (required for direct I/O and DMA), or cache-line alignment for network I/O
//! (reduces fragmentation).
//!
//! # Thread Safety
//!
//! [`BufferPool`] is `Send + Sync` and can be safely shared across threads.
//! Allocation and deallocation use atomic counters together with a bounded
//! lock-free global freelist plus per-thread caches.
//!
//! # Pool Lifecycle
//!
//! Tracked buffers held by pooled views or cached in thread-local bins keep a
//! strong reference to the originating size class. Buffers can outlive the
//! public [`BufferPool`] handle and still return to their original size class.
//! - Untracked fallback allocations store no class reference and deallocate
//! directly when dropped.
//! - Requests smaller than [`BufferPoolConfig::pool_min_size`] bypass pooling
//! entirely and return untracked aligned allocations from both
//! [`BufferPool::try_alloc`] and [`BufferPool::alloc`].
//! - Dropping [`BufferPool`] drains only the shared global freelists, pooled
//! views and buffers cached in a live thread's local cache can keep their
//! size class alive until they are dropped or the thread exits.
//!
//! # Size Classes
//!
//! Buffers are organized into power-of-two size classes from `min_size` to
//! `max_size`. For example, with `min_size = 4096` and `max_size = 32768`:
//! - Class 0: 4096 bytes
//! - Class 1: 8192 bytes
//! - Class 2: 16384 bytes
//! - Class 3: 32768 bytes
//!
//! Allocation requests are rounded up to the next size class. Requests larger
//! than `max_size` return [`PoolError::Oversized`] from [`BufferPool::try_alloc`],
//! or fall back to an untracked aligned heap allocation from [`BufferPool::alloc`].
//!
//! # Cache Structure
//!
//! Each size class uses a two-level allocator:
//! - a small per-thread local cache for steady-state same-thread reuse
//! - a shared global freelist for refill and spill between threads
//!
//! When a local cache misses, the pool refills a small batch from the global
//! freelist before attempting to create a new tracked buffer. Returned buffers
//! first try to re-enter the dropping thread's local cache, spilling a bounded
//! batch back to the global freelist if needed.
use super::{freelist::Freelist, IoBufMut};
use crate::{
iobuf::buffer::{PooledBufMut, PooledBuffer},
telemetry::metrics::{raw, Counter, CounterFamily, EncodeLabelSet, GaugeFamily, Register},
};
use commonware_utils::{NZUsize, NZU32};
use crossbeam_utils::CachePadded;
use std::{
alloc::Layout,
cell::{Cell, UnsafeCell},
mem::{align_of, MaybeUninit},
num::{NonZeroU32, NonZeroUsize},
ptr,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
};
/// Minimum thread-local cache capacity required before refill/spill batches.
///
/// Below this threshold TLS still provides same-thread locality, but batching
/// would degrade to single-buffer moves and add policy complexity without
/// amortizing shared-queue traffic.
const MIN_TLS_BATCH_CAPACITY: usize = 4;
/// Error returned when buffer pool allocation fails.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PoolError {
/// The requested capacity exceeds the maximum buffer size.
Oversized,
/// The pool is exhausted for the required size class.
Exhausted,
}
impl std::fmt::Display for PoolError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Oversized => write!(f, "requested capacity exceeds maximum buffer size"),
Self::Exhausted => write!(f, "pool exhausted for required size class"),
}
}
}
impl std::error::Error for PoolError {}
/// Returns the system page size.
///
/// On Unix systems, queries the actual page size via `sysconf`.
/// On other systems (Windows), defaults to 4KB.
#[cfg(unix)]
fn page_size() -> usize {
// SAFETY: sysconf is safe to call.
let size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
if size <= 0 {
4096 // Safe fallback if sysconf fails
} else {
size as usize
}
}
#[cfg(not(unix))]
#[allow(clippy::missing_const_for_fn)]
fn page_size() -> usize {
4096
}
/// Returns the cache line size for the current architecture.
///
/// Matches the architecture-specific alignment used by
/// [`crossbeam_utils::CachePadded`].
const fn cache_line_size() -> usize {
align_of::<CachePadded<u8>>()
}
/// Policy for sizing each thread's cache within a buffer pool size class.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BufferPoolThreadCacheConfig {
/// Enable thread-local caching.
///
/// `None` derives the per-thread cache size from the pool's per-class
/// capacity and expected parallelism, reserving about half of each class
/// for the shared freelist. Small per-class budgets may resolve to zero,
/// disabling thread-local caching so free buffers do not become stranded in
/// other threads.
///
/// `Some(n)` uses an exact per-thread cache size for every size class.
Enabled(Option<NonZeroUsize>),
/// Disable thread-local caching and route all reuse through the shared global freelist.
Disabled,
}
/// Configuration for a buffer pool.
#[derive(Debug, Clone)]
pub struct BufferPoolConfig {
/// Minimum request size that should use pooled allocation.
///
/// Requests smaller than this bypass the pool and use direct aligned
/// allocation instead. A value of `0` means all eligible requests use the
/// pool.
pub pool_min_size: usize,
/// Minimum buffer size. Must be >= alignment and a power of two.
pub min_size: NonZeroUsize,
/// Maximum buffer size. Must be a power of two and >= min_size.
pub max_size: NonZeroUsize,
/// Maximum number of buffers per size class.
///
/// Size-class slots are identified by `u32`, so the per-class capacity is
/// capped by this type.
pub max_per_class: NonZeroU32,
/// Whether to create every tracked buffer during pool construction.
///
/// When enabled, each size class creates `max_per_class` buffers and parks
/// them in the class-global freelist before the pool is returned. This
/// moves allocation cost to startup and makes the first reuse path avoid
/// heap allocation.
pub prefill: bool,
/// Buffer alignment. Must be a power of two.
pub alignment: NonZeroUsize,
/// Expected number of threads concurrently accessing the pool.
///
/// This sizes the shared global freelist stripes. It is also used to derive
/// thread-cache capacity when the thread-cache policy is automatic, using
/// approximately half of [`Self::max_per_class`] divided across expected
/// threads.
pub parallelism: NonZeroUsize,
/// Policy for sizing the per-thread local cache in each size class.
///
/// By default, thread-cache capacity is derived from [`Self::parallelism`].
/// [`Self::with_thread_cache_capacity`] uses an exact per-thread cache size.
/// [`Self::with_thread_cache_disabled`] bypasses thread-local caches.
pub(crate) thread_cache_config: BufferPoolThreadCacheConfig,
}
impl BufferPoolConfig {
/// Network I/O preset: cache-line aligned, 1KB to 64KB buffers,
/// 4096 per class, not prefilled.
///
/// Network operations typically need multiple concurrent buffers per connection
/// (message, encoding, encryption) so we allow 4096 buffers per size class.
/// Cache-line alignment is used because network buffers don't require page
/// alignment for DMA, and smaller alignment reduces internal fragmentation.
pub const fn for_network() -> Self {
Self {
pool_min_size: 0,
min_size: NZUsize!(1024),
max_size: NZUsize!(128 * 1024),
max_per_class: NZU32!(4096),
prefill: false,
alignment: NZUsize!(1),
parallelism: NZUsize!(1),
thread_cache_config: BufferPoolThreadCacheConfig::Enabled(None),
}
}
/// Storage I/O preset: page-aligned, page_size to 8MB buffers, 64 per class,
/// not prefilled.
///
/// Page alignment is required for direct I/O and efficient DMA transfers.
pub fn for_storage() -> Self {
let page = NZUsize!(page_size());
Self {
pool_min_size: 0,
min_size: page,
max_size: NZUsize!(8 * 1024 * 1024),
max_per_class: NZU32!(64),
prefill: false,
alignment: NZUsize!(1),
parallelism: NZUsize!(1),
thread_cache_config: BufferPoolThreadCacheConfig::Enabled(None),
}
}
/// Returns a copy of this config with a new minimum request size that uses pooling.
pub const fn with_pool_min_size(mut self, pool_min_size: usize) -> Self {
self.pool_min_size = pool_min_size;
self
}
/// Returns a copy of this config with a new minimum buffer size.
pub const fn with_min_size(mut self, min_size: NonZeroUsize) -> Self {
self.min_size = min_size;
self
}
/// Returns a copy of this config with a new maximum buffer size.
pub const fn with_max_size(mut self, max_size: NonZeroUsize) -> Self {
self.max_size = max_size;
self
}
/// Returns a copy of this config with a new maximum number of buffers per size class.
pub const fn with_max_per_class(mut self, max_per_class: NonZeroU32) -> Self {
self.max_per_class = max_per_class;
self
}
/// Returns a copy of this config with a new expected parallelism.
///
/// This controls the minimum global-freelist stripe count, and controls
/// thread-cache capacity when the thread-cache policy is automatic. The
/// automatic policy reserves about half of each class for the global
/// freelist and divides the remaining capacity across expected threads.
pub const fn with_parallelism(mut self, parallelism: NonZeroUsize) -> Self {
self.parallelism = parallelism;
self
}
/// Returns a copy of this config with an explicit per-thread cache size.
///
/// Global-freelist striping is set separately by [`Self::with_parallelism`].
pub const fn with_thread_cache_capacity(mut self, thread_cache_capacity: NonZeroUsize) -> Self {
self.thread_cache_config =
BufferPoolThreadCacheConfig::Enabled(Some(thread_cache_capacity));
self
}
/// Returns a copy of this config with thread-local caching disabled.
///
/// Global-freelist striping is set separately by [`Self::with_parallelism`].
pub const fn with_thread_cache_disabled(mut self) -> Self {
self.thread_cache_config = BufferPoolThreadCacheConfig::Disabled;
self
}
/// Returns a copy of this config with a new prefill setting.
pub const fn with_prefill(mut self, prefill: bool) -> Self {
self.prefill = prefill;
self
}
/// Returns a copy of this config with a new alignment.
pub const fn with_alignment(mut self, alignment: NonZeroUsize) -> Self {
self.alignment = alignment;
self
}
/// Returns a copy of this config sized for an approximate tracked-memory budget.
///
/// This computes `max_per_class` as:
///
/// `ceil(budget_bytes / sum(size_class_bytes))`
///
/// where `size_class_bytes` includes every class from `min_size` to `max_size`.
/// This always rounds up to at least one buffer per size class, so the
/// resulting estimated capacity may exceed `budget_bytes`.
///
/// # Panics
///
/// - `min_size` is not a power of two
/// - `max_size` is not a power of two
/// - `max_size < min_size`
/// - the derived per-class capacity does not fit in `u32`.
pub fn with_budget_bytes(mut self, budget_bytes: NonZeroUsize) -> Self {
self.validate_size_class_bounds();
let mut class_bytes = 0usize;
let min_size = self.min_size.get();
for i in 0..Self::num_classes(min_size, self.max_size.get()) {
class_bytes = class_bytes.saturating_add(Self::class_size(min_size, i));
}
if class_bytes == 0 {
return self;
}
let max_per_class = u32::try_from(budget_bytes.get().div_ceil(class_bytes))
.expect("max_per_class must fit in u32 slot ids");
self.max_per_class =
NonZeroU32::new(max_per_class).expect("max_per_class must be non-zero");
self
}
/// Validates the size-class bounds, panicking on invalid values.
///
/// # Panics
///
/// - `min_size` is not a power of two
/// - `max_size` is not a power of two
/// - `max_size < min_size`
fn validate_size_class_bounds(&self) {
let min_size = self.min_size.get();
let max_size = self.max_size.get();
assert!(
min_size.is_power_of_two(),
"min_size must be a power of two"
);
assert!(
max_size.is_power_of_two(),
"max_size must be a power of two"
);
assert!(max_size >= min_size, "max_size must be >= min_size");
}
/// Validates the configuration, panicking on invalid values.
///
/// # Panics
///
/// - `alignment` is not a power of two
/// - `min_size` is not a power of two
/// - `max_size` is not a power of two
/// - `min_size < alignment`
/// - `max_size < min_size`
/// - `pool_min_size > min_size`
/// - explicit `thread_cache_capacity > max_per_class`
fn validate(&self) {
self.validate_size_class_bounds();
assert!(
self.alignment.is_power_of_two(),
"alignment must be a power of two"
);
assert!(
self.min_size >= self.alignment,
"min_size ({}) must be >= alignment ({})",
self.min_size,
self.alignment
);
assert!(
self.pool_min_size <= self.min_size.get(),
"pool_min_size ({}) must be <= min_size ({})",
self.pool_min_size,
self.min_size
);
if let BufferPoolThreadCacheConfig::Enabled(Some(thread_cache_capacity)) =
self.thread_cache_config
{
assert!(
thread_cache_capacity.get() <= self.max_per_class.get() as usize,
"thread_cache_capacity ({}) must be <= max_per_class ({})",
thread_cache_capacity,
self.max_per_class
);
}
}
/// Returns the number of size classes between validated bounds.
#[inline]
const fn num_classes(min_size: usize, max_size: usize) -> usize {
// Since sizes are powers of two, trailing zeros is the size-class
// exponent
(max_size.trailing_zeros() - min_size.trailing_zeros() + 1) as usize
}
/// Returns the buffer size for a validated size-class index.
#[inline]
const fn class_size(min_size: usize, index: usize) -> usize {
min_size << index
}
/// Resolves the effective per-thread cache size for each size class.
///
/// Derived capacities divide half of the class budget across the expected
/// parallelism so cross-thread reuse remains effective. Small class budgets
/// may resolve to zero.
fn resolve_thread_cache_capacity(&self) -> usize {
match self.thread_cache_config {
BufferPoolThreadCacheConfig::Enabled(None) => {
let max_per_class = self.max_per_class.get() as usize;
let effective_threads = self.parallelism.get().min(max_per_class);
max_per_class / (2 * effective_threads)
}
BufferPoolThreadCacheConfig::Enabled(Some(thread_cache_capacity)) => {
thread_cache_capacity.get()
}
BufferPoolThreadCacheConfig::Disabled => 0,
}
}
}
/// Label for buffer pool metrics, identifying the size class.
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
struct SizeClassLabel {
size_class: u64,
}
/// Metrics for the buffer pool.
struct PoolMetrics {
/// Number of tracked buffers created for the size class.
created: GaugeFamily<SizeClassLabel>,
/// Total number of failed allocations (pool exhausted).
exhausted_total: CounterFamily<SizeClassLabel>,
/// Total number of oversized allocation requests.
oversized_total: Counter,
}
impl PoolMetrics {
fn new(registry: &mut impl Register) -> Self {
Self {
created: registry.register(
"buffer_pool_created",
"Number of tracked buffers created for the pool",
raw::Family::default(),
),
exhausted_total: registry.register(
"buffer_pool_exhausted_total",
"Total number of failed allocations due to pool exhaustion",
raw::Family::default(),
),
oversized_total: registry.register(
"buffer_pool_oversized_total",
"Total number of allocation requests exceeding max buffer size",
raw::Counter::default(),
),
}
}
}
/// Per-size-class state.
///
/// Each class is a small two-level allocator:
/// - a shared global freelist for tracked buffers visible to all threads
/// - a per-thread local cache for same-thread reuse
///
/// The global freelist owns the allocation layout, slot reservation counter,
/// and parking cells for this class. A tracked buffer can be globally parked,
/// owned by a pooled backing, or parked in one thread's local cache, but the
/// slot always belongs to this `SizeClass`.
///
/// Liveness follows the buffer ownership state. Global freelist entries rely on
/// the pool's [`SizeClassHandle`] while the pool is alive and are drained when
/// the pool is dropped. Pooled backing values carry a [`SizeClassLease`].
/// Thread-local cache entries use banked strong references owned by the cache.
/// Those non-global states are what allow a buffer to outlive the public
/// [`BufferPool`] handle and still return to the correct freelist.
///
/// The freelist is the only place that deallocates tracked buffers. Returning a
/// buffer to the freelist transfers buffer ownership back to that freelist and
/// releases the pooled-backing lease or banked strong reference that kept the
/// class alive while the buffer was outside the global freelist.
///
/// Allocation prefers the local cache, then refills from the global freelist,
/// and only creates a new tracked buffer when no free buffer is available and
/// the class still has remaining capacity.
pub(super) struct SizeClass {
/// Dense global identifier for the TLS cache registry.
class_id: usize,
/// The buffer size for this class.
size: usize,
/// Global free list of tracked buffers available for reuse.
global: Freelist,
/// Maximum number of buffers retained in the current thread's local bin.
thread_cache_capacity: usize,
}
// SAFETY: shared state in `SizeClass` is synchronized through atomics and the
// global free set. Per-thread bins are stored in thread-local registries and only
// accessed by the current thread.
unsafe impl Send for SizeClass {}
// SAFETY: see above.
unsafe impl Sync for SizeClass {}
/// Non-owning raw identity for a size class.
///
/// # Size-class lifetime model
///
/// A [`SizeClass`] owns the [`Freelist`] for one buffer size class. The
/// freelist creates tracked [`PooledBuffer`]s, owns the allocation layout
/// needed to deallocate them, and is the only place that releases their memory.
/// A `PooledBuffer` outside the freelist does not carry enough information to
/// deallocate itself, so it must keep its originating `SizeClass` alive until
/// it can return to that freelist.
///
/// The pool has three buffer states, and those states determine where the
/// strong size-class references live.
///
/// - Global freelist: the buffer is parked in [`SizeClass::global`] and carries
/// no per-buffer strong reference. While the public pool exists, the
/// [`SizeClassHandle`] in [`BufferPoolInner::classes`] keeps the class alive.
/// - Pooled view: the buffer is owned by mutable or immutable I/O view state
/// and carries one [`SizeClassLease`], which is one strong reference to the
/// class.
/// - Thread-local cache: the [`TlsSizeClassCache`] stores the
/// [`SizeClassToken`] once, and owns one banked strong reference for each
/// initialized [`TlsSizeClassCacheEntry`]. A banked reference is an owned
/// `Arc<SizeClass>` reference counted by TLS cache state instead of
/// represented by a `SizeClassLease` value in each entry. Increasing `len`
/// banks one reference, decreasing `len` transfers one reference back into a
/// `SizeClassLease` or releases it to the global freelist.
///
/// Moving a buffer from the global freelist to pooled view or TLS state retains
/// one class reference. Moving it back to the global freelist releases that
/// reference. Moving between pooled view and TLS state transfers the same
/// reference without touching the refcount.
///
/// Dropping the public [`BufferPool`] drains globally parked buffers, then
/// drops its `SizeClassHandle`s. Pooled views and non-empty TLS caches may keep
/// the `SizeClass` alive after that point. Empty TLS caches may still remember
/// a token value, but with no banked references that token is only an inert
/// identity value and must not be dereferenced.
///
/// This is the one raw pointer shape used by all pool-owned, pooled view, and
/// thread-local references to a [`SizeClass`]. The pointer is always derived
/// from [`Arc::into_raw`].
///
/// `SizeClassToken` itself owns nothing. It is only an identity token and raw
/// pointer accepted by the `Arc` refcount APIs:
/// - [`SizeClassHandle`] pairs a token with ownership of one strong reference.
/// - [`SizeClassLease`] pairs a token with ownership of one strong reference.
/// - [`TlsSizeClassCache`] stores a token plus `len` banked strong references.
///
/// Because the token is non-owning, it may be stale when held by an empty TLS
/// cache. Code may dereference it or adjust the strong count only when another
/// invariant proves the allocation is still live. For example,
/// [`SizeClassHandle`] and [`SizeClassLease`] prove liveness through owned
/// strong references, and a non-empty [`TlsSizeClassCache`] proves liveness
/// through its banked entries.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct SizeClassToken {
ptr: ptr::NonNull<SizeClass>,
}
impl SizeClassToken {
/// Creates a token and owns the initial strong reference for `class`.
///
/// The returned token is non-owning in the type system, but the raw pointer
/// still represents one strong reference. The caller must wrap it in an
/// owning type, such as [`SizeClassHandle`], or otherwise arrange for that
/// strong reference to be released.
fn new(class: SizeClass) -> Self {
let ptr = Arc::into_raw(Arc::new(class)).cast_mut();
// SAFETY: `Arc::into_raw` never returns null.
let ptr = unsafe { ptr::NonNull::new_unchecked(ptr) };
Self { ptr }
}
/// Returns the referenced size class.
///
/// # Safety
///
/// Some owner must currently hold a strong reference for this token.
#[inline(always)]
const unsafe fn as_ref(&self) -> &SizeClass {
// SAFETY: guaranteed by the caller.
unsafe { self.ptr.as_ref() }
}
/// Retains one strong reference for this token.
///
/// # Safety
///
/// Some owner must currently hold a strong reference for this token.
#[inline(always)]
unsafe fn retain(self) {
// SAFETY: guaranteed by the caller.
unsafe { Arc::increment_strong_count(self.ptr.as_ptr()) };
}
/// Releases one owned strong reference for this token.
///
/// # Safety
///
/// The caller must own one strong reference represented by this token.
#[inline(always)]
unsafe fn release(self) {
// SAFETY: guaranteed by the caller.
unsafe { Arc::decrement_strong_count(self.ptr.as_ptr()) };
}
}
/// Owning pool reference to a size class.
///
/// This is the pool's strong `Arc<SizeClass>` reference represented by a
/// [`SizeClassToken`]. `SizeClassHandle` is the long-lived owner for a class
/// while the [`BufferPoolInner`] exists. Dropping the handle releases that
/// pool-owned strong reference. A class may still outlive the handle if pooled
/// backing values or thread-local cache entries own additional references
/// through [`SizeClassLease`] or banked TLS refs.
///
/// Functionally this is an `Arc<SizeClass>` stored in raw-token form. It exists
/// to keep the pool-owned reference alive and to provide a live token for
/// allocation paths that need to retain pooled-backing or TLS-banked
/// references. The raw form keeps the already-loaded class pointer usable for
/// explicit refcount operations without calling [`Arc::as_ptr`] or storing a
/// second token alongside an `Arc`.
struct SizeClassHandle {
token: SizeClassToken,
}
// SAFETY: `SizeClassHandle` owns a strong reference to a `SizeClass`, which is
// `Send`.
unsafe impl Send for SizeClassHandle {}
// SAFETY: same argument as `Send`, shared access to `SizeClass` is synchronized.
unsafe impl Sync for SizeClassHandle {}
impl SizeClassHandle {
/// Creates a new size class and takes ownership of its initial strong ref.
///
/// If `prefill` is true, the global freelist creates `max` buffers upfront
/// and makes them immediately available for reuse.
fn new(
class_id: usize,
size: usize,
alignment: usize,
max: NonZeroU32,
parallelism: NonZeroUsize,
thread_cache_capacity: usize,
prefill: bool,
) -> Self {
let layout = Layout::from_size_align(size, alignment).expect("alignment is a power of two");
let freelist = Freelist::new(max, parallelism, layout, prefill);
let class = SizeClass {
class_id,
size,
global: freelist,
thread_cache_capacity,
};
Self {
token: SizeClassToken::new(class),
}
}
/// Creates a new tracked buffer and retains this size class for its slot.
#[inline(always)]
fn try_create(&self, zeroed: bool) -> Option<(u32, PooledBuffer, SizeClassLease)> {
let (slot, buffer) = self.global.try_create(zeroed)?;
let class = SizeClassLease::retain(self);
Some((slot, buffer, class))
}
}
impl Drop for SizeClassHandle {
fn drop(&mut self) {
// SAFETY: this handle owns one strong reference for `self.token`.
unsafe { self.token.release() };
}
}
impl std::ops::Deref for SizeClassHandle {
type Target = SizeClass;
#[inline(always)]
fn deref(&self) -> &Self::Target {
// SAFETY: this handle owns one strong reference for `self.token`.
unsafe { self.token.as_ref() }
}
}
/// Owned size-class reference for a pooled buffer outside the global freelist.
///
/// A pooled buffer outside the global freelist must keep its originating
/// [`SizeClass`] alive so it can be returned after the [`BufferPool`] handle is
/// dropped. This is one strong `Arc<SizeClass>` reference represented by a
/// [`SizeClassToken`], with retain and release performed explicitly at the
/// boundaries where a buffer enters or leaves global pool state.
///
/// Lifetime-wise this is the same kind of reference as [`SizeClassHandle`]:
/// both own exactly one strong reference for a token. The types are separate
/// because they live in different state machines. `SizeClassHandle` is ordinary
/// RAII ownership for the pool's class vector. `SizeClassLease` is hot-path
/// pooled view ownership that must be explicitly transferred into TLS cache
/// state or returned to the global freelist.
///
/// The raw representation matters because the hot path mostly transfers
/// ownership between pooled view state and this thread's local cache. A real
/// `Arc<SizeClass>` field is pointer-sized too, but it is a non-`Copy` value
/// with drop glue. Even when the strong count would not change, moving it
/// through pooled buffer and cache-entry structs makes the compiler preserve
/// destructor paths for those structs. `SizeClassLease` has no automatic drop:
/// moving between pooled view and local-cache state is a plain pointer
/// transfer, and only explicit calls such as [`Self::return_global`] adjust the
/// strong count.
///
/// A lease must be consumed by one of those explicit transitions, such as
/// [`Self::into_banked`] or [`Self::return_global`]. Because this type
/// intentionally has no `Drop` implementation, simply dropping a lease value
/// would leak the strong reference. This keeps hot transfers free of drop glue,
/// but means every owner must complete one of the explicit transitions.
///
/// Thread-local cache entries do not store a lease per entry. The cache stores
/// the class token once and owns one banked strong reference for each
/// initialized entry. Popping from the local cache materializes a lease from
/// one of those banked references without touching the strong count.
///
/// Globally parked buffers do not carry a class reference: taking from the
/// global freelist retains the class, and returning to the global freelist
/// releases it.
#[must_use]
pub(crate) struct SizeClassLease {
token: SizeClassToken,
}
// SAFETY: `SizeClassLease` owns one strong reference to a `SizeClass`, which is
// `Send`.
unsafe impl Send for SizeClassLease {}
// SAFETY: same argument as `Send`, shared access to `SizeClass` is synchronized.
unsafe impl Sync for SizeClassLease {}
impl SizeClassLease {
/// Converts one banked class reference into a lease.
///
/// This does not retain the class. It only changes how an already-owned
/// strong reference is represented: from TLS cache state into a
/// `SizeClassLease` value.
///
/// # Safety
///
/// The caller must own one banked strong reference for `class.token`, and
/// that retained reference must be transferred to the returned lease. This
/// must not consume the pool-owned reference held by `class` itself.
#[inline(always)]
const unsafe fn from_banked(class: &SizeClassHandle) -> Self {
Self { token: class.token }
}
/// Retains `class` for a buffer leaving the global freelist.
#[inline(always)]
fn retain(class: &SizeClassHandle) -> Self {
let token = class.token;
// SAFETY: the borrowed `class` owns one strong reference for `token`.
unsafe { token.retain() };
Self { token }
}
/// Transfers this lease into a TLS cache entry.
///
/// This does not release the class. It consumes the lease and relies on the
/// caller to record one additional banked reference in TLS cache state,
/// normally by storing an entry and increasing the cache length. The cache
/// must later materialize or release exactly one lease for that entry.
///
/// This is a no-op at runtime, it exists to mark the ownership transition.
#[inline(always)]
const fn into_banked(self) {}
/// Returns the referenced size class.
///
/// The token is valid because `SizeClassLease` owns one strong reference.
#[inline(always)]
const fn class(&self) -> &SizeClass {
// SAFETY: guaranteed by the ownership invariant documented on
// `SizeClassLease`.
unsafe { self.token.as_ref() }
}
/// Returns the buffer size for this lease's size class.
#[inline(always)]
pub(crate) const fn size(&self) -> usize {
self.class().size
}
/// Returns a buffer to this class's global freelist and releases the class
/// reference.
///
/// The buffer is parked before the strong reference is released. If this is
/// the last outstanding reference after the public pool has been dropped,
/// dropping the `SizeClass` will then drain the just-parked buffer.
#[inline(always)]
fn return_global(self, slot: u32, buffer: PooledBuffer) {
self.class().global.put(slot, buffer);
// SAFETY: this lease owns one strong reference.
unsafe { self.token.release() };
}
}
/// Free tracked buffer owned by a thread-local size-class cache.
///
/// This is allocator cache state, not a caller-visible pooled view. While an
/// entry is held here, the buffer is owned by the current thread and is not
/// visible to the class-global freelist.
///
/// The `slot` identifies the buffer within its [`SizeClass`]. The enclosing
/// cache owns one banked size-class reference for this entry. The entry itself
/// intentionally stores only `(buffer, slot)` so local pop/push does not move a
/// class pointer per buffer.
struct TlsSizeClassCacheEntry {
buffer: PooledBuffer,
slot: u32,
}
/// Per-thread cache for one size class's tracked buffers.
///
/// Each instance is stored in [`TlsSizeClassCaches`] under one global
/// [`SizeClass::class_id`], so all entries in the cache belong to the same size
/// class. The cache owns full [`PooledBuffer`] values while they are local,
/// returning them to the global freelist happens only on miss refill, overflow,
/// explicit flush, or thread exit.
///
/// `class` is a non-owning token for this cache's size class. It can be stale
/// while `len == 0`, because an empty cache does not keep its pool alive. When
/// `len > 0`, each initialized entry in `entries[..len]` owns one banked
/// size-class reference, which keeps the pointed-to class alive. The entry
/// itself stays small (`buffer, slot`), popping it materializes a
/// [`SizeClassLease`] from one banked reference.
///
/// As described in [`SizeClassToken`], a banked reference is represented by
/// cache state rather than by a value stored in the entry. Changing `len` is
/// therefore an ownership transition as well as a stack operation.
///
/// An empty cache may keep a stale token only for identity checks. It must not
/// dereference the token or adjust its strong count until a live
/// [`SizeClassHandle`], [`SizeClassLease`], or banked entry proves the class is
/// still alive.
///
/// The hot steady-state allocation path pops an entry from `entries`, and the
/// hot return path pushes one back while there is room.
struct TlsSizeClassCache {
class: SizeClassToken,
entries: Box<[MaybeUninit<TlsSizeClassCacheEntry>]>,
len: usize,
capacity: usize,
}
impl TlsSizeClassCache {
/// Creates a new empty cache with the given maximum thread-cache size.
///
/// The cache stores `class` for identity, but starts with `len == 0` and
/// therefore owns no banked size-class references.
fn new(class: SizeClassToken, capacity: usize) -> Self {
let entries = (0..capacity)
.map(|_| MaybeUninit::uninit())
.collect::<Vec<_>>()
.into_boxed_slice();
Self {
class,
entries,
len: 0,
capacity,
}
}
/// Removes and returns one reusable buffer entry.
///
/// Local hits are served directly from the cache. On a local miss, small
/// caches take only the buffer being returned to the caller. Larger caches
/// batch-take from the global freelist, return the first claimed buffer,
/// and retain the rest locally for future allocations.
///
/// The returned lease is materialized from the banked size-class reference
/// associated with the returned entry.
#[inline(always)]
fn pop(&mut self, class: &SizeClassHandle) -> Option<(TlsSizeClassCacheEntry, SizeClassLease)> {
if let Some(entry) = self.pop_local() {
// SAFETY: the popped entry consumed one banked reference owned by
// this cache. Transfer that reference to the returned lease.
let lease = unsafe { SizeClassLease::from_banked(class) };
return Some((entry, lease));
}
// Take from the class-global freelist on a local miss.
self.pop_global(class)
}
/// Removes and returns one entry from this thread's local stack.
///
/// This touches only thread-local cache state. A returned entry consumes
/// one banked size-class reference from this cache, the caller must
/// materialize or release that reference.
#[inline(always)]
fn pop_local(&mut self) -> Option<TlsSizeClassCacheEntry> {
if self.len == 0 {
return None;
}
self.len -= 1;
// SAFETY: entries in `0..self.len` are initialized. Decrementing `len`
// above makes this slot uninitialized again.
Some(unsafe { self.entries.get_unchecked(self.len).assume_init_read() })
}
/// Takes from the class-global freelist after the local stack misses.
///
/// Every claimed global entry gets one retained class reference. The first
/// claimed entry is returned with that reference materialized as a
/// [`SizeClassLease`], additional claimed entries are parked in this cache
/// and counted by `len`.
///
/// This is separate from [`Self::pop`] so the steady-state allocation hot
/// path can inline only the local cache hit. We annotate with `inline(never)`
/// to keep the refill and batching code out of `BufferPoolInner::try_alloc`,
/// reducing hot-path code size and register pressure.
#[inline(never)]
fn pop_global(
&mut self,
class: &SizeClassHandle,
) -> Option<(TlsSizeClassCacheEntry, SizeClassLease)> {
// Tiny caches do not batch enough to justify the wider global claim.
// Keep their miss path equivalent to a single take.
if self.capacity < MIN_TLS_BATCH_CAPACITY {
return class.global.take().map(|(slot, buffer)| {
let lease = SizeClassLease::retain(class);
(TlsSizeClassCacheEntry { buffer, slot }, lease)
});
}
// Refill larger caches to half capacity. That leaves room for future
// same-thread returns while still amortizing the global atomic scan
// over several future local pops.
let mut entry = None;
let take = self.capacity / 2;
class.global.take_batch(take, |slot, buffer| {
// Each claimed global entry becomes either the returned lease or a
// local cache entry, so each needs one retained class reference.
let cache_entry = TlsSizeClassCacheEntry { buffer, slot };
let lease = SizeClassLease::retain(class);
if entry.is_none() {
// Hand the first claimed buffer to the allocation that missed
// locally. Additional claimed buffers refill the local cache.
entry = Some((cache_entry, lease));
} else {
// The take count is derived from the target occupancy, so
// refill cannot overflow the local cache. Push directly to
// avoid the spill checks used by return-to-cache.
self.push_local(cache_entry, lease);
}
});
entry
}
/// Pushes an entry into the local cache, spilling to global if full.
///
/// Small local caches prioritize same-thread locality and route overflow
/// directly to the global freelist. Once the local cache is large enough to
/// batch effectively, half the entries are drained to amortize global queue
/// traffic across future returns.
#[inline(always)]
fn push(&mut self, lease: SizeClassLease, slot: u32, buffer: PooledBuffer) {
let entry = TlsSizeClassCacheEntry { buffer, slot };
if self.len < self.capacity {
// Keep the returned entry local while there is room.
self.push_local(entry, lease);
return;
}
// Handle overflow when the local stack is full.
self.push_full(entry, lease);
}
/// Pushes one entry onto this thread's local stack.
///
/// The caller must ensure the stack has room. `lease` becomes the banked
/// size-class reference represented by `entry`.
#[inline(always)]
fn push_local(&mut self, entry: TlsSizeClassCacheEntry, lease: SizeClassLease) {
lease.into_banked();
// SAFETY: the caller ensured `self.len < self.capacity`, so this slot
// is in bounds and currently uninitialized.
unsafe {
self.entries.get_unchecked_mut(self.len).write(entry);
}
self.len += 1;
}
/// Handles a push after the local stack fills.
///
/// Very small caches return the incoming entry directly to the global
/// freelist. Larger caches spill older local entries in a batch, then keep
/// the incoming entry local so the dropping thread retains the freshest