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
//! [`Talc`](crate::base::Talc)'s internal binning strategy is dictated by
//! the [`Binning`] implementation used. See [`Binning`]'s docs for more
//! information on those specifics.
//!
//! This is useful to change depending on how [`Talc`](crate::base::Talc)
//! is being used. For example, WebAssembly module size and performance
//! substantially benefits from [`WasmBinning`](crate::wasm::WasmBinning)
//! over [`DefaultBinning`] due to platform-specific quirks (64-bit
//! instructions on a 32-bit memory architecture).
//!
//! [`DefaultBinning`] serves as a very general-purpose binning strategy.
//! If you need to implement something more tailored, be aware of
//! - [`test_utils`] which provides methods for evaluating binning strategies.
//! - [`linear_extent_then_linearly_divided_exponential_binning`] which is a highly
//! optimized `size_to_bin` implementation that you should consider using,
//! perhaps with different parameters to [`DefaultBinning`]'s choices.
use BitField;
/// Implementors describe a binning strategy for [`Talc`](super::Talc) to use.
///
/// Different binning strategies greatly affect the performance and efficiency
/// of the allocator, and different bit-fields are better depending on the
/// instruction set architecture.
///
/// A binning strategy determines:
/// - [`Binning::BIN_COUNT`]: how many free lists there are.
/// - [`Binning::size_to_bin`]: which chunks go into which lists based on size.
/// - [`Binning::AvailabilityBitField`]: what type is used to track the availability of chunks in the free lists.
/// The default [`Binning`] implementation used by `Talc`.
///
/// Very competitive efficiency while still being very fast. Sticking with this is generally a good choice.
;
/// A fast binning algorithm with relatively even coverage and configurable behavior.
///
/// This is the default binning algorithm that `Talc` uses due to having a good
/// spread of bin intervals, being able to take advantage of many or few buckets
/// well, and being very fast (only a handful of instructions with one branch).
///
/// # Behavior by size
/// - `0..=(CHUNK_UNIT*LIN_DIVS*LIN_EXT_MULTI)` : Bins sizes into one-bin-per-chunk-size
/// - `(CHUNK_UNIT*LIN_DIVS*LIN_EXT_MULTI)..` : Binds sizes by linearly-subdivided exponential levels.
///
/// # Parameters
/// - `LIN_DIVS`: the number of linear regions per power of two in the exponential region.
/// - The higher this is, the more buckets are needed but the binning is more fine-grained.
/// - Must be a power of two.
/// - Typically 2 (few bins, subpar granularity), 4, or 8 (lots of bins, good granularity).
/// - This is the parameter you want to figure out first for a given number of bins.
///
/// - `LIN_EXT_MULTI`: the linear region extent multiplier.
/// - Scales the extent of the linear region.
/// - Must be a power of two.
/// - Set this to 1 by default.
/// - If there are too many bins being used on excessively-high size regions, this is useful
/// for spending those bins on more buckets for small sizes instead.
///
/// # Deciding on the parameters
/// Make use of [`test_utils::find_binning_boundaries`] to get a sense for
/// the mapping. `LIN_DIVS` has a much larger effect so tinker with that first
/// while keeping `LIN_EXT_MULTI` low, and then increase `LIN_EXT_MULTI` if
/// there is useless range at the top, given the number of bins you have.
///
/// Having a range up to around 128MiB~2GiB is enough for most applications.
/// But keep in mind the largest bucket size you'll ever make use of is the largest
/// contiguous span of memory.
///
/// The main effects on the allocator will be the heap efficiency and the performance.
/// Scripts to test these can be found in the repository in `benches/src/bin/`.
pub const
/// Contains utilities for evaluating and testing [`Binning`] implementation behavior.
// The graveyard of some binning algorithms that I haven't bothered to fix up/finish/expose yet.
// `fast_linear_else_exponential_bin_to_size` is fast but rather heap inefficient and is unused.
// `bin_to_size_64_kib_max_with_63_bins` was part of an old idea that never came to fruition (MT+superblocks).
// The large two are relatively slow compared to `linear_extent_then_linearly_divided_exponential_binning`
/* /// A [`Binning::size_to_bin`] implementation that bins linearly, then exponentially.
///
/// This is a very simple but reasonably effective binning algorithm.
///
/// This works well on any platform and with any `chunk_unit::<A>()`,
/// but requires that `B::bin_count()` is at least 29.
/// This might be relaxed in the future.
#[inline]
pub fn fast_linear_else_exponential_bin_to_size<B: Binning>(size: usize) -> u32 {
let linear_division_size = crate::base::CHUNK_UNIT;
if B::BIN_COUNT < 29 {
// This isn't a hard requirement, but I doubt people will commonly want
// so few bins and still want to use this binning algorithm.
// If you run into this, check if there's a misconfiguration with the
// `Binning` impl being used. If you do really want so few bins,
// consider writing your own `size_to_bin` implementation instead.
panic!("`bin_to_size_lin_exp` expects at least 29 bins to be available.")
}
// This really doesn't need to be that high. Doesn't matter what
// platform you're on, allocating over 100MiB at a time is rare enough
// to not dedicate many bins to.
//
// At worst, the number of bins is 28 and so there will be 7 linear bins.
// At worst, linear_divisions might be 16 on 32 bit platforms.
// => `linear_extent` is 16 * (7 + 1) = 128
// => The maximum bin category is 2^(ilog2(144) + 18) which is 32MiB
// This is fine.
// More commonly, `linear_extent` will be at least 512, resulting in a reach of
// 2^(log2(512) + 18) which is 128MiB, which is plenty.
let exponential_bins = 22;
let linear_bins = B::BIN_COUNT - exponential_bins;
// We map the sizes as follows:
// Linear mapping:
// 0..linear_divisions : u8::MAX
// linear_divisions..(linear_divisions * (linear_bins + 1)) : 0..linear_bins
// Exponential mapping:
// (linear_divisions * linear_bins).. : linear_bins..B::bin_count()
let linear_extent = linear_division_size * (linear_bins as usize + 1);
if size < linear_extent {
((size / linear_division_size) as u32).wrapping_sub(1)
} else {
let exp_bin = size.ilog2() - linear_extent.ilog2() + linear_bins;
exp_bin
}
} */
/* pub const fn bin_to_size_64_kib_max_with_63_bins(size: usize) -> usize {
if size < 1024 {
(size >> 5) - 1
} else {
let category = usize::BITS as usize - 10 - size.leading_zeros() as usize;
let v = 1 << (6 - category);
((size >> (4 + category * 2)) ^ (v >> 1)) + (63 - v)
}
} */
/*/// Calls [`auto_size_to_bin_with_soft_max`] with `SOFT_MAX` = 96 MiB on 64 bits systems and 20 MiB on 32 bit systems.
pub unsafe fn auto_size_to_bin<B: Binning>(size: usize) -> u8 {
#[cfg(target_pointer_width = "32")]
return auto_size_to_bin_with_soft_max::<B, {1 << 20}>(size);
#[cfg(target_pointer_width = "64")]
return auto_size_to_bin_with_soft_max::<B, {1 << 20}>(size);
// return bin_of_size_l1_l2_pexp::<TwoUsizeBinCfg, A>(size);
// return bin_of_size_lin_exp::<A>(size);
}
/// Linear region.
/// Transition (trans) region.
/// Pseudo-exponential (pexp) region.
pub unsafe fn auto_size_to_bin_with_soft_max<B: Binning, const SOFT_MAX: usize>(size: usize) -> u32 {
// All of these `let` statements are done at compile time if optimizations are enabled.
// They configure how we will do bin allocation across 3 regions:
// - Linearly divided bins
// - Exponential region with changing linear subdivisions (transition region)
// - Exponential region with fixed linear subdivisions
// These give nice coverage and spread.
// The function is pretty fast too after any level of optimizations.
let alloc_unit = crate::base::CHUNK_UNIT;
let non_pexp_bins = 1 << (B::BIN_COUNT * 2 / 3).ilog2();
let linear_bins = non_pexp_bins >> 1;
let linear_max = alloc_unit * linear_bins;
let trans_max = linear_max * linear_bins;
let pexp_bin_offset = non_pexp_bins - 2;
let pexp_bins = B::BIN_COUNT as usize - pexp_bin_offset;
let linear_subdivs_per_exp_step = pexp_bins / (SOFT_MAX.ilog2() - trans_max.ilog2());
let linear_subdivs_per_exp_step = 2.max(1usize << linear_subdivs_per_exp_step.ilog2());
// Calculate the maximum extent of the pseudo-exponential region with the bins available.
// Note that the divide loses some information here; the extra few bins will add linear subdivs.
let pexp_max_without_linear_extra = trans_max * 1 << (pexp_bins / linear_subdivs_per_exp_step);
// We add the extra extent due to the linear subdivs by finding the modulo.
let pexp_max = pexp_max_without_linear_extra
+ (pexp_bins % linear_subdivs_per_exp_step) * pexp_max_without_linear_extra / linear_subdivs_per_exp_step;
/* // This asserts in debug or "proves" in release to the compiler
// that the size is at least `alloc_unit`.
if size < alloc_unit {
debug_assert!(false, "size is less than allocation unit!");
unsafe { core::hint::unreachable_unchecked() };
} */
if alloc_unit * B::BIN_COUNT as usize >= SOFT_MAX {
return ((size / alloc_unit) as u8).min(B::BIN_COUNT).wrapping_sub(1);
}
if size < linear_max {
((size / alloc_unit) as u8).wrapping_sub(1)
} else if size < trans_max {
let category = ilog2(size) - (ilog2(alloc_unit * linear_bins) - 1);
let v = 1 << (ilog2(linear_bins) - category);
(((size >> (alloc_unit.ilog2() as usize - 1 + category * 2)) ^ v) + (non_pexp_bins - 1 - v * 2)) as u8
} else if size < pexp_max {
// Log 2 of (minimum pseudo-exponential chunk size)
let min_exp_bits_less_1 = ilog2(trans_max);
// how many bits are used to determine the division
let pexp_div_bits = ilog2(linear_subdivs_per_exp_step);
let bits_less_one = ilog2(size);
// the magnitude the size belongs to.
// calculate the difference in bit count i.e. difference in power
let magnitude = bits_less_one - min_exp_bits_less_1;
// the division of the magnitude the size belongs to.
// slide the size to get the division bits at the bottom and remove the top bit
let division = (size >> (bits_less_one - pexp_div_bits)) & !linear_subdivs_per_exp_step;
// the index into the pseudo-exponential bins.
let bin_offset = (magnitude << pexp_div_bits) | division;
// cap the max bin at the last bin
let pexp_bin = bin_offset + pexp_bin_offset;
pexp_bin as u8
} else {
B::BIN_COUNT - 1
}
} */
/* pub trait L1L2PexpConfig {
const L1_DIVS: u32;
const L2_DIVS: u32;
const PEXP_LIN_DIVS: u32;
}
pub const fn bin_of_size_l1_l2_pexp<B: Binning, Cfg: L1L2PexpConfig>(size: usize) -> u32 {
// this mess determines the binning strategy used by the allocator
// the default is to have a bin per multiple of word size from the minimum
// chunk size up to WORD_BINED_SIZE and double word gap (sharing two sizes)
// up to DOUBLE_BINED_SIZE, and from there on use pseudo-logarithmic sizes.
// such sizes are as follows: begin at some power of two (DOUBLE_BINED_SIZE)
// and increase by some power of two fraction (quarters, on 64 bit machines)
// until reaching the next power of two, and repeat:
// e.g. begin at 32, increase by quarters: 32, 40, 48, 56, 64, 80, 96, 112, 128, ...
let l1_size = crate::base::CHUNK_UNIT;
let l2_size = l1_size * 2;
let l1_extent = l1_size * (Cfg::L1_DIVS as usize + 1);
let l2_extent = l1_extent + l2_size * Cfg::L2_DIVS as usize;
// Log 2 of (minimum pseudo-exponential chunk size)
let min_exp_bits_less_1 = l2_extent.ilog2();
// how many bits are used to determine the division
let pexp_div_bits = Cfg::PEXP_LIN_DIVS.ilog2();
/* // Calculate the maximum extent of the pseudo-exponential region with the bins available.
let pexp_bins = Cfg::BIN_COUNT - Cfg::L1_DIVS - Cfg::L2_DIVS;
// Note that the divide loses some information here; the extra few bins will add linear subdivs.
let pexp_max_without_linear_extra = l2_extent * 1 << (pexp_bins / Cfg::PEXP_LIN_DIVS);
// We add the extra extent due to the linear subdivs by finding the modulo.
let pexp_max = pexp_max_without_linear_extra
+ (pexp_bins % Cfg::PEXP_LIN_DIVS) * pexp_max_without_linear_extra / Cfg::PEXP_LIN_DIVS; */
if size < l1_extent {
// single word separated bins
((size / l1_size) as u32).wrapping_sub(1)
} else if size < l2_extent {
// quad word separated bins
// equiv to (size - WORD_BIN_LIMIT) / 2WORD_SIZE + DBL_BIN
// but saves an instruction
(size / l2_size - l1_extent / l2_size) as u32 + Cfg::L1_DIVS
} else {
// pseudo-exponentially separated bin
// here's what a size is, bit by bit: 1_div_extra
// e.g. with four divisions 1_01_00010011000
// the bin is determined by the magnitude and the division
// mag 0 div 0, mag 0 div 1, mag 0 div 2, mag 0 div 3, mag 1 div 0, ...
// let shifted_size = (size)
let bits_less_one = size.ilog2();
// the magnitude the size belongs to.
// calculate the difference in bit count i.e. difference in power
let magnitude = bits_less_one - min_exp_bits_less_1;
// the division of the magnitude the size belongs to.
// slide the size to get the division bits at the bottom and remove the top bit
let division = (size >> (bits_less_one - pexp_div_bits)) as u32 & !Cfg::PEXP_LIN_DIVS;
// the index into the pseudo-exponential bins.
let bin_offset = (magnitude << pexp_div_bits) | division;
// cap the max bin at the last bin
let pexp_bin = bin_offset + Cfg::L1_DIVS + Cfg::L2_DIVS;
if pexp_bin >= B::BIN_COUNT {
return B::BIN_COUNT - 1;
}
pexp_bin
}
}
pub struct TwoUsizeBinCfg;
#[cfg(target_pointer_width = "64")]
impl L1L2PexpConfig for TwoUsizeBinCfg {
const L1_DIVS: u32 = 55;
const L2_DIVS: u32 = 36;
const PEXP_LIN_DIVS: u32 = 4;
}
#[cfg(target_pointer_width = "32")]
impl L1L2PexpConfig for TwoUsizeBinCfg {
const L1_DIVS: u32 = 27;
const L2_DIVS: u32 = 18;
const PEXP_LIN_DIVS: u32 = 2;
} */