2 * lock-free-alloc.c: Lock free allocator.
4 * (C) Copyright 2011 Novell, Inc
6 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
10 * This is a simplified version of the lock-free allocator described in
12 * Scalable Lock-Free Dynamic Memory Allocation
13 * Maged M. Michael, PLDI 2004
15 * I could not get Michael's allocator working bug free under heavy
16 * stress tests. The paper doesn't provide correctness proof and after
17 * failing to formalize the ownership of descriptors I devised this
20 * Allocation within superblocks proceeds exactly like in Michael's
21 * allocator. The simplification is that a thread has to "acquire" a
22 * descriptor before it can allocate from its superblock. While it owns
23 * the descriptor no other thread can acquire and hence allocate from
24 * it. A consequence of this is that the ABA problem cannot occur, so
25 * we don't need the tag field and don't have to use 64 bit CAS.
27 * Descriptors are stored in two locations: The partial queue and the
28 * active field. They can only be in at most one of those at one time.
29 * If a thread wants to allocate, it needs to get a descriptor. It
30 * tries the active descriptor first, CASing it to NULL. If that
31 * doesn't work, it gets a descriptor out of the partial queue. Once it
32 * has the descriptor it owns it because it is not referenced anymore.
33 * It allocates a slot and then gives the descriptor back (unless it is
36 * Note that it is still possible that a slot is freed while an
37 * allocation is in progress from the same superblock. Ownership in
38 * this case is not complicated, though. If the block was FULL and the
39 * free set it to PARTIAL, the free now owns the block (because FULL
40 * blocks are not referenced from partial and active) and has to give it
41 * back. If the block was PARTIAL then the free doesn't own the block
42 * (because it's either still referenced, or an alloc owns it). A
43 * special case of this is that it has changed from PARTIAL to EMPTY and
44 * now needs to be retired. Technically, the free wouldn't have to do
45 * anything in this case because the first thing an alloc does when it
46 * gets ownership of a descriptor is to check whether it is EMPTY and
47 * retire it if that is the case. As an optimization, our free does try
48 * to acquire the descriptor (by CASing the active field, which, if it
49 * is lucky, points to that descriptor) and if it can do so, retire it.
50 * If it can't, it tries to retire other descriptors from the partial
51 * queue, so that we can be sure that even if no more allocations
52 * happen, descriptors are still retired. This is analogous to what
53 * Michael's allocator does.
55 * Another difference to Michael's allocator is not related to
56 * concurrency, however: We don't point from slots to descriptors.
57 * Instead we allocate superblocks aligned and point from the start of
58 * the superblock to the descriptor, so we only need one word of
59 * metadata per superblock.
61 * FIXME: Having more than one allocator per size class is probably
62 * buggy because it was never tested.
68 #include <mono/utils/atomic.h>
69 #ifdef SGEN_WITHOUT_MONO
70 #include <mono/sgen/sgen-gc.h>
71 #include <mono/sgen/sgen-client.h>
73 #include <mono/utils/mono-mmap.h>
75 #include <mono/utils/mono-membar.h>
76 #include <mono/utils/hazard-pointer.h>
77 #include <mono/utils/lock-free-queue.h>
79 #include <mono/utils/lock-free-alloc.h>
81 //#define DESC_AVAIL_DUMMY
98 typedef struct _MonoLockFreeAllocDescriptor Descriptor;
99 struct _MonoLockFreeAllocDescriptor {
100 MonoLockFreeQueueNode node;
101 MonoLockFreeAllocator *heap;
102 volatile Anchor anchor;
103 unsigned int slot_size;
104 unsigned int block_size;
105 unsigned int max_count;
107 #ifndef DESC_AVAIL_DUMMY
108 Descriptor * volatile next;
110 gboolean in_use; /* used for debugging only */
113 #define NUM_DESC_BATCH 64
115 static MONO_ALWAYS_INLINE gpointer
116 sb_header_for_addr (gpointer addr, size_t block_size)
118 return (gpointer)(((size_t)addr) & (~(block_size - 1)));
121 /* Taken from SGen */
124 prot_flags_for_activate (int activate)
126 unsigned long prot_flags = activate? MONO_MMAP_READ|MONO_MMAP_WRITE: MONO_MMAP_NONE;
127 return prot_flags | MONO_MMAP_PRIVATE | MONO_MMAP_ANON;
131 alloc_sb (Descriptor *desc)
133 static int pagesize = -1;
138 pagesize = mono_pagesize ();
140 sb_header = desc->block_size == pagesize ?
141 mono_valloc (NULL, desc->block_size, prot_flags_for_activate (TRUE)) :
142 mono_valloc_aligned (desc->block_size, desc->block_size, prot_flags_for_activate (TRUE));
144 g_assert (sb_header == sb_header_for_addr (sb_header, desc->block_size));
146 *(Descriptor**)sb_header = desc;
147 //g_print ("sb %p for %p\n", sb_header, desc);
149 return (char*)sb_header + LOCK_FREE_ALLOC_SB_HEADER_SIZE;
153 free_sb (gpointer sb, size_t block_size)
155 gpointer sb_header = sb_header_for_addr (sb, block_size);
156 g_assert ((char*)sb_header + LOCK_FREE_ALLOC_SB_HEADER_SIZE == sb);
157 mono_vfree (sb_header, block_size);
158 //g_print ("free sb %p\n", sb_header);
161 #ifndef DESC_AVAIL_DUMMY
162 static Descriptor * volatile desc_avail;
167 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
173 desc = (Descriptor *) get_hazardous_pointer ((gpointer * volatile)&desc_avail, hp, 1);
175 Descriptor *next = desc->next;
176 success = (InterlockedCompareExchangePointer ((gpointer * volatile)&desc_avail, next, desc) == desc);
178 size_t desc_size = sizeof (Descriptor);
182 desc = (Descriptor *) mono_valloc (NULL, desc_size * NUM_DESC_BATCH, prot_flags_for_activate (TRUE));
184 /* Organize into linked list. */
186 for (i = 0; i < NUM_DESC_BATCH; ++i) {
187 Descriptor *next = (i == (NUM_DESC_BATCH - 1)) ? NULL : (Descriptor*)((char*)desc + ((i + 1) * desc_size));
189 mono_lock_free_queue_node_init (&d->node, TRUE);
193 mono_memory_write_barrier ();
195 success = (InterlockedCompareExchangePointer ((gpointer * volatile)&desc_avail, desc->next, NULL) == NULL);
198 mono_vfree (desc, desc_size * NUM_DESC_BATCH);
201 mono_hazard_pointer_clear (hp, 1);
207 g_assert (!desc->in_use);
214 desc_enqueue_avail (gpointer _desc)
216 Descriptor *desc = (Descriptor *) _desc;
217 Descriptor *old_head;
219 g_assert (desc->anchor.data.state == STATE_EMPTY);
220 g_assert (!desc->in_use);
223 old_head = desc_avail;
224 desc->next = old_head;
225 mono_memory_write_barrier ();
226 } while (InterlockedCompareExchangePointer ((gpointer * volatile)&desc_avail, desc, old_head) != old_head);
230 desc_retire (Descriptor *desc)
232 g_assert (desc->anchor.data.state == STATE_EMPTY);
233 g_assert (desc->in_use);
234 desc->in_use = FALSE;
235 free_sb (desc->sb, desc->block_size);
236 mono_thread_hazardous_try_free (desc, desc_enqueue_avail);
239 MonoLockFreeQueue available_descs;
244 Descriptor *desc = (Descriptor*)mono_lock_free_queue_dequeue (&available_descs);
249 return calloc (1, sizeof (Descriptor));
253 desc_retire (Descriptor *desc)
255 free_sb (desc->sb, desc->block_size);
256 mono_lock_free_queue_enqueue (&available_descs, &desc->node);
261 list_get_partial (MonoLockFreeAllocSizeClass *sc)
264 Descriptor *desc = (Descriptor*) mono_lock_free_queue_dequeue (&sc->partial);
267 if (desc->anchor.data.state != STATE_EMPTY)
274 desc_put_partial (gpointer _desc)
276 Descriptor *desc = (Descriptor *) _desc;
278 g_assert (desc->anchor.data.state != STATE_FULL);
280 mono_lock_free_queue_node_unpoison (&desc->node);
281 mono_lock_free_queue_enqueue (&desc->heap->sc->partial, &desc->node);
285 list_put_partial (Descriptor *desc)
287 g_assert (desc->anchor.data.state != STATE_FULL);
288 mono_thread_hazardous_try_free (desc, desc_put_partial);
292 list_remove_empty_desc (MonoLockFreeAllocSizeClass *sc)
294 int num_non_empty = 0;
296 Descriptor *desc = (Descriptor*) mono_lock_free_queue_dequeue (&sc->partial);
300 * We don't need to read atomically because we're the
301 * only thread that references this descriptor.
303 if (desc->anchor.data.state == STATE_EMPTY) {
306 g_assert (desc->heap->sc == sc);
307 mono_thread_hazardous_try_free (desc, desc_put_partial);
308 if (++num_non_empty >= 2)
315 heap_get_partial (MonoLockFreeAllocator *heap)
317 return list_get_partial (heap->sc);
321 heap_put_partial (Descriptor *desc)
323 list_put_partial (desc);
327 set_anchor (Descriptor *desc, Anchor old_anchor, Anchor new_anchor)
329 if (old_anchor.data.state == STATE_EMPTY)
330 g_assert (new_anchor.data.state == STATE_EMPTY);
332 return InterlockedCompareExchange (&desc->anchor.value, new_anchor.value, old_anchor.value) == old_anchor.value;
336 alloc_from_active_or_partial (MonoLockFreeAllocator *heap)
339 Anchor old_anchor, new_anchor;
345 if (InterlockedCompareExchangePointer ((gpointer * volatile)&heap->active, NULL, desc) != desc)
348 desc = heap_get_partial (heap);
353 /* Now we own the desc. */
357 new_anchor = old_anchor = *(volatile Anchor*)&desc->anchor.value;
358 if (old_anchor.data.state == STATE_EMPTY) {
359 /* We must free it because we own it. */
363 g_assert (old_anchor.data.state == STATE_PARTIAL);
364 g_assert (old_anchor.data.count > 0);
366 addr = (char*)desc->sb + old_anchor.data.avail * desc->slot_size;
368 mono_memory_read_barrier ();
370 next = *(unsigned int*)addr;
371 g_assert (next < LOCK_FREE_ALLOC_SB_USABLE_SIZE (desc->block_size) / desc->slot_size);
373 new_anchor.data.avail = next;
374 --new_anchor.data.count;
376 if (new_anchor.data.count == 0)
377 new_anchor.data.state = STATE_FULL;
378 } while (!set_anchor (desc, old_anchor, new_anchor));
380 /* If the desc is partial we have to give it back. */
381 if (new_anchor.data.state == STATE_PARTIAL) {
382 if (InterlockedCompareExchangePointer ((gpointer * volatile)&heap->active, desc, NULL) != NULL)
383 heap_put_partial (desc);
390 alloc_from_new_sb (MonoLockFreeAllocator *heap)
392 unsigned int slot_size, block_size, count, i;
393 Descriptor *desc = desc_alloc ();
395 slot_size = desc->slot_size = heap->sc->slot_size;
396 block_size = desc->block_size = heap->sc->block_size;
397 count = LOCK_FREE_ALLOC_SB_USABLE_SIZE (block_size) / slot_size;
401 * Setting avail to 1 because 0 is the block we're allocating
404 desc->anchor.data.avail = 1;
405 desc->slot_size = heap->sc->slot_size;
406 desc->max_count = count;
408 desc->anchor.data.count = desc->max_count - 1;
409 desc->anchor.data.state = STATE_PARTIAL;
411 desc->sb = alloc_sb (desc);
413 /* Organize blocks into linked list. */
414 for (i = 1; i < count - 1; ++i)
415 *(unsigned int*)((char*)desc->sb + i * slot_size) = i + 1;
417 mono_memory_write_barrier ();
419 /* Make it active or free it again. */
420 if (InterlockedCompareExchangePointer ((gpointer * volatile)&heap->active, desc, NULL) == NULL) {
423 desc->anchor.data.state = STATE_EMPTY;
430 mono_lock_free_alloc (MonoLockFreeAllocator *heap)
436 addr = alloc_from_active_or_partial (heap);
440 addr = alloc_from_new_sb (heap);
449 mono_lock_free_free (gpointer ptr, size_t block_size)
451 Anchor old_anchor, new_anchor;
454 MonoLockFreeAllocator *heap = NULL;
456 desc = *(Descriptor**) sb_header_for_addr (ptr, block_size);
457 g_assert (block_size == desc->block_size);
462 new_anchor = old_anchor = *(volatile Anchor*)&desc->anchor.value;
463 *(unsigned int*)ptr = old_anchor.data.avail;
464 new_anchor.data.avail = ((char*)ptr - (char*)sb) / desc->slot_size;
465 g_assert (new_anchor.data.avail < LOCK_FREE_ALLOC_SB_USABLE_SIZE (block_size) / desc->slot_size);
467 if (old_anchor.data.state == STATE_FULL)
468 new_anchor.data.state = STATE_PARTIAL;
470 if (++new_anchor.data.count == desc->max_count) {
472 new_anchor.data.state = STATE_EMPTY;
474 } while (!set_anchor (desc, old_anchor, new_anchor));
476 if (new_anchor.data.state == STATE_EMPTY) {
477 g_assert (old_anchor.data.state != STATE_EMPTY);
479 if (InterlockedCompareExchangePointer ((gpointer * volatile)&heap->active, NULL, desc) == desc) {
480 /* We own it, so we free it. */
484 * Somebody else must free it, so we do some
485 * freeing for others.
487 list_remove_empty_desc (heap->sc);
489 } else if (old_anchor.data.state == STATE_FULL) {
491 * Nobody owned it, now we do, so we need to give it
495 g_assert (new_anchor.data.state == STATE_PARTIAL);
497 if (InterlockedCompareExchangePointer ((gpointer * volatile)&desc->heap->active, desc, NULL) != NULL)
498 heap_put_partial (desc);
502 #define g_assert_OR_PRINT(c, format, ...) do { \
505 g_print ((format), ## __VA_ARGS__); \
512 descriptor_check_consistency (Descriptor *desc, gboolean print)
514 int count = desc->anchor.data.count;
515 int max_count = LOCK_FREE_ALLOC_SB_USABLE_SIZE (desc->block_size) / desc->slot_size;
517 gboolean* linked = alloca(max_count*sizeof(gboolean));
519 gboolean linked [max_count];
524 #ifndef DESC_AVAIL_DUMMY
527 for (avail = desc_avail; avail; avail = avail->next)
528 g_assert_OR_PRINT (desc != avail, "descriptor is in the available list\n");
531 g_assert_OR_PRINT (desc->slot_size == desc->heap->sc->slot_size, "slot size doesn't match size class\n");
534 g_print ("descriptor %p is ", desc);
536 switch (desc->anchor.data.state) {
540 g_assert_OR_PRINT (count == 0, "count is not zero: %d\n", count);
544 g_print ("partial\n");
545 g_assert_OR_PRINT (count < max_count, "count too high: is %d but must be below %d\n", count, max_count);
550 g_assert_OR_PRINT (count == max_count, "count is wrong: is %d but should be %d\n", count, max_count);
553 g_assert_OR_PRINT (FALSE, "invalid state\n");
556 for (i = 0; i < max_count; ++i)
559 index = desc->anchor.data.avail;
561 for (i = 0; i < count; ++i) {
562 gpointer addr = (char*)desc->sb + index * desc->slot_size;
563 g_assert_OR_PRINT (index >= 0 && index < max_count,
564 "index %d for %dth available slot, linked from %d, not in range [0 .. %d)\n",
565 index, i, last, max_count);
566 g_assert_OR_PRINT (!linked [index], "%dth available slot %d linked twice\n", i, index);
569 linked [index] = TRUE;
571 index = *(unsigned int*)addr;
576 mono_lock_free_allocator_check_consistency (MonoLockFreeAllocator *heap)
578 Descriptor *active = heap->active;
581 g_assert (active->anchor.data.state == STATE_PARTIAL);
582 descriptor_check_consistency (active, FALSE);
584 while ((desc = (Descriptor*)mono_lock_free_queue_dequeue (&heap->sc->partial))) {
585 g_assert (desc->anchor.data.state == STATE_PARTIAL || desc->anchor.data.state == STATE_EMPTY);
586 descriptor_check_consistency (desc, FALSE);
592 mono_lock_free_allocator_init_size_class (MonoLockFreeAllocSizeClass *sc, unsigned int slot_size, unsigned int block_size)
594 g_assert (block_size > 0);
595 g_assert ((block_size & (block_size - 1)) == 0); /* check if power of 2 */
596 g_assert (slot_size * 2 <= LOCK_FREE_ALLOC_SB_USABLE_SIZE (block_size));
598 mono_lock_free_queue_init (&sc->partial);
599 sc->slot_size = slot_size;
600 sc->block_size = block_size;
604 mono_lock_free_allocator_init_allocator (MonoLockFreeAllocator *heap, MonoLockFreeAllocSizeClass *sc)