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
use crate::compiler_hints::UNLIKELY;
use core::alloc::AllocError;
use core::alloc::Layout;
use core::cell::Cell;
use core::ptr::NonNull;
#[derive(Debug)]
pub enum ChunkAllocatorError {
BadHeapMemory,
BadBitmapMemory,
BadChunkSize,
OutOfMemory,
}
pub const DEFAULT_CHUNK_SIZE: usize = 256;
#[derive(Debug)]
pub struct ChunkAllocator<'a, const CHUNK_SIZE: usize = DEFAULT_CHUNK_SIZE> {
heap: &'a mut [u8],
bitmap: &'a mut [u8],
is_first_alloc: Cell<bool>,
maybe_next_free_chunk: (usize, usize),
}
impl<'a, const CHUNK_SIZE: usize> ChunkAllocator<'a, CHUNK_SIZE> {
#[inline]
pub const fn chunk_size(&self) -> usize {
CHUNK_SIZE
}
#[inline]
pub const fn new(
heap: &'a mut [u8],
bitmap: &'a mut [u8],
) -> Result<Self, ChunkAllocatorError> {
if CHUNK_SIZE == 0 {
return Err(ChunkAllocatorError::BadChunkSize);
}
let heap_starts_at_0 = heap.as_ptr().is_null();
let heap_is_multiple_of_chunk_size = heap.len() % CHUNK_SIZE == 0;
if heap.is_empty() || heap_starts_at_0 || !heap_is_multiple_of_chunk_size {
return Err(ChunkAllocatorError::BadHeapMemory);
}
let chunk_count = heap.len() / CHUNK_SIZE;
let chunk_count_is_multiple_of_8 = chunk_count % 8 == 0;
if !chunk_count_is_multiple_of_8 {
return Err(ChunkAllocatorError::BadHeapMemory);
}
let bitmap_chunk_capacity = bitmap.len() * 8;
let bitmap_covers_all_chunks_exact = chunk_count == bitmap_chunk_capacity;
if !bitmap_covers_all_chunks_exact {
return Err(ChunkAllocatorError::BadBitmapMemory);
}
Ok(Self {
heap,
bitmap,
is_first_alloc: Cell::new(true),
maybe_next_free_chunk: (0, chunk_count),
})
}
#[inline]
pub const fn new_const(heap: &'a mut [u8], bitmap: &'a mut [u8]) -> Self {
assert!(CHUNK_SIZE > 0, "chunk size must not be zero!");
let heap_starts_at_0 = heap.as_ptr().is_null();
let heap_is_multiple_of_chunk_size = heap.len() % CHUNK_SIZE == 0;
assert!(
!heap.is_empty() && !heap_starts_at_0 && heap_is_multiple_of_chunk_size,
"heap must be not empty and a multiple of the chunk size"
);
let chunk_count = heap.len() / CHUNK_SIZE;
let chunk_count_is_multiple_of_8 = chunk_count % 8 == 0;
assert!(
chunk_count_is_multiple_of_8,
"chunk count must be a multiple of 8"
);
let bitmap_chunk_capacity = bitmap.len() * 8;
let bitmap_covers_all_chunks_exact = chunk_count == bitmap_chunk_capacity;
assert!(
bitmap_covers_all_chunks_exact,
"the bitmap must cover the amount of chunks exactly"
);
Self {
heap,
bitmap,
is_first_alloc: Cell::new(true),
maybe_next_free_chunk: (0, chunk_count),
}
}
#[inline]
pub const fn capacity(&self) -> usize {
self.heap.len()
}
#[inline]
pub const fn chunk_count(&self) -> usize {
self.capacity() / CHUNK_SIZE
}
#[inline]
pub fn usage(&self) -> f32 {
let mut used_chunks = 0;
let chunk_count = self.chunk_count();
for chunk_i in 0..chunk_count {
if !self.chunk_is_free(chunk_i) {
used_chunks += 1;
}
}
let ratio = used_chunks as f32 / chunk_count as f32;
libm::roundf(ratio * 10000.0) / 100.0
}
#[inline(always)]
fn chunk_is_free(&self, chunk_index: usize) -> bool {
debug_assert!(
chunk_index < self.chunk_count(),
"chunk_index={} is bigger than max chunk index={}",
chunk_index,
self.chunk_count() - 1
);
let (byte_i, bit) = self.chunk_index_to_bitmap_indices(chunk_index);
let relevant_bit = (self.bitmap[byte_i] >> bit) & 1;
relevant_bit == 0
}
#[inline(always)]
fn mark_chunk_as_used(&mut self, chunk_index: usize) {
debug_assert!(chunk_index < self.chunk_count());
if UNLIKELY(!self.chunk_is_free(chunk_index)) {
panic!(
"tried to mark chunk {} as used but it is already used",
chunk_index
);
}
let (byte_i, bit) = self.chunk_index_to_bitmap_indices(chunk_index);
self.bitmap[byte_i] ^= 1 << bit;
}
#[inline(always)]
fn mark_chunk_as_free(&mut self, chunk_index: usize) {
debug_assert!(chunk_index < self.chunk_count());
if UNLIKELY(self.chunk_is_free(chunk_index)) {
panic!(
"tried to mark chunk {} as free but it is already free",
chunk_index
);
}
let (byte_i, bit) = self.chunk_index_to_bitmap_indices(chunk_index);
let updated_byte = self.bitmap[byte_i] ^ (1 << bit);
self.bitmap[byte_i] = updated_byte;
}
#[inline(always)]
fn chunk_index_to_bitmap_indices(&self, chunk_index: usize) -> (usize, usize) {
debug_assert!(
chunk_index < self.chunk_count(),
"chunk_index out of range!"
);
(chunk_index / 8, chunk_index % 8)
}
#[inline(always)]
fn find_free_continuous_memory_region(
&mut self,
chunk_num_request: usize,
alignment: usize,
) -> Result<usize, ChunkAllocatorError> {
if UNLIKELY(chunk_num_request > self.chunk_count()) {
return Err(ChunkAllocatorError::OutOfMemory);
}
let start_index = self.maybe_next_free_chunk.0;
(start_index..(start_index + self.chunk_count()))
.map(|index| index % self.chunk_count())
.filter(|chunk_index| self.chunk_is_free(*chunk_index))
.filter(|chunk_index| {
*chunk_index + chunk_num_request <= self.chunk_count()
})
.map(|chunk_index| (chunk_index, unsafe { self.chunk_index_to_ptr(chunk_index) }))
.filter(|(_, addr)| addr.align_offset(alignment) == 0)
.map(|(chunk_index, _)| chunk_index)
.find(|chunk_index| {
(chunk_index + 1..((chunk_index + 1) + chunk_num_request - 1))
.all(|index| self.chunk_is_free(index))
})
.ok_or(ChunkAllocatorError::OutOfMemory)
}
#[inline(always)]
unsafe fn chunk_index_to_ptr(&self, chunk_index: usize) -> *mut u8 {
debug_assert!(
chunk_index < self.chunk_count(),
"chunk_index out of range!"
);
self.heap.as_ptr().add(chunk_index * CHUNK_SIZE) as *mut u8
}
#[inline(always)]
unsafe fn ptr_to_chunk_index(&self, ptr: *const u8) -> usize {
let heap_begin_inclusive = self.heap.as_ptr();
let heap_end_exclusive = self.heap.as_ptr().add(self.heap.len());
debug_assert!(
heap_begin_inclusive <= ptr && ptr < heap_end_exclusive,
"pointer {:?} is out of range {:?}..{:?} of the allocators backing storage",
ptr,
heap_begin_inclusive,
heap_end_exclusive
);
(ptr as usize - heap_begin_inclusive as usize) / CHUNK_SIZE
}
#[inline(always)]
const fn calc_required_chunks(&self, size: usize) -> usize {
if size % CHUNK_SIZE == 0 {
size / CHUNK_SIZE
} else {
(size / CHUNK_SIZE) + 1
}
}
#[track_caller]
#[inline]
#[must_use = "The pointer must be used and freed eventually to prevent memory leaks."]
pub fn allocate(&mut self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
if UNLIKELY(self.is_first_alloc.get()) {
self.is_first_alloc.replace(false);
self.bitmap.fill(0);
}
let layout = if UNLIKELY(layout.size() == 0) {
Layout::from_size_align(1, layout.align()).unwrap()
} else {
layout
};
let required_chunks = self.calc_required_chunks(layout.size());
let index = self.find_free_continuous_memory_region(required_chunks, layout.align());
if UNLIKELY(index.is_err()) {
log::warn!(
"Out of Memory. Can't fulfill the requested layout: {:?}. Current usage is: {}%/{}byte",
layout,
self.usage(),
((self.usage() * self.capacity() as f32) as u64)
);
}
let index = index.map_err(|_| AllocError)?;
for i in index..index + required_chunks {
self.mark_chunk_as_used(i);
}
if !self.chunk_is_free(self.maybe_next_free_chunk.0) {
self.maybe_next_free_chunk = ((index + 1) % self.chunk_count(), 1);
}
let heap_ptr = unsafe { self.chunk_index_to_ptr(index) };
log::trace!(
"alloc: layout={layout:?}, ptr={heap_ptr:?}, #chunks={}",
required_chunks
);
let heap_ptr = NonNull::new(heap_ptr).unwrap();
Ok(NonNull::slice_from_raw_parts(
heap_ptr,
required_chunks * self.chunk_size(),
))
}
#[track_caller]
#[inline]
pub unsafe fn deallocate(&mut self, ptr: NonNull<u8>, layout: Layout) {
let layout = if UNLIKELY(layout.size() == 0) {
Layout::from_size_align(1, layout.align()).unwrap()
} else {
layout
};
let freed_chunks = self.calc_required_chunks(layout.size());
log::trace!("dealloc: layout={:?}, #chunks={})", layout, freed_chunks);
let index = self.ptr_to_chunk_index(ptr.as_ptr());
for i in index..index + freed_chunks {
self.mark_chunk_as_free(i);
}
if freed_chunks < self.maybe_next_free_chunk.1 {
self.maybe_next_free_chunk = (index, freed_chunks);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::alloc::{AllocError, Allocator, Global};
use std::cmp::max;
use std::ptr::NonNull;
use std::vec::Vec;
mod helpers {
use super::*;
pub struct GlobalPageAlignedAlloc;
unsafe impl Allocator for GlobalPageAlignedAlloc {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
let alignment = max(layout.align(), 4096);
let layout = layout.align_to(alignment).unwrap();
Global.allocate(layout)
}
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
Global.deallocate(ptr, layout)
}
}
pub fn create_heap_and_bitmap_vectors() -> (
Vec<u8, GlobalPageAlignedAlloc>,
Vec<u8, GlobalPageAlignedAlloc>,
) {
const CHUNK_COUNT: usize = 32;
const HEAP_SIZE: usize = DEFAULT_CHUNK_SIZE * CHUNK_COUNT;
let mut heap = Vec::with_capacity_in(HEAP_SIZE, GlobalPageAlignedAlloc);
(0..heap.capacity()).for_each(|_| heap.push(0));
const BITMAP_SIZE: usize = HEAP_SIZE / DEFAULT_CHUNK_SIZE / 8;
let mut heap_bitmap = Vec::with_capacity_in(BITMAP_SIZE, GlobalPageAlignedAlloc);
(0..heap_bitmap.capacity()).for_each(|_| heap_bitmap.push(0));
assert_eq!(heap.as_ptr().align_offset(4096), 0, "must be page aligned");
assert_eq!(
heap_bitmap.as_ptr().align_offset(4096),
0,
"must be page aligned"
);
(heap, heap_bitmap)
}
}
#[test]
fn test_new_fails_illegal_chunk_size() {
let (mut heap, mut heap_bitmap) = helpers::create_heap_and_bitmap_vectors();
assert!(matches!(
ChunkAllocator::<0>::new(&mut heap, &mut heap_bitmap).unwrap_err(),
ChunkAllocatorError::BadChunkSize
));
std::panic::catch_unwind(|| {
let (mut heap, mut heap_bitmap) = helpers::create_heap_and_bitmap_vectors();
ChunkAllocator::<0>::new_const(&mut heap, &mut heap_bitmap);
})
.expect_err("expected panic because of bad chunk size");
assert!(matches!(
ChunkAllocator::<3>::new(&mut heap, &mut heap_bitmap).unwrap_err(),
ChunkAllocatorError::BadHeapMemory
));
std::panic::catch_unwind(|| {
let (mut heap, mut heap_bitmap) = helpers::create_heap_and_bitmap_vectors();
ChunkAllocator::<3>::new_const(&mut heap, &mut heap_bitmap);
})
.expect_err("expected panic because of bad heap memory");
assert!(matches!(
ChunkAllocator::<DEFAULT_CHUNK_SIZE>::new(&mut heap, &mut [0]).unwrap_err(),
ChunkAllocatorError::BadBitmapMemory
));
std::panic::catch_unwind(|| {
let (mut heap, _) = helpers::create_heap_and_bitmap_vectors();
ChunkAllocator::<DEFAULT_CHUNK_SIZE>::new_const(&mut heap, &mut [0]);
})
.expect_err("expected panic because of bad bitmap memory");
}
#[test]
fn test_compiles_dynamic() {
let (mut heap, mut heap_bitmap) = helpers::create_heap_and_bitmap_vectors();
let mut _alloc: ChunkAllocator = ChunkAllocator::new(&mut heap, &mut heap_bitmap).unwrap();
}
#[test]
fn test_compiles_const() {
const CHUNK_COUNT: usize = 16;
const HEAP_SIZE: usize = DEFAULT_CHUNK_SIZE * CHUNK_COUNT;
static mut HEAP: [u8; HEAP_SIZE] = [0; HEAP_SIZE];
const BITMAP_SIZE: usize = HEAP_SIZE / DEFAULT_CHUNK_SIZE / 8;
static mut HEAP_BITMAP: [u8; BITMAP_SIZE] = [0; BITMAP_SIZE];
let mut _alloc: ChunkAllocator =
unsafe { ChunkAllocator::new(&mut HEAP, &mut HEAP_BITMAP).unwrap() };
}
#[test]
fn test_chunk_count_matches_bitmap() {
let min_chunk_count = 8;
for chunk_count in (min_chunk_count..128).step_by(8) {
let heap_size: usize = chunk_count * DEFAULT_CHUNK_SIZE;
let mut heap = vec![0_u8; heap_size];
let bitmap_size_exact = if chunk_count % 8 == 0 {
chunk_count / 8
} else {
(chunk_count / 8) + 1
};
let mut bitmap = vec![0_u8; bitmap_size_exact];
let alloc: ChunkAllocator = ChunkAllocator::new(&mut heap, &mut bitmap).unwrap();
assert_eq!(
chunk_count,
alloc.chunk_count(),
"the allocator must get constructed successfully because the bitmap size matches the number of chunks"
);
}
}
#[test]
fn test_alloc_new_fails_when_bitmap_doesnt_match() {
for chunk_count in (0..128).filter(|chunk_count| *chunk_count % 8 != 0) {
let heap_size: usize = chunk_count * DEFAULT_CHUNK_SIZE;
let mut heap = vec![0_u8; heap_size];
let bitmap_size_exact = if chunk_count % 8 == 0 {
chunk_count / 8
} else {
(chunk_count / 8) + 1
};
let mut bitmap = vec![0_u8; bitmap_size_exact];
let alloc = ChunkAllocator::<DEFAULT_CHUNK_SIZE>::new(&mut heap, &mut bitmap);
assert!(
alloc.is_err(),
"new() must fail, because the bitmap can not exactly cover the available chunks"
);
}
}
#[test]
fn test_chunk_index_to_bitmap_indices() {
let (mut heap, mut heap_bitmap) = helpers::create_heap_and_bitmap_vectors();
let alloc: ChunkAllocator = ChunkAllocator::new(&mut heap, &mut heap_bitmap).unwrap();
assert_eq!((0, 3), alloc.chunk_index_to_bitmap_indices(3));
assert_eq!((0, 7), alloc.chunk_index_to_bitmap_indices(7));
assert_eq!((1, 0), alloc.chunk_index_to_bitmap_indices(8));
assert_eq!((1, 1), alloc.chunk_index_to_bitmap_indices(9));
assert_eq!((1, 7), alloc.chunk_index_to_bitmap_indices(15));
}
#[test]
fn test_chunk_is_free() {
let (mut heap, mut heap_bitmap) = helpers::create_heap_and_bitmap_vectors();
heap_bitmap[0] = 0x2f;
let alloc: ChunkAllocator = ChunkAllocator::new(&mut heap, &mut heap_bitmap).unwrap();
assert!(!alloc.chunk_is_free(0));
assert!(!alloc.chunk_is_free(1));
assert!(!alloc.chunk_is_free(2));
assert!(!alloc.chunk_is_free(3));
assert!(alloc.chunk_is_free(4));
assert!(!alloc.chunk_is_free(5));
}
#[test]
fn test_chunk_index_to_ptr() {
let (mut heap, mut heap_bitmap) = helpers::create_heap_and_bitmap_vectors();
let heap_ptr = heap.as_ptr();
let alloc: ChunkAllocator = ChunkAllocator::new(&mut heap, &mut heap_bitmap).unwrap();
unsafe {
assert_eq!(heap_ptr, alloc.chunk_index_to_ptr(0));
assert_eq!(
heap_ptr.add(alloc.chunk_size() * 1),
alloc.chunk_index_to_ptr(1)
);
assert_eq!(
heap_ptr.add(alloc.chunk_size() * 7),
alloc.chunk_index_to_ptr(7)
);
}
}
#[test]
fn test_find_free_continuous_memory_region_basic() {
let (mut heap, mut heap_bitmap) = helpers::create_heap_and_bitmap_vectors();
let mut alloc: ChunkAllocator = ChunkAllocator::new(&mut heap, &mut heap_bitmap).unwrap();
assert_eq!(alloc.chunk_size(), DEFAULT_CHUNK_SIZE);
assert_eq!(alloc.chunk_count(), 32);
assert_eq!(
0,
alloc.find_free_continuous_memory_region(1, 4096).unwrap()
);
alloc.mark_chunk_as_used(0);
alloc.maybe_next_free_chunk = (1, 1);
assert_eq!(1, alloc.find_free_continuous_memory_region(1, 1).unwrap());
alloc.maybe_next_free_chunk = (2, 1);
assert_eq!(
16,
alloc.find_free_continuous_memory_region(1, 4096).unwrap()
);
alloc.mark_chunk_as_used(16);
alloc.maybe_next_free_chunk = (17, 1);
assert!(
alloc.find_free_continuous_memory_region(1, 4096).is_err(),
"out of memory; only 2 pages of memory"
);
alloc.mark_chunk_as_free(0);
assert_eq!(
0,
alloc.find_free_continuous_memory_region(1, 4096).unwrap()
);
}
#[test]
fn test_find_free_continuous_memory_region_full_1() {
let (mut heap, mut heap_bitmap) = helpers::create_heap_and_bitmap_vectors();
let mut alloc: ChunkAllocator = ChunkAllocator::new(&mut heap, &mut heap_bitmap).unwrap();
assert_eq!(alloc.chunk_size(), DEFAULT_CHUNK_SIZE);
assert_eq!(alloc.chunk_count(), 32);
assert!(
alloc.find_free_continuous_memory_region(33, 1).is_err(),
"out of memory"
);
let res = alloc.find_free_continuous_memory_region(32, 1);
assert!(res.is_ok());
assert_eq!(0, res.unwrap());
for i in 0..32 {
alloc.mark_chunk_as_used(i);
}
assert!(
alloc.find_free_continuous_memory_region(32, 1).is_err(),
"out of memory"
);
for i in 16..32 {
alloc.mark_chunk_as_free(i);
}
let res = alloc.find_free_continuous_memory_region(16, 4096);
assert_eq!(16, res.unwrap());
for i in 16..32 {
alloc.mark_chunk_as_used(i);
}
}
#[test]
fn test_find_free_continuous_memory_region_full_2() {
let (mut heap, mut heap_bitmap) = helpers::create_heap_and_bitmap_vectors();
let mut alloc: ChunkAllocator = ChunkAllocator::new(&mut heap, &mut heap_bitmap).unwrap();
assert_eq!(alloc.chunk_size(), DEFAULT_CHUNK_SIZE);
assert_eq!(alloc.chunk_count(), 32);
alloc.mark_chunk_as_used(0);
alloc.mark_chunk_as_used(1);
alloc.mark_chunk_as_used(2);
alloc.mark_chunk_as_used(16);
assert!(alloc.find_free_continuous_memory_region(
1,
4096).is_err(),
"out of memory! chunks 0 and 16 are occupied; the only available page-aligned addresses"
);
assert_eq!(17, alloc.find_free_continuous_memory_region(15, 1).unwrap(),);
}
}