forked from spaskalev/buddy_alloc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buddy_alloc.h
1793 lines (1496 loc) · 60.9 KB
/
buddy_alloc.h
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
/*
* Copyright 2021 Stanislav Paskalev <[email protected]>
*/
/*
* A binary buddy memory allocator
*
* To include and use it in your project do the following
* 1. Add buddy_alloc.h (this file) to your include directory
* 2. Include the header in places where you need to use the allocator
* 3. In one of your source files #define BUDDY_ALLOC_IMPLEMENTATION
* and then import the header. This will insert the implementation.
*/
#ifndef BUDDY_ALLOC_H
#define BUDDY_ALLOC_H
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
struct buddy;
/* Returns the size of a buddy required to manage of block of the specified size */
size_t buddy_sizeof(size_t memory_size);
/* Initializes a binary buddy memory allocator at the specified location */
struct buddy *buddy_init(unsigned char *at, unsigned char *main, size_t memory_size);
/*
* Initializes a binary buddy memory allocator embedded in the specified arena.
* The arena's capacity is reduced to account for the allocator metadata.
*/
struct buddy *buddy_embed(unsigned char *main, size_t memory_size);
/* Resizes the arena and metadata to a new size. */
struct buddy *buddy_resize(struct buddy *buddy, size_t new_memory_size);
/* Tests if the allocation can be shrunk in half */
unsigned int buddy_can_shrink(struct buddy *buddy);
/* Tests if the allocation is completely empty */
unsigned int buddy_is_empty(struct buddy *buddy);
/* Reports the arena size */
size_t buddy_arena_size(struct buddy *buddy);
/*
* Allocation functions
*/
/* Use the specified buddy to allocate memory. See malloc. */
void *buddy_malloc(struct buddy *buddy, size_t requested_size);
/* Use the specified buddy to allocate zeroed memory. See calloc. */
void *buddy_calloc(struct buddy *buddy, size_t members_count, size_t member_size);
/* Realloc semantics are a joke. See realloc. */
void *buddy_realloc(struct buddy *buddy, void *ptr, size_t requested_size);
/* Realloc-like behavior that checks for overflow. See reallocarray*/
void *buddy_reallocarray(struct buddy *buddy, void *ptr,
size_t members_count, size_t member_size);
/* Use the specified buddy to free memory. See free. */
void buddy_free(struct buddy *buddy, void *ptr);
/* A (safer) free with a size. Will not free unless the size fits the target span. */
void buddy_safe_free(struct buddy *buddy, void *ptr, size_t requested_size);
/*
* Reservation functions
*/
/* Reserve a range by marking it as allocated. Useful for dealing with physical memory. */
void buddy_reserve_range(struct buddy *buddy, void *ptr, size_t requested_size);
/* Release a reserved memory range. Unsafe, this can mess up other allocations if called with wrong parameters! */
void buddy_unsafe_release_range(struct buddy *buddy, void *ptr, size_t requested_size);
/*
* Iteration functions
*/
/*
* Iterate through the allocated slots and call the provided function for each of them.
*
* If the provided function returns a non-NULL result the iteration stops and the result
* is returned to called. NULL is returned upon completing iteration without stopping.
*
* The iteration order is implementation-defined and may change between versions.
*/
void *buddy_walk(struct buddy *buddy, void *(fp)(void *ctx, void *addr, size_t slot_size), void *ctx);
/*
* Miscellaneous functions
*/
/*
* Calculates the fragmentation in the allocator in a 0.0 - 1.0 range.
* NOTE: if you are using a non-power-of-two sized arena the maximum upper bound can be lower.
*/
float buddy_fragmentation(struct buddy *buddy);
/*
* Configure the allocator to bias allocations on the left, lower side of its arena.
*/
void buddy_set_left_bias(struct buddy *buddy);
/*
* Configure the allocator to optimize allocations, instead of biasing them. This is the default mode.
*/
void buddy_set_optimal_fit(struct buddy *buddy);
#ifdef __cplusplus
}
#endif
#endif /* BUDDY_ALLOC_H */
#ifdef BUDDY_ALLOC_IMPLEMENTATION
#undef BUDDY_ALLOC_IMPLEMENTATION
#ifdef __cplusplus
extern "C" {
#endif
#ifndef BUDDY_ALLOC_ALIGN
#define BUDDY_ALLOC_ALIGN (sizeof(size_t) * CHAR_BIT)
#endif
#ifdef __cplusplus
#define BUDDY_ALIGNOF(x) alignof(x)
#else // not __cplusplus
#ifndef BUDDY_ALIGNOF
#ifndef _MSC_VER
#define BUDDY_ALIGNOF(x) __alignof__(x)
#else
#define BUDDY_ALIGNOF(x) _Alignof(x)
#endif
#endif
#endif // __cplusplus
// ssize_t is a POSIX extension
#if defined(_MSC_VER) && !defined(_SSIZE_T_DEFINED)
#if _WIN64
typedef signed long long ssize_t;
#else
typedef signed long ssize_t;
#endif
#define _SSIZE_T_DEFINED
#endif
/*
* Debug functions
*/
/* Implementation defined */
static void buddy_debug(FILE *stream, struct buddy *buddy);
struct buddy_tree;
struct buddy_tree_pos {
size_t index;
size_t depth;
};
#define INVALID_POS ((struct buddy_tree_pos){ 0, 0 })
struct buddy_tree_interval {
struct buddy_tree_pos from;
struct buddy_tree_pos to;
};
struct buddy_tree_walk_state {
struct buddy_tree_pos starting_pos;
struct buddy_tree_pos current_pos;
unsigned int going_up;
unsigned int walk_done;
};
/*
* Initialization functions
*/
/* Returns the size of a buddy allocation tree of the desired order*/
static size_t buddy_tree_sizeof(uint8_t order);
/* Initializes a buddy allocation tree at the specified location */
static struct buddy_tree *buddy_tree_init(unsigned char *at, uint8_t order);
/* Indicates whether this is a valid position for the tree */
static unsigned int buddy_tree_valid(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Returns the order of the specified buddy allocation tree */
static uint8_t buddy_tree_order(struct buddy_tree *t);
/* Resize the tree to the new order. When downsizing the left subtree is picked. */
/* Caller must ensure enough space for the new order. */
static void buddy_tree_resize(struct buddy_tree *t, uint8_t desired_order);
/*
* Navigation functions
*/
/* Returns a position at the root of a buddy allocation tree */
static struct buddy_tree_pos buddy_tree_root(void);
/* Returns the leftmost child node */
static struct buddy_tree_pos buddy_tree_leftmost_child(struct buddy_tree *t);
/* Returns the tree depth of the indicated position */
static inline size_t buddy_tree_depth(struct buddy_tree_pos pos);
/* Returns the left child node position. Does not check if that is a valid position */
static inline struct buddy_tree_pos buddy_tree_left_child(struct buddy_tree_pos pos);
/* Returns the right child node position. Does not check if that is a valid position */
static inline struct buddy_tree_pos buddy_tree_right_child(struct buddy_tree_pos pos);
/* Returns the current sibling node position. Does not check if that is a valid position */
static inline struct buddy_tree_pos buddy_tree_sibling(struct buddy_tree_pos pos);
/* Returns the parent node position or an invalid position if there is no parent node */
static inline struct buddy_tree_pos buddy_tree_parent(struct buddy_tree_pos pos);
/* Returns the right adjacent node position or an invalid position if there is no right adjacent node */
static struct buddy_tree_pos buddy_tree_right_adjacent(struct buddy_tree_pos pos);
/* Returns the at-depth index of the indicated position */
static size_t buddy_tree_index(struct buddy_tree_pos pos);
/* Return the interval of the deepest positions spanning the indicated position */
static struct buddy_tree_interval buddy_tree_interval(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Checks if one interval contains another */
static unsigned int buddy_tree_interval_contains(struct buddy_tree_interval outer,
struct buddy_tree_interval inner);
/* Return a walk state structure starting from the root of a tree */
static struct buddy_tree_walk_state buddy_tree_walk_state_root();
/* Walk the tree, keeping track in the provided state structure */
static unsigned int buddy_tree_walk(struct buddy_tree *t, struct buddy_tree_walk_state *state);
/*
* Allocation functions
*/
/* Returns the free capacity at or underneath the indicated position */
static size_t buddy_tree_status(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Marks the indicated position as allocated and propagates the change */
static void buddy_tree_mark(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Marks the indicated position as free and propagates the change */
static void buddy_tree_release(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Returns a free position at the specified depth or an invalid position */
static struct buddy_tree_pos buddy_tree_find_free(struct buddy_tree *t, uint8_t depth, uint8_t left_bias);
/* Tests if the incidated position is available for allocation */
static unsigned int buddy_tree_is_free(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Tests if the tree can be shrank in half */
static unsigned int buddy_tree_can_shrink(struct buddy_tree *t);
/*
* Debug functions
*/
/* Implementation defined */
static void buddy_tree_debug(FILE *stream, struct buddy_tree *t, struct buddy_tree_pos pos, size_t start_size);
/* Implementation defined */
static unsigned int buddy_tree_check_invariant(struct buddy_tree *t, struct buddy_tree_pos pos);
/* Report fragmentation in a 0.0 - 1.0 range */
static float buddy_tree_fragmentation(struct buddy_tree *t);
/*
* A char-backed bitset implementation
*/
static size_t bitset_sizeof(size_t elements);
static void bitset_set_range(unsigned char *bitset, size_t from_pos, size_t to_pos);
static void bitset_clear_range(unsigned char *bitset, size_t from_pos, size_t to_pos);
static size_t bitset_count_range(unsigned char *bitset, size_t from_pos, size_t to_pos);
static inline void bitset_set(unsigned char *bitset, size_t pos);
static inline void bitset_clear(unsigned char *bitset, size_t pos);
static inline unsigned int bitset_test(const unsigned char *bitset, size_t pos);
static void bitset_shift_left(unsigned char *bitset, size_t from_pos, size_t to_pos, size_t by);
static void bitset_shift_right(unsigned char *bitset, size_t from_pos, size_t to_pos, size_t by);
/*
* Debug functions
*/
/* Implementation defined */
static void bitset_debug(FILE *stream, unsigned char *bitset, size_t length);
/*
* Bits
*/
/* Returns the number of set bits in the given byte */
static unsigned int popcount_byte(unsigned char b);
/* Returns the index of the highest bit set (1-based) */
static size_t highest_bit_position(size_t value);
/* Returns the nearest larger or equal power of two */
static inline size_t ceiling_power_of_two(size_t value);
/*
* Math
*/
/* Approximates the square root of a float */
static inline float approximate_square_root(float f);
/*
Implementation
*/
const unsigned int BUDDY_RELATIVE_MODE = 1;
const unsigned int BUDDY_LEFT_BIAS = 2;
/*
* A binary buddy memory allocator
*/
struct buddy {
size_t memory_size;
size_t virtual_slots;
union {
unsigned char *main;
ptrdiff_t main_offset;
} arena;
size_t buddy_flags;
unsigned char buddy_tree[];
};
struct buddy_embed_check {
unsigned int can_fit;
size_t offset;
size_t buddy_size;
};
static size_t buddy_tree_order_for_memory(size_t memory_size);
static size_t depth_for_size(struct buddy *buddy, size_t requested_size);
static inline size_t size_for_depth(struct buddy *buddy, size_t depth);
static unsigned char *address_for_position(struct buddy *buddy, struct buddy_tree_pos pos);
static struct buddy_tree_pos position_for_address(struct buddy *buddy, const unsigned char *addr);
static unsigned char *buddy_main(struct buddy *buddy);
static unsigned int buddy_relative_mode(struct buddy *buddy);
static struct buddy_tree *buddy_tree(struct buddy *buddy);
static size_t buddy_effective_memory_size(struct buddy *buddy);
static void buddy_toggle_virtual_slots(struct buddy *buddy, unsigned int state);
static void buddy_toggle_range_reservation(struct buddy *buddy, void *ptr, size_t requested_size, unsigned int state);
static struct buddy *buddy_resize_standard(struct buddy *buddy, size_t new_memory_size);
static struct buddy *buddy_resize_embedded(struct buddy *buddy, size_t new_memory_size);
static unsigned int buddy_is_free(struct buddy *buddy, size_t from);
static unsigned int buddy_is_left_biased(struct buddy *buddy);
static struct buddy_embed_check buddy_embed_offset(size_t memory_size);
static struct buddy_tree_pos deepest_position_for_offset(struct buddy *buddy, size_t offset);
size_t buddy_sizeof(size_t memory_size) {
if (memory_size < BUDDY_ALLOC_ALIGN) {
return 0; /* invalid */
}
size_t buddy_tree_order = buddy_tree_order_for_memory(memory_size);
return sizeof(struct buddy) + buddy_tree_sizeof((uint8_t)buddy_tree_order);
}
struct buddy *buddy_init(unsigned char *at, unsigned char *main, size_t memory_size) {
if (at == NULL) {
return NULL;
}
if (main == NULL) {
return NULL;
}
if (at == main) {
return NULL;
}
size_t at_alignment = ((uintptr_t) at) % BUDDY_ALIGNOF(struct buddy);
if (at_alignment != 0) {
return NULL;
}
size_t main_alignment = ((uintptr_t) main) % BUDDY_ALIGNOF(size_t);
if (main_alignment != 0) {
return NULL;
}
/* Trim down memory to alignment */
if (memory_size % BUDDY_ALLOC_ALIGN) {
memory_size -= (memory_size % BUDDY_ALLOC_ALIGN);
}
size_t size = buddy_sizeof(memory_size);
if (size == 0) {
return NULL;
}
size_t buddy_tree_order = buddy_tree_order_for_memory(memory_size);
/* TODO check for overlap between buddy metadata and main block */
struct buddy *buddy = (struct buddy *) at;
buddy->arena.main = main;
buddy->memory_size = memory_size;
buddy->buddy_flags = 0;
buddy_tree_init(buddy->buddy_tree, (uint8_t) buddy_tree_order);
buddy_toggle_virtual_slots(buddy, 1);
return buddy;
}
struct buddy *buddy_embed(unsigned char *main, size_t memory_size) {
if (! main) {
return NULL;
}
struct buddy_embed_check result = buddy_embed_offset(memory_size);
if (! result.can_fit) {
return NULL;
}
struct buddy *buddy = buddy_init(main+result.offset, main, result.offset);
if (! buddy) { /* regular initialization failed */
return NULL;
}
buddy->buddy_flags |= BUDDY_RELATIVE_MODE;
buddy->arena.main_offset = (unsigned char *)buddy - main;
return buddy;
}
struct buddy *buddy_resize(struct buddy *buddy, size_t new_memory_size) {
if (new_memory_size == buddy->memory_size) {
return buddy;
}
if (buddy_relative_mode(buddy)) {
return buddy_resize_embedded(buddy, new_memory_size);
} else {
return buddy_resize_standard(buddy, new_memory_size);
}
}
static struct buddy *buddy_resize_standard(struct buddy *buddy, size_t new_memory_size) {
/* Trim down memory to alignment */
if (new_memory_size % BUDDY_ALLOC_ALIGN) {
new_memory_size -= (new_memory_size % BUDDY_ALLOC_ALIGN);
}
/* Account for tree use */
if (!buddy_is_free(buddy, new_memory_size)) {
return NULL;
}
/* Release the virtual slots */
buddy_toggle_virtual_slots(buddy, 0);
/* Calculate new tree order and resize it */
size_t new_buddy_tree_order = buddy_tree_order_for_memory(new_memory_size);
buddy_tree_resize(buddy_tree(buddy), (uint8_t) new_buddy_tree_order);
/* Store the new memory size and reconstruct any virtual slots */
buddy->memory_size = new_memory_size;
buddy_toggle_virtual_slots(buddy, 1);
/* Resize successful */
return buddy;
}
static struct buddy *buddy_resize_embedded(struct buddy *buddy, size_t new_memory_size) {
/* Ensure that the embedded allocator can fit */
struct buddy_embed_check result = buddy_embed_offset(new_memory_size);
if (! result.can_fit) {
return NULL;
}
/* Resize the allocator in the normal way */
struct buddy *resized = buddy_resize_standard(buddy, result.offset);
if (! resized) {
return NULL;
}
/* Get the absolute main address. The relative will be invalid after relocation. */
unsigned char *main = buddy_main(buddy);
/* Relocate the allocator */
unsigned char *buddy_destination = buddy_main(buddy) + result.offset;
memmove(buddy_destination, resized, result.buddy_size);
/* Update the main offset in the allocator */
struct buddy *relocated = (struct buddy *) buddy_destination;
relocated->arena.main_offset = buddy_destination - main;
return relocated;
}
unsigned int buddy_can_shrink(struct buddy *buddy) {
if (buddy == NULL) {
return 0;
}
return buddy_is_free(buddy, buddy->memory_size / 2);
}
unsigned int buddy_is_empty(struct buddy *buddy) {
if (buddy == NULL) {
return 1;
}
return buddy_is_free(buddy, 0);
}
size_t buddy_arena_size(struct buddy *buddy) {
if (buddy == NULL) {
return 0;
}
return buddy->memory_size;
}
static size_t buddy_tree_order_for_memory(size_t memory_size) {
size_t blocks = memory_size / BUDDY_ALLOC_ALIGN;
return highest_bit_position(ceiling_power_of_two(blocks));
}
void *buddy_malloc(struct buddy *buddy, size_t requested_size) {
if (buddy == NULL) {
return NULL;
}
if (requested_size == 0) {
/*
* Batshit crazy code exists that calls malloc(0) and expects
* a result that can be safely passed to free().
* And even though this allocator will safely handle a free(NULL)
* the particular batshit code will expect a non-NULL malloc(0) result!
*
* See also https://wiki.sei.cmu.edu/confluence/display/c/MEM04-C.+Beware+of+zero-length+allocations
*/
requested_size = 1;
}
if (requested_size > buddy->memory_size) {
return NULL;
}
size_t target_depth = depth_for_size(buddy, requested_size);
struct buddy_tree *tree = buddy_tree(buddy);
struct buddy_tree_pos pos = buddy_tree_find_free(tree, (uint8_t) target_depth, (uint8_t) buddy_is_left_biased(buddy));
if (! buddy_tree_valid(tree, pos)) {
return NULL; /* no slot found */
}
/* Allocate the slot */
buddy_tree_mark(tree, pos);
/* Find and return the actual memory address */
return address_for_position(buddy, pos);
}
void *buddy_calloc(struct buddy *buddy, size_t members_count, size_t member_size) {
if (members_count == 0 || member_size == 0) {
/* See the gleeful remark in malloc */
members_count = 1;
member_size = 1;
}
/* Check for overflow */
if (((members_count * member_size)/members_count) != member_size) {
return NULL;
}
size_t total_size = members_count * member_size;
void *result = buddy_malloc(buddy, total_size);
if (result) {
memset(result, 0, total_size);
}
return result;
}
void *buddy_realloc(struct buddy *buddy, void *ptr, size_t requested_size) {
/*
* realloc is a joke:
* - NULL ptr degrades into malloc
* - Zero size degrades into free
* - Same size as previous malloc/calloc/realloc is a no-op or a rellocation
* - Smaller size than previous *alloc decrease the allocated size with an optional rellocation
* - If the new allocation cannot be satisfied NULL is returned BUT the slot is preserved
* - Larger size than previous *alloc increase tha allocated size with an optional rellocation
*/
if (ptr == NULL) {
return buddy_malloc(buddy, requested_size);
}
if (requested_size == 0) {
buddy_free(buddy, ptr);
return NULL;
}
if (requested_size > buddy->memory_size) {
return NULL;
}
/* Find the position tracking this address */
struct buddy_tree *tree = buddy_tree(buddy);
struct buddy_tree_pos origin = position_for_address(buddy, (unsigned char *) ptr);
if (! buddy_tree_valid(tree, origin)) {
return NULL;
}
size_t current_depth = buddy_tree_depth(origin);
size_t target_depth = depth_for_size(buddy, requested_size);
/* Release the position and perform a search */
buddy_tree_release(tree, origin);
struct buddy_tree_pos new_pos = buddy_tree_find_free(tree, (uint8_t) target_depth, buddy_is_left_biased(buddy));
if (! buddy_tree_valid(tree, new_pos)) {
/* allocation failure, restore mark and return null */
buddy_tree_mark(tree, origin);
return NULL;
}
if (origin.index == new_pos.index) {
/* Allocated to the same slot, restore mark and return null */
buddy_tree_mark(tree, origin);
return ptr;
}
/* Copy the content */
void *source = address_for_position(buddy, origin);
void *destination = address_for_position(buddy, new_pos);
memmove(destination, source, size_for_depth(buddy,
current_depth > target_depth ? current_depth : target_depth));
/* Allocate and return */
buddy_tree_mark(tree, new_pos);
return destination;
}
void *buddy_reallocarray(struct buddy *buddy, void *ptr,
size_t members_count, size_t member_size) {
if (members_count == 0 || member_size == 0) {
return buddy_realloc(buddy, ptr, 0);
}
/* Check for overflow */
if ((members_count * member_size)/members_count != member_size) {
return NULL;
}
return buddy_realloc(buddy, ptr, members_count * member_size);
}
void buddy_free(struct buddy *buddy, void *ptr) {
if (buddy == NULL) {
return;
}
if (ptr == NULL) {
return;
}
unsigned char *dst = (unsigned char *)ptr;
unsigned char *main = buddy_main(buddy);
if ((dst < main) || (dst >= (main + buddy->memory_size))) {
return;
}
/* Find the position tracking this address */
struct buddy_tree *tree = buddy_tree(buddy);
struct buddy_tree_pos pos = position_for_address(buddy, dst);
if (! buddy_tree_valid(tree, pos)) {
return;
}
/* Release the position */
buddy_tree_release(tree, pos);
}
void buddy_safe_free(struct buddy *buddy, void *ptr, size_t requested_size) {
if (buddy == NULL) {
return;
}
if (ptr == NULL) {
return;
}
unsigned char *dst = (unsigned char *)ptr;
unsigned char *main = buddy_main(buddy);
if ((dst < main) || (dst >= (main + buddy->memory_size))) {
return;
}
/* Find the position tracking this address */
struct buddy_tree *tree = buddy_tree(buddy);
struct buddy_tree_pos pos = position_for_address(buddy, dst);
if (! buddy_tree_valid(tree, pos)) {
return;
}
size_t allocated_size_for_depth = size_for_depth(buddy, pos.depth);
if (requested_size < BUDDY_ALLOC_ALIGN) {
requested_size = BUDDY_ALLOC_ALIGN;
}
if (requested_size > allocated_size_for_depth) {
return;
}
if (requested_size <= (allocated_size_for_depth / 2)) {
return;
}
/* Release the position */
buddy_tree_release(tree, pos);
}
void buddy_reserve_range(struct buddy *buddy, void *ptr, size_t requested_size) {
buddy_toggle_range_reservation(buddy, ptr, requested_size, 1);
}
void buddy_unsafe_release_range(struct buddy *buddy, void *ptr, size_t requested_size) {
buddy_toggle_range_reservation(buddy, ptr, requested_size, 0);
}
void *buddy_walk(struct buddy *buddy,
void *(fp)(void *ctx, void *addr, size_t slot_size), void *ctx) {
if (buddy == NULL) {
return NULL;
}
if (fp == NULL) {
return NULL;
}
unsigned char *main = buddy_main(buddy);
size_t effective_memory_size = buddy_effective_memory_size(buddy);
struct buddy_tree *tree = buddy_tree(buddy);
size_t tree_order = buddy_tree_order(tree);
struct buddy_tree_walk_state state = buddy_tree_walk_state_root();
do {
size_t pos_status = buddy_tree_status(tree, state.current_pos);
if (pos_status == 0) { // Empty position
state.going_up = 1;
} else if (pos_status != (tree_order - state.current_pos.depth + 1)) { // Partially-allocated
continue;
} else { // Fully-allocated
// The tree doesn't make a distinction of a fully-allocated node
// due to a single allocation and a fully-allocated due to maxed out
// child allocations - we need to check the children.
// A child-allocated node will have both children set to their maximum
// but it is sufficient to check just one for non-zero.
struct buddy_tree_pos left = buddy_tree_left_child(state.current_pos);
if (buddy_tree_valid(tree, left) && buddy_tree_status(tree, left)) {
continue;
}
// Current node is allocated, process
size_t pos_size = effective_memory_size >> (state.current_pos.depth - 1u);
unsigned char *addr = address_for_position(buddy, state.current_pos);
if (((size_t)(addr - main + pos_size)) > buddy->memory_size) {
// Do not process virtual slots
// As virtual slots are on the right side of the tree
// if we see a one with the current iteration order this
// means that all subsequent slots will be virtual,
// hence we can return early.
return NULL;
} else {
void *result = (fp)(ctx, addr, pos_size);
if (result != NULL) {
return result;
}
}
}
} while (buddy_tree_walk(tree, &state));
return NULL;
}
float buddy_fragmentation(struct buddy *buddy) {
if (buddy == NULL) {
return 0;
}
return buddy_tree_fragmentation(buddy_tree(buddy));
}
void buddy_set_left_bias(struct buddy *buddy) {
if (buddy == NULL) {
return;
}
buddy->buddy_flags |= BUDDY_LEFT_BIAS;
}
void buddy_set_optimal_fit(struct buddy *buddy) {
if (buddy == NULL) {
return;
}
buddy->buddy_flags &= ~BUDDY_LEFT_BIAS;
}
static size_t depth_for_size(struct buddy *buddy, size_t requested_size) {
if (requested_size < BUDDY_ALLOC_ALIGN) {
requested_size = BUDDY_ALLOC_ALIGN;
}
size_t depth = 1;
size_t effective_memory_size = buddy_effective_memory_size(buddy);
while ((effective_memory_size / requested_size) >> 1u) {
depth++;
effective_memory_size >>= 1u;
}
return depth;
}
static inline size_t size_for_depth(struct buddy *buddy, size_t depth) {
depth += !depth; /* Silences a clang warning about undefined right shift */
return ceiling_power_of_two(buddy->memory_size) >> (depth-1);
}
static struct buddy_tree *buddy_tree(struct buddy *buddy) {
return (struct buddy_tree*) buddy->buddy_tree;
}
static size_t buddy_effective_memory_size(struct buddy *buddy) {
return ceiling_power_of_two(buddy->memory_size);
}
static unsigned char *address_for_position(struct buddy *buddy, struct buddy_tree_pos pos) {
size_t block_size = size_for_depth(buddy, buddy_tree_depth(pos));
size_t addr = block_size * buddy_tree_index(pos);
return buddy_main(buddy) + addr;
}
static struct buddy_tree_pos deepest_position_for_offset(struct buddy *buddy, size_t offset) {
size_t index = offset / BUDDY_ALLOC_ALIGN;
struct buddy_tree_pos pos = buddy_tree_leftmost_child(buddy_tree(buddy));
pos.index += index;
return pos;
}
static struct buddy_tree_pos position_for_address(struct buddy *buddy, const unsigned char *addr) {
/* Find the deepest position tracking this address */
unsigned char *main = buddy_main(buddy);
ptrdiff_t offset = addr - main;
#ifdef BUDDY_ALLOC_SAFETY
if (offset % BUDDY_ALLOC_ALIGN) {
return INVALID_POS; /* invalid alignment */
}
#endif
struct buddy_tree *tree = buddy_tree(buddy);
struct buddy_tree_pos pos = deepest_position_for_offset(buddy, offset);
/* Find the actual allocated position tracking this address */
while (buddy_tree_valid(tree, pos) && !buddy_tree_status(tree, pos)) {
pos = buddy_tree_parent(pos);
}
#ifdef BUDDY_ALLOC_SAFETY
if (address_for_position(buddy, pos) != addr) {
return INVALID_POS; /* invalid alignment */
}
#endif
return pos;
}
static unsigned char *buddy_main(struct buddy *buddy) {
if (buddy_relative_mode(buddy)) {
return (unsigned char *)buddy - buddy->arena.main_offset;
}
return buddy->arena.main;
}
static unsigned int buddy_relative_mode(struct buddy *buddy) {
return buddy->buddy_flags & BUDDY_RELATIVE_MODE;
}
static void buddy_toggle_virtual_slots(struct buddy *buddy, unsigned int state) {
size_t memory_size = buddy->memory_size;
/* Mask/unmask the virtual space if memory is not a power of two */
size_t effective_memory_size = buddy_effective_memory_size(buddy);
if (effective_memory_size == memory_size) {
/* Update the virtual slot count */
buddy->virtual_slots = 0;
return;
}
/* Get the area that we need to mask and pad it to alignment */
/* Node memory size is already aligned to BUDDY_ALLOC_ALIGN */
size_t delta = effective_memory_size - memory_size;
/* Update the virtual slot count */
buddy->virtual_slots = state ? (delta / BUDDY_ALLOC_ALIGN) : 0;
/* Determine whether to mark or release */
void (*toggle)(struct buddy_tree *, struct buddy_tree_pos) =
state ? &buddy_tree_mark : &buddy_tree_release;
struct buddy_tree *tree = buddy_tree(buddy);
struct buddy_tree_pos pos = buddy_tree_right_child(buddy_tree_root());
while (delta) {
size_t current_pos_size = size_for_depth(buddy, buddy_tree_depth(pos));
if (delta == current_pos_size) {
// toggle current pos
(*toggle)(tree, pos);
break;
}
if (delta <= (current_pos_size / 2)) {
// re-run for right child
pos = buddy_tree_right_child(pos);
continue;
} else {
// toggle right child
(*toggle)(tree, buddy_tree_right_child(pos));
// reduce delta
delta -= current_pos_size / 2;
// re-run for left child
pos = buddy_tree_left_child(pos);
continue;
}
}
}
static void buddy_toggle_range_reservation(struct buddy *buddy, void *ptr, size_t requested_size, unsigned int state) {
if (buddy == NULL) {
return;
}
if (ptr == NULL) {
return;
}
if (requested_size == 0) {
return;
}
unsigned char *dst = (unsigned char *)ptr;
unsigned char *main = buddy_main(buddy);
if ((dst < main) || ((dst + requested_size) > (main + buddy->memory_size))) {
return;
}
/* Determine whether to mark or release */
void (*toggle)(struct buddy_tree *, struct buddy_tree_pos) =
state ? &buddy_tree_mark : &buddy_tree_release;
/* Find the deepest position tracking this address */
struct buddy_tree *tree = buddy_tree(buddy);
ptrdiff_t offset = dst - main;
struct buddy_tree_pos pos = deepest_position_for_offset(buddy, offset);
/* Advance one position at a time and process */
while (requested_size) {
(*toggle)(tree, pos);
requested_size = (requested_size < BUDDY_ALLOC_ALIGN) ? 0 : (requested_size - BUDDY_ALLOC_ALIGN);
pos.index++;
}
return;
}
/* Internal function that checks if there are any allocations
after the indicated relative memory index. Used to check if
the arena can be downsized. */
static unsigned int buddy_is_free(struct buddy *buddy, size_t from) {
/* from is already adjusted for alignment */
size_t effective_memory_size = buddy_effective_memory_size(buddy);
size_t to = effective_memory_size -
((buddy->virtual_slots ? buddy->virtual_slots : 1) * BUDDY_ALLOC_ALIGN);
struct buddy_tree *t = buddy_tree(buddy);
struct buddy_tree_interval query_range = {0};
query_range.from = deepest_position_for_offset(buddy, from);
query_range.to = deepest_position_for_offset(buddy, to);
struct buddy_tree_pos pos = deepest_position_for_offset(buddy, from);
while(buddy_tree_valid(t, pos) && (pos.index < query_range.to.index)) {
struct buddy_tree_interval current_test_range = buddy_tree_interval(t, pos);
struct buddy_tree_interval parent_test_range =
buddy_tree_interval(t, buddy_tree_parent(pos));
while(buddy_tree_interval_contains(query_range, parent_test_range)) {
pos = buddy_tree_parent(pos);
current_test_range = parent_test_range;
parent_test_range = buddy_tree_interval(t, buddy_tree_parent(pos));
}
/* pos is now tracking an overlapping segment */
if (! buddy_tree_is_free(t, pos)) {
return 0;
}
/* Advance check */
pos = buddy_tree_right_adjacent(current_test_range.to);
}
return 1;
}