-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathcorealloc.h
More file actions
1583 lines (1401 loc) · 51.6 KB
/
Copy pathcorealloc.h
File metadata and controls
1583 lines (1401 loc) · 51.6 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
#pragma once
#include "../ds/ds.h"
#include "check_init.h"
#include "freelist.h"
#include "metadata.h"
#include "pool.h"
#include "remotecache.h"
#include "sizeclasstable.h"
#include "snmalloc/stl/new.h"
#include "ticker.h"
#if defined(_MSC_VER)
# define ALLOCATOR __declspec(allocator) __declspec(restrict)
#elif __has_attribute(malloc)
# define ALLOCATOR __attribute__((malloc))
#else
# define ALLOCATOR
#endif
namespace snmalloc
{
/**
* @brief This is the default continuation class used for handling successful,
* and failing allocations.
*
* @tparam zero_mem Specifies whether the allocated memory should be zeroed.
*
* The failure case sets errno to ENOMEM, as per the C standard.
*/
template<ZeroMem zero_mem = ZeroMem::NoZero>
class DefaultConts
{
public:
static void* success(void* p, size_t size, bool secondary_allocator = false)
{
UNUSED(secondary_allocator);
SNMALLOC_ASSERT(p != nullptr);
SNMALLOC_ASSERT(
secondary_allocator ||
is_start_of_object(size_to_sizeclass_full(size), address_cast(p)));
if (zero_mem == ZeroMem::YesZero)
{
// Zero the memory if requested.
return ::memset(p, 0, round_size(size));
}
return p;
}
static void* failure(size_t size) noexcept
{
UNUSED(size);
// If we are here, then the allocation failed.
// Set errno to ENOMEM, as per the C standard.
errno = ENOMEM;
// Return nullptr on failure.
return nullptr;
}
};
using Zero = DefaultConts<ZeroMem::YesZero>;
using Uninit = DefaultConts<ZeroMem::NoZero>;
template<typename Conts>
inline static SNMALLOC_FAST_PATH void*
finish_alloc(freelist::HeadPtr p, size_t size)
{
return Conts::success(capptr_reveal(p.as_void()), size, false);
}
struct FastFreeLists
{
// Free list per small size class. These are used for
// allocation on the fast path. This part of the code is inspired by
// mimalloc.
freelist::Iter<> small_fast_free_lists[NUM_SMALL_SIZECLASSES] = {};
};
/**
* The core, stateful, part of a memory allocator.
*
* The template parameter provides all of the global configuration for this
* instantiation of snmalloc. This includes three options that apply to this
* class:
*
* - `AllocIsPoolAllocated` defines whether this `Allocator`
* configuration should support pool allocation. This defaults to true but
* a configuration that allocates allocators eagerly may opt out.
* - `AllocOwnsLocalState` defines whether the `Allocator` owns the
* associated `LocalState` object. If this is true (the default) then
* `Allocator` embeds the LocalState object. If this is set to false
* then a `LocalState` object must be provided to the constructor. This
* allows external code to provide explicit configuration of the address
* range managed by this object.
* - `IsQueueInline` (defaults to true) defines whether the message queue
* (`RemoteAllocator`) for this class is inline or provided externally. If
* provided externally, then it must be set explicitly with
* `init_message_queue`.
*/
template<SNMALLOC_CONCEPT(IsConfigLazy) Config_>
class Allocator : public FastFreeLists,
public stl::conditional_t<
Config_::Options.AllocIsPoolAllocated,
Pooled<Allocator<Config_>>,
Empty>
{
public:
using Config = Config_;
private:
/**
* Define local names for specialised versions of various types that are
* specialised for the back-end that we are using.
* @{
*/
using BackendSlabMetadata = typename Config::Backend::SlabMetadata;
using PagemapEntry = typename Config::PagemapEntry;
/// }@
/**
* Remote deallocations for other threads
*/
RemoteDeallocCache<Config> remote_dealloc_cache;
/**
* Per size class list of active slabs for this allocator.
*/
struct SlabMetadataCache
{
SeqSet<BackendSlabMetadata> available{};
uint16_t unused = 0;
uint16_t length = 0;
} alloc_classes[NUM_SMALL_SIZECLASSES]{};
/**
* The set of all slabs and large allocations
* from this allocator that are full or almost full.
*/
SeqSet<BackendSlabMetadata> laden{};
/**
* Local entropy source and current version of keys for
* this thread
*/
LocalEntropy entropy;
/**
* Message queue for allocations being returned to this
* allocator
*/
stl::conditional_t<
Config::Options.IsQueueInline,
RemoteAllocator,
RemoteAllocator*>
remote_alloc;
/**
* The type used local state. This is defined by the back end.
*/
using LocalState = typename Config::LocalState;
/**
* A local area of address space managed by this allocator.
* Used to reduce calls on the global address space. This is inline if the
* core allocator owns the local state or indirect if it is owned
* externally.
*/
stl::conditional_t<
Config::Options.AllocOwnsLocalState,
LocalState,
LocalState*>
backend_state;
/**
* Ticker to query the clock regularly at a lower cost.
*/
Ticker<typename Config::Pal> ticker;
/**
* The message queue needs to be accessible from other threads
*
* In the cross trust domain version this is the minimum amount
* of allocator state that must be accessible to other threads.
*/
auto* public_state()
{
if constexpr (Config::Options.IsQueueInline)
{
return &remote_alloc;
}
else
{
return remote_alloc;
}
}
/**
* Return a pointer to the backend state.
*/
LocalState* backend_state_ptr()
{
if constexpr (Config::Options.AllocOwnsLocalState)
{
return &backend_state;
}
else
{
return backend_state;
}
}
/**
* Return this allocator's "truncated" ID, an integer useful as a hash
* value of this allocator.
*
* Specifically, this is the address of this allocator's message queue
* with the least significant bits missing, masked by SIZECLASS_MASK.
* This will be unique for Allocs with inline queues; Allocs with
* out-of-line queues must ensure that no two queues' addresses collide
* under this masking.
*/
size_t get_trunc_id()
{
return public_state()->trunc_id();
}
/**
* Abstracts access to the message queue to handle different
* layout configurations of the allocator.
*/
auto& message_queue()
{
return *public_state();
}
/**
* Check if this allocator has messages to deallocate blocks from another
* thread
*/
SNMALLOC_FAST_PATH bool has_messages()
{
return message_queue().can_dequeue();
}
/**
* Initialiser, shared code between the constructors for different
* configurations.
*/
void init()
{
#ifdef SNMALLOC_TRACING
message<1024>("Making an allocator.");
#endif
// Entropy must be first, so that all data-structures can use the key
// it generates.
// This must occur before any freelists are constructed.
entropy.init<typename Config::Pal>();
// Ignoring stats for now.
// stats().start();
// Initialise the remote cache
remote_dealloc_cache.init();
}
/**
* Initialiser, shared code between the constructors for different
* configurations.
*
* spare is the amount of space directly after the allocator that is
* reserved as meta-data, but is not required by this Allocator.
*/
void init(Range<capptr::bounds::Alloc>& spare)
{
init();
if (spare.length != 0)
{
/*
* Seed this frontend's private metadata allocation cache with any
* excess space from the metadata allocation holding the frontend
* Allocator object itself. This alleviates thundering herd
* contention on the backend during startup: each slab opened now
* makes one trip to the backend, for the slab itself, rather than
* two, for the slab and its metadata.
*/
Config::Backend::dealloc_meta_data(
get_backend_local_state(), spare.base, spare.length);
}
}
friend class ThreadAlloc;
constexpr Allocator(bool){};
public:
/**
* Constructor for the case that the core allocator owns the local state.
* SFINAE disabled if the allocator does not own the local state.
*
* spare is the amount of space directly after the allocator that is
* reserved as meta-data, but is not required by this Allocator.
*/
template<
typename Config__ = Config,
typename = stl::enable_if_t<Config__::Options.AllocOwnsLocalState>>
Allocator(Range<capptr::bounds::Alloc>& spare)
{
init(spare);
}
/**
* Constructor for the case that the core allocator does not owns the local
* state. SFINAE disabled if the allocator does own the local state.
*
* spare is the amount of space directly after the allocator that is
* reserved as meta-data, but is not required by this Allocator.
*/
template<
typename Config__ = Config,
typename = stl::enable_if_t<!Config__::Options.AllocOwnsLocalState>>
Allocator(
Range<capptr::bounds::Alloc>& spare, LocalState* backend = nullptr)
: backend_state(backend)
{
init(spare);
}
/**
* Constructor for the case that the core allocator does not owns the local
* state. SFINAE disabled if the allocator does own the local state.
*
* This constructor is used when the allocator is not pool allocated.
*/
template<
typename Config__ = Config,
typename = stl::enable_if_t<Config__::Options.AllocOwnsLocalState>>
Allocator()
{
init();
}
/**
* If the message queue is not inline, provide it. This will then
* configure the message queue for use.
*/
template<bool InlineQueue = Config::Options.IsQueueInline>
stl::enable_if_t<!InlineQueue> init_message_queue(RemoteAllocator* q)
{
remote_alloc = q;
}
/**
* Post deallocations onto other threads.
*
* Returns true if it actually performed a post,
* and false otherwise.
*/
SNMALLOC_FAST_PATH bool post()
{
// stats().remote_post(); // TODO queue not in line!
bool sent_something =
remote_dealloc_cache.template post<sizeof(Allocator)>(
backend_state_ptr(), public_state()->trunc_id());
return sent_something;
}
/**
* Accessor for the local state. This hides whether the local state is
* stored inline or provided externally from the rest of the code.
*/
SNMALLOC_FAST_PATH
LocalState& get_backend_local_state()
{
if constexpr (Config::Options.AllocOwnsLocalState)
{
return backend_state;
}
else
{
SNMALLOC_ASSERT(backend_state);
return *backend_state;
}
}
/**
* Handles the messages in the queue if there are any,
* and then calls the action.
*
* This is designed to provide a fast path common case that simply
* checks the queue and calls the action if it is empty. If there
* are messages, then it goes to the slow path, handle_message_queue_slow.
*
* This is heavily templated to cause inlining, and passing of arguments on
* the stack as often closing over the arguments would cause less good
* codegen.
*/
template<bool noexc, typename Action, typename... Args>
SNMALLOC_FAST_PATH decltype(auto)
handle_message_queue(Action action, Args... args) noexcept(noexc)
{
// Inline the empty check, but not necessarily the full queue handling.
if (SNMALLOC_LIKELY(!has_messages()))
{
return action(args...);
}
return handle_message_queue_slow<noexc>(action, args...);
}
/**
* Process remote frees into this allocator.
*/
template<bool noexc, typename Action, typename... Args>
SNMALLOC_SLOW_PATH decltype(auto)
handle_message_queue_slow(Action action, Args... args) noexcept(noexc)
{
bool need_post = false;
size_t bytes_freed = 0;
auto local_state = backend_state_ptr();
auto domesticate = [local_state](freelist::QueuePtr p)
SNMALLOC_FAST_PATH_LAMBDA {
return capptr_domesticate<Config>(local_state, p);
};
auto cb = [this, domesticate, &need_post, &bytes_freed](
capptr::Alloc<RemoteMessage> msg) SNMALLOC_FAST_PATH_LAMBDA {
auto& entry =
Config::Backend::get_metaentry(snmalloc::address_cast(msg));
handle_dealloc_remote(entry, msg, need_post, domesticate, bytes_freed);
return bytes_freed < REMOTE_BATCH_LIMIT;
};
#ifdef SNMALLOC_TRACING
message<1024>("Handling remote queue before proceeding...");
#endif
if constexpr (Config::Options.QueueHeadsAreTame)
{
/*
* The front of the queue has already been validated; just change the
* annotating type.
*/
auto domesticate_first =
[](freelist::QueuePtr p) SNMALLOC_FAST_PATH_LAMBDA {
return freelist::HeadPtr::unsafe_from(p.unsafe_ptr());
};
message_queue().dequeue(domesticate_first, domesticate, cb);
}
else
{
message_queue().dequeue(domesticate, domesticate, cb);
}
if (need_post)
{
post();
}
return action(args...);
}
/**
* Dealloc a message either by putting for a forward, or
* deallocating locally.
*
* need_post will be set to true, if capacity is exceeded.
*/
template<typename Domesticator_queue>
void handle_dealloc_remote(
const PagemapEntry& entry,
capptr::Alloc<RemoteMessage> msg,
bool& need_post,
Domesticator_queue domesticate,
size_t& bytes_returned)
{
// TODO this needs to not double count stats
// TODO this needs to not double revoke if using MTE
// TODO thread capabilities?
if (SNMALLOC_LIKELY(entry.get_remote() == public_state()))
{
auto meta = entry.get_slab_metadata();
auto unreturned = dealloc_local_objects_fast(
msg, entry, meta, entropy, domesticate, bytes_returned);
/*
* dealloc_local_objects_fast has updated the free list but not updated
* the slab metadata; it falls to us to do so. It is UNLIKELY that we
* will need to take further steps, but we might.
*/
if (SNMALLOC_UNLIKELY(unreturned.template step<true>()))
{
dealloc_local_object_slow(msg.as_void(), entry, meta);
while (SNMALLOC_UNLIKELY(unreturned.template step<false>()))
{
dealloc_local_object_meta(entry, meta);
}
}
return;
}
auto nelem = RemoteMessage::template ring_size<Config>(
msg,
freelist::Object::key_root,
entry.get_slab_metadata()->as_key_tweak(),
domesticate);
if (!need_post && !remote_dealloc_cache.reserve_space(entry, nelem))
{
need_post = true;
}
remote_dealloc_cache.template forward<sizeof(Allocator)>(
entry.get_remote()->trunc_id(), msg);
}
template<typename Domesticator>
SNMALLOC_FAST_PATH static auto dealloc_local_objects_fast(
capptr::Alloc<RemoteMessage> msg,
const PagemapEntry& entry,
BackendSlabMetadata* meta,
LocalEntropy& entropy,
Domesticator domesticate,
size_t& bytes_freed)
{
SNMALLOC_ASSERT(!meta->is_unused());
snmalloc_check_client(
mitigations(sanity_checks),
is_start_of_object(entry.get_sizeclass(), address_cast(msg)),
"Not deallocating start of an object");
size_t objsize = sizeclass_full_to_size(entry.get_sizeclass());
auto [curr, length] = RemoteMessage::template open_free_ring<Config>(
msg,
objsize,
freelist::Object::key_root,
meta->as_key_tweak(),
domesticate);
bytes_freed += objsize * length;
// Update the head and the next pointer in the free list.
meta->free_queue.append_segment(
curr,
msg.template as_reinterpret<freelist::Object::T<>>(),
length,
freelist::Object::key_root,
meta->as_key_tweak(),
entropy);
return meta->return_objects(length);
}
/*************************************************************************
* Allocation Code Overview
*
* The code is structured to allow the compiler to inline and turn most
* paths into tail calls.
*
* The overall shape is:
*
* - alloc(size_t)
* - small_alloc(size_t)
* - gets allocation from a fast free list and is done.
* - if no fast free list,
* - check for message queue
* - small_refill(size_t)
* - If another free list is available, use it.
* - Otherwise,
* - Check if the allocator has been initialised, if it hasn't
* restart with a fresh allocator.
* - Otherwise, call small_refill_slow(size_t) which allocates
* a new slab and fills it with a free list using
* alloc_new_list.
* - static alloc_not_small(size_t, Allocator*)
* - If size is zero, call small_alloc(1) - this deals with the
* annoying case of zero off the fast path.
* - Otherwise,
* - Check for initialisation, and
* - call backend to allocate a large allocation.
*************************************************************************/
/**
* Allocates a block of memory of the given size.
* @param size The size of the block to allocate.
* @return A pointer to the allocated block, or nullptr if the allocation
* failed.
* @tparam Conts : Carries two function success and failure, that are used
* to either apply additional operations in the case of success, such as
* zeroing, or to handle the failure case, such as set_new_handler, or
* throwing an exception or setting errno to ENOMEM.
* @tparam CheckInit is a class that can handle lazy initiasation if
* required. It is defaulted to do nothing.
*/
template<typename Conts = Uninit, typename CheckInit = CheckInitNoOp>
SNMALLOC_FAST_PATH ALLOCATOR void*
alloc(size_t size) noexcept(noexcept(Conts::failure(0)))
{
// Perform the - 1 on size, so that zero wraps around and ends up on
// slow path.
if (SNMALLOC_LIKELY(
(size - 1) <= (sizeclass_to_size(NUM_SMALL_SIZECLASSES - 1) - 1)))
{
// Small allocations are more likely. Improve
// branch prediction by placing this case first.
return small_alloc<Conts, CheckInit>(size);
}
return alloc_not_small<Conts, CheckInit>(size, this);
}
/**
* Fast allocation for small objects.
*/
template<typename Conts, typename CheckInit>
SNMALLOC_FAST_PATH void*
small_alloc(size_t size) noexcept(noexcept(Conts::failure(0)))
{
auto domesticate =
[this](freelist::QueuePtr p) SNMALLOC_FAST_PATH_LAMBDA {
return capptr_domesticate<Config>(backend_state_ptr(), p);
};
auto& key = freelist::Object::key_root;
smallsizeclass_t sizeclass = size_to_sizeclass(size);
auto* fl = &small_fast_free_lists[sizeclass];
if (SNMALLOC_LIKELY(!fl->empty()))
{
auto p = fl->take(key, domesticate);
return finish_alloc<Conts>(p, size);
}
return handle_message_queue<noexcept(Conts::failure(0))>(
[](
Allocator* alloc,
smallsizeclass_t sizeclass,
freelist::Iter<>* fl,
size_t size) SNMALLOC_FAST_PATH_LAMBDA {
return alloc->small_refill<Conts, CheckInit>(sizeclass, *fl, size);
},
this,
sizeclass,
fl,
size);
}
/**
* Allocation that are larger that will result in an allocation directly
* from the backend. This additionally checks for 0 size allocations and
* handles checking for messages and initialisation.
*
* Note this is a static method to switch the argument order to improve
* code quality as the calling code already has size in the first argument
* register.
*/
template<typename Conts, typename CheckInit>
static SNMALLOC_SLOW_PATH void* alloc_not_small(
size_t size, Allocator* self) noexcept(noexcept(Conts::failure(0)))
{
if (size == 0)
{
// Deal with alloc zero of with a small object here.
// Alternative semantics giving nullptr is also allowed by the
// standard.
return self->small_alloc<Conts, CheckInit>(1);
}
return self->template handle_message_queue<noexcept(Conts::failure(0))>(
[](Allocator* self, size_t size) SNMALLOC_FAST_PATH_LAMBDA {
return CheckInit::check_init(
[self, size]() SNMALLOC_FAST_PATH_LAMBDA {
if (size > bits::one_at_bit(bits::BITS - 1))
{
// Cannot allocate something that is more that half the size of
// the address space
return Conts::failure(size);
}
// Check if secondary allocator wants to offer the memory
void* result = Config::SecondaryAllocator::allocate(
[size]() -> stl::Pair<size_t, size_t> {
return {size, natural_alignment(size)};
});
if (result != nullptr)
{
return Conts::success(result, size, true);
}
// Grab slab of correct size
// Set remote as large allocator remote.
auto [chunk, meta] = Config::Backend::alloc_chunk(
self->get_backend_local_state(),
large_size_to_chunk_size(size),
PagemapEntry::encode(
self->public_state(), size_to_sizeclass_full(size)),
size_to_sizeclass_full(size));
#ifdef SNMALLOC_TRACING
message<1024>(
"size {} pow2size {}", size, bits::next_pow2_bits(size));
#endif
SNMALLOC_ASSERT(
(chunk.unsafe_ptr() == nullptr) == (meta == nullptr));
// set up meta data so sizeclass is correct, and hence alloc size,
// and external pointer. Initialise meta data for a successful
// large allocation.
if (meta != nullptr)
{
meta->initialise_large(
address_cast(chunk), freelist::Object::key_root);
self->laden.insert(meta);
// Make capptr system happy we are allowed to pass this to
// `success`.
auto p = capptr_reveal(
capptr_chunk_is_alloc(capptr_to_user_address_control(chunk)));
return Conts::success(p, size);
}
return Conts::failure(size);
},
[](Allocator* a, size_t size) SNMALLOC_FAST_PATH_LAMBDA {
return alloc_not_small<Conts, CheckInitNoOp>(size, a);
},
size);
},
self,
size);
}
template<typename Conts, typename CheckInit>
SNMALLOC_FAST_PATH void* small_refill(
smallsizeclass_t sizeclass,
freelist::Iter<>& fast_free_list,
size_t size) noexcept(noexcept(Conts::failure(0)))
{
void* result = Config::SecondaryAllocator::allocate(
[size]() -> stl::Pair<size_t, size_t> {
return {size, natural_alignment(size)};
});
if (result != nullptr)
{
result = Conts::success(result, size, true);
// We need to check for initialisation here in the case where
// this is the first allocation in the system, so snmalloc has
// not initialised the pagemap. If this allocation is subsequently
// deallocated, before snmalloc is initialised, then it will fail
// to access the pagemap.
return CheckInit::check_init(
[result]() { return result; },
[](Allocator*, void* result) { return result; },
result);
}
// Look to see if we can grab a free list.
auto& sl = alloc_classes[sizeclass].available;
if (SNMALLOC_LIKELY(alloc_classes[sizeclass].length > 0))
{
if constexpr (mitigations(random_extra_slab))
{
// Occassionally don't use the last list.
if (SNMALLOC_UNLIKELY(alloc_classes[sizeclass].length == 1))
{
if (entropy.next_bit() == 0)
return small_refill_slow<Conts, CheckInit>(
sizeclass, fast_free_list, size);
}
}
// Mitigations use LIFO to increase time to reuse.
auto meta = sl.template pop<!mitigations(reuse_LIFO)>();
// Drop length of sl, and empty count if it was empty.
alloc_classes[sizeclass].length--;
if (meta->needed() == 0)
alloc_classes[sizeclass].unused--;
auto domesticate =
[this](freelist::QueuePtr p) SNMALLOC_FAST_PATH_LAMBDA {
return capptr_domesticate<Config>(backend_state_ptr(), p);
};
auto [p, still_active] = BackendSlabMetadata::alloc_free_list(
domesticate, meta, fast_free_list, entropy, sizeclass);
if (still_active)
{
alloc_classes[sizeclass].length++;
sl.insert(meta);
}
else
{
laden.insert(meta);
}
auto r = finish_alloc<Conts>(p, size);
return ticker.check_tick(r);
}
return small_refill_slow<Conts, CheckInit>(
sizeclass, fast_free_list, size);
}
template<typename Conts, typename CheckInit>
SNMALLOC_SLOW_PATH void* small_refill_slow(
smallsizeclass_t sizeclass,
freelist::Iter<>& fast_free_list,
size_t size) noexcept(noexcept(Conts::failure(0)))
{
return CheckInit::check_init(
[this, size, sizeclass, &fast_free_list]() SNMALLOC_FAST_PATH_LAMBDA {
size_t rsize = sizeclass_to_size(sizeclass);
// No existing free list get a new slab.
size_t slab_size = sizeclass_to_slab_size(sizeclass);
#ifdef SNMALLOC_TRACING
message<1024>(
"small_refill_slow rsize={} slab size={}", rsize, slab_size);
#endif
auto [slab, meta] = Config::Backend::alloc_chunk(
get_backend_local_state(),
slab_size,
PagemapEntry::encode(
public_state(), sizeclass_t::from_small_class(sizeclass)),
sizeclass_t::from_small_class(sizeclass));
if (slab == nullptr)
{
return Conts::failure(sizeclass_to_size(sizeclass));
}
// Set meta slab to empty.
meta->initialise(
sizeclass, address_cast(slab), freelist::Object::key_root);
// Build a free list for the slab
alloc_new_list(slab, meta, rsize, slab_size, entropy);
auto domesticate =
[this](freelist::QueuePtr p) SNMALLOC_FAST_PATH_LAMBDA {
return capptr_domesticate<Config>(backend_state_ptr(), p);
};
auto [p, still_active] = BackendSlabMetadata::alloc_free_list(
domesticate, meta, fast_free_list, entropy, sizeclass);
if (still_active)
{
alloc_classes[sizeclass].length++;
alloc_classes[sizeclass].available.insert(meta);
}
else
{
laden.insert(meta);
}
auto r = finish_alloc<Conts>(p, size);
return ticker.check_tick(r);
},
[](Allocator* a, size_t size) SNMALLOC_FAST_PATH_LAMBDA {
return a->small_alloc<Conts, CheckInitNoOp>(size);
},
size);
}
static SNMALLOC_FAST_PATH void alloc_new_list(
capptr::Chunk<void>& bumpptr,
BackendSlabMetadata* meta,
size_t rsize,
size_t slab_size,
LocalEntropy& entropy)
{
auto slab_end = pointer_offset(bumpptr, slab_size + 1 - rsize);
auto key_tweak = meta->as_key_tweak();
auto& b = meta->free_queue;
if constexpr (mitigations(random_initial))
{
// Structure to represent the temporary list elements
struct PreAllocObject
{
capptr::AllocFull<PreAllocObject> next;
};
// The following code implements Sattolo's algorithm for generating
// random cyclic permutations. This implementation is in the opposite
// direction, so that the original space does not need initialising.
// This is described as outside-in without citation on Wikipedia,
// appears to be Folklore algorithm.
// Note the wide bounds on curr relative to each of the ->next fields;
// curr is not persisted once the list is built.
capptr::Chunk<PreAllocObject> curr =
pointer_offset(bumpptr, 0).template as_static<PreAllocObject>();
curr->next =
Aal::capptr_bound<PreAllocObject, capptr::bounds::AllocFull>(
curr, rsize);
uint16_t count = 1;
for (curr =
pointer_offset(curr, rsize).template as_static<PreAllocObject>();
curr.as_void() < slab_end;
curr =
pointer_offset(curr, rsize).template as_static<PreAllocObject>())
{
size_t insert_index = entropy.sample(count);
curr->next = stl::exchange(
pointer_offset(bumpptr, insert_index * rsize)
.template as_static<PreAllocObject>()
->next,
Aal::capptr_bound<PreAllocObject, capptr::bounds::AllocFull>(
curr, rsize));
count++;
}
// Pick entry into space, and then build linked list by traversing cycle
// to the start. Use ->next to jump from Chunk to Alloc.
auto start_index = entropy.sample(count);
auto start_ptr = pointer_offset(bumpptr, start_index * rsize)
.template as_static<PreAllocObject>()
->next;
auto curr_ptr = start_ptr;
do
{
auto next_ptr = curr_ptr->next;
b.add(
// Here begins our treatment of the heap as containing Wild pointers
freelist::Object::make<capptr::bounds::AllocWild>(
capptr_to_user_address_control(curr_ptr.as_void())),
freelist::Object::key_root,
key_tweak,
entropy);
curr_ptr = next_ptr;
} while (curr_ptr != start_ptr);
}
else
{
auto p = bumpptr;
do
{
b.add(
// Here begins our treatment of the heap as containing Wild pointers
freelist::Object::make<capptr::bounds::AllocWild>(
capptr_to_user_address_control(
Aal::capptr_bound<void, capptr::bounds::AllocFull>(
p.as_void(), rsize))),
freelist::Object::key_root,
key_tweak,
entropy);
p = pointer_offset(p, rsize);
} while (p < slab_end);
}
// This code consumes everything up to slab_end.
bumpptr = slab_end;
}
/***************************************************************************
* Deallocation code
*
* The main deallocation code is in dealloc. This, like alloc, takes a
* template to initialise the state of the allocator. It is possible for
* the first operation on a thread to be a deallocation.
*
* The algorithm is
* - dealloc(void*)
* - If object, originated from this allocator, then
* - dealloc_local_object(void*) which returns the object to the free
* list.
* - the free list length is updated, which can trigger a slow path for
* * large objects (dealloc_local_object_slow)
* * completely full list
* * previously empty list - (in checked builds we move the notion of
* empty to increase randomness)
* The later two are handled by dealloc_local_object_meta.
* In the completely full list case, then we heuristically determine
* if we should return slabs to the backend using dealloc_local_slabs
* - Otherwise, the object originated from another allocator, so we call
* - dealloc_remote(void*)
* - If there is sufficient budget to put in the remote cache, we do
* that and return.
* - Otherwise, we need to create some space in the remote cache using
* dealloc_remote_slow. This initially checks if we actually have a
* proper allocator.
* - If not, we acquire an allocator, and completely restart the
* deallocation process (we may acquire the originating allocator).
* - If we do have an allocator, we post the remote cache and this
* deallocation to the other allocators.