[runtime] Revert this change as it strips the volatileness of the load.
[mono.git] / mono / utils / lock-free-alloc.c
1 /*
2  * lock-free-alloc.c: Lock free allocator.
3  *
4  * (C) Copyright 2011 Novell, Inc
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining
7  * a copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sublicense, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  * 
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  * 
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24  */
25
26 /*
27  * This is a simplified version of the lock-free allocator described in
28  *
29  * Scalable Lock-Free Dynamic Memory Allocation
30  * Maged M. Michael, PLDI 2004
31  *
32  * I could not get Michael's allocator working bug free under heavy
33  * stress tests.  The paper doesn't provide correctness proof and after
34  * failing to formalize the ownership of descriptors I devised this
35  * simpler allocator.
36  *
37  * Allocation within superblocks proceeds exactly like in Michael's
38  * allocator.  The simplification is that a thread has to "acquire" a
39  * descriptor before it can allocate from its superblock.  While it owns
40  * the descriptor no other thread can acquire and hence allocate from
41  * it.  A consequence of this is that the ABA problem cannot occur, so
42  * we don't need the tag field and don't have to use 64 bit CAS.
43  *
44  * Descriptors are stored in two locations: The partial queue and the
45  * active field.  They can only be in at most one of those at one time.
46  * If a thread wants to allocate, it needs to get a descriptor.  It
47  * tries the active descriptor first, CASing it to NULL.  If that
48  * doesn't work, it gets a descriptor out of the partial queue.  Once it
49  * has the descriptor it owns it because it is not referenced anymore.
50  * It allocates a slot and then gives the descriptor back (unless it is
51  * FULL).
52  *
53  * Note that it is still possible that a slot is freed while an
54  * allocation is in progress from the same superblock.  Ownership in
55  * this case is not complicated, though.  If the block was FULL and the
56  * free set it to PARTIAL, the free now owns the block (because FULL
57  * blocks are not referenced from partial and active) and has to give it
58  * back.  If the block was PARTIAL then the free doesn't own the block
59  * (because it's either still referenced, or an alloc owns it).  A
60  * special case of this is that it has changed from PARTIAL to EMPTY and
61  * now needs to be retired.  Technically, the free wouldn't have to do
62  * anything in this case because the first thing an alloc does when it
63  * gets ownership of a descriptor is to check whether it is EMPTY and
64  * retire it if that is the case.  As an optimization, our free does try
65  * to acquire the descriptor (by CASing the active field, which, if it
66  * is lucky, points to that descriptor) and if it can do so, retire it.
67  * If it can't, it tries to retire other descriptors from the partial
68  * queue, so that we can be sure that even if no more allocations
69  * happen, descriptors are still retired.  This is analogous to what
70  * Michael's allocator does.
71  *
72  * Another difference to Michael's allocator is not related to
73  * concurrency, however: We don't point from slots to descriptors.
74  * Instead we allocate superblocks aligned and point from the start of
75  * the superblock to the descriptor, so we only need one word of
76  * metadata per superblock.
77  *
78  * FIXME: Having more than one allocator per size class is probably
79  * buggy because it was never tested.
80  */
81
82 #include <glib.h>
83 #include <stdlib.h>
84
85 #include <mono/utils/atomic.h>
86 #include <mono/utils/mono-mmap.h>
87 #include <mono/utils/mono-membar.h>
88 #include <mono/utils/hazard-pointer.h>
89 #include <mono/utils/lock-free-queue.h>
90
91 #include <mono/utils/lock-free-alloc.h>
92
93 //#define DESC_AVAIL_DUMMY
94
95 enum {
96         STATE_FULL,
97         STATE_PARTIAL,
98         STATE_EMPTY
99 };
100
101 typedef union {
102         gint32 value;
103         struct {
104                 guint32 avail : 15;
105                 guint32 count : 15;
106                 guint32 state : 2;
107         } data;
108 } Anchor;
109
110 typedef struct _MonoLockFreeAllocDescriptor Descriptor;
111 struct _MonoLockFreeAllocDescriptor {
112         MonoLockFreeQueueNode node;
113         MonoLockFreeAllocator *heap;
114         volatile Anchor anchor;
115         unsigned int slot_size;
116         unsigned int block_size;
117         unsigned int max_count;
118         gpointer sb;
119 #ifndef DESC_AVAIL_DUMMY
120         Descriptor * volatile next;
121 #endif
122         gboolean in_use;        /* used for debugging only */
123 };
124
125 #define NUM_DESC_BATCH  64
126
127 static MONO_ALWAYS_INLINE gpointer
128 sb_header_for_addr (gpointer addr, size_t block_size)
129 {
130         return (gpointer)(((size_t)addr) & (~(block_size - 1)));
131 }
132
133 /* Taken from SGen */
134
135 static unsigned long
136 prot_flags_for_activate (int activate)
137 {
138         unsigned long prot_flags = activate? MONO_MMAP_READ|MONO_MMAP_WRITE: MONO_MMAP_NONE;
139         return prot_flags | MONO_MMAP_PRIVATE | MONO_MMAP_ANON;
140 }
141
142 static gpointer
143 alloc_sb (Descriptor *desc)
144 {
145         static int pagesize = -1;
146
147         gpointer sb_header;
148
149         if (pagesize == -1)
150                 pagesize = mono_pagesize ();
151
152         sb_header = desc->block_size == pagesize ?
153                 mono_valloc (0, desc->block_size, prot_flags_for_activate (TRUE)) :
154                 mono_valloc_aligned (desc->block_size, desc->block_size, prot_flags_for_activate (TRUE));
155
156         g_assert (sb_header == sb_header_for_addr (sb_header, desc->block_size));
157
158         *(Descriptor**)sb_header = desc;
159         //g_print ("sb %p for %p\n", sb_header, desc);
160
161         return (char*)sb_header + LOCK_FREE_ALLOC_SB_HEADER_SIZE;
162 }
163
164 static void
165 free_sb (gpointer sb, size_t block_size)
166 {
167         gpointer sb_header = sb_header_for_addr (sb, block_size);
168         g_assert ((char*)sb_header + LOCK_FREE_ALLOC_SB_HEADER_SIZE == sb);
169         mono_vfree (sb_header, block_size);
170         //g_print ("free sb %p\n", sb_header);
171 }
172
173 #ifndef DESC_AVAIL_DUMMY
174 static Descriptor * volatile desc_avail;
175
176 static Descriptor*
177 desc_alloc (void)
178 {
179         MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
180         Descriptor *desc;
181
182         for (;;) {
183                 gboolean success;
184
185                 desc = (Descriptor *) get_hazardous_pointer ((gpointer * volatile)&desc_avail, hp, 1);
186                 if (desc) {
187                         Descriptor *next = desc->next;
188                         success = (InterlockedCompareExchangePointer ((gpointer * volatile)&desc_avail, next, desc) == desc);
189                 } else {
190                         size_t desc_size = sizeof (Descriptor);
191                         Descriptor *d;
192                         int i;
193
194                         desc = (Descriptor *) mono_valloc (0, desc_size * NUM_DESC_BATCH, prot_flags_for_activate (TRUE));
195
196                         /* Organize into linked list. */
197                         d = desc;
198                         for (i = 0; i < NUM_DESC_BATCH; ++i) {
199                                 Descriptor *next = (i == (NUM_DESC_BATCH - 1)) ? NULL : (Descriptor*)((char*)desc + ((i + 1) * desc_size));
200                                 d->next = next;
201                                 mono_lock_free_queue_node_init (&d->node, TRUE);
202                                 d = next;
203                         }
204
205                         mono_memory_write_barrier ();
206
207                         success = (InterlockedCompareExchangePointer ((gpointer * volatile)&desc_avail, desc->next, NULL) == NULL);
208
209                         if (!success)
210                                 mono_vfree (desc, desc_size * NUM_DESC_BATCH);
211                 }
212
213                 mono_hazard_pointer_clear (hp, 1);
214
215                 if (success)
216                         break;
217         }
218
219         g_assert (!desc->in_use);
220         desc->in_use = TRUE;
221
222         return desc;
223 }
224
225 static void
226 desc_enqueue_avail (gpointer _desc)
227 {
228         Descriptor *desc = (Descriptor *) _desc;
229         Descriptor *old_head;
230
231         g_assert (desc->anchor.data.state == STATE_EMPTY);
232         g_assert (!desc->in_use);
233
234         do {
235                 old_head = desc_avail;
236                 desc->next = old_head;
237                 mono_memory_write_barrier ();
238         } while (InterlockedCompareExchangePointer ((gpointer * volatile)&desc_avail, desc, old_head) != old_head);
239 }
240
241 static void
242 desc_retire (Descriptor *desc)
243 {
244         g_assert (desc->anchor.data.state == STATE_EMPTY);
245         g_assert (desc->in_use);
246         desc->in_use = FALSE;
247         free_sb (desc->sb, desc->block_size);
248         mono_thread_hazardous_free_or_queue (desc, desc_enqueue_avail, FALSE, TRUE);
249 }
250 #else
251 MonoLockFreeQueue available_descs;
252
253 static Descriptor*
254 desc_alloc (void)
255 {
256         Descriptor *desc = (Descriptor*)mono_lock_free_queue_dequeue (&available_descs);
257
258         if (desc)
259                 return desc;
260
261         return calloc (1, sizeof (Descriptor));
262 }
263
264 static void
265 desc_retire (Descriptor *desc)
266 {
267         free_sb (desc->sb, desc->block_size);
268         mono_lock_free_queue_enqueue (&available_descs, &desc->node);
269 }
270 #endif
271
272 static Descriptor*
273 list_get_partial (MonoLockFreeAllocSizeClass *sc)
274 {
275         for (;;) {
276                 Descriptor *desc = (Descriptor*) mono_lock_free_queue_dequeue (&sc->partial);
277                 if (!desc)
278                         return NULL;
279                 if (desc->anchor.data.state != STATE_EMPTY)
280                         return desc;
281                 desc_retire (desc);
282         }
283 }
284
285 static void
286 desc_put_partial (gpointer _desc)
287 {
288         Descriptor *desc = (Descriptor *) _desc;
289
290         g_assert (desc->anchor.data.state != STATE_FULL);
291
292         mono_lock_free_queue_node_free (&desc->node);
293         mono_lock_free_queue_enqueue (&desc->heap->sc->partial, &desc->node);
294 }
295
296 static void
297 list_put_partial (Descriptor *desc)
298 {
299         g_assert (desc->anchor.data.state != STATE_FULL);
300         mono_thread_hazardous_free_or_queue (desc, desc_put_partial, FALSE, TRUE);
301 }
302
303 static void
304 list_remove_empty_desc (MonoLockFreeAllocSizeClass *sc)
305 {
306         int num_non_empty = 0;
307         for (;;) {
308                 Descriptor *desc = (Descriptor*) mono_lock_free_queue_dequeue (&sc->partial);
309                 if (!desc)
310                         return;
311                 /*
312                  * We don't need to read atomically because we're the
313                  * only thread that references this descriptor.
314                  */
315                 if (desc->anchor.data.state == STATE_EMPTY) {
316                         desc_retire (desc);
317                 } else {
318                         g_assert (desc->heap->sc == sc);
319                         mono_thread_hazardous_free_or_queue (desc, desc_put_partial, FALSE, TRUE);
320                         if (++num_non_empty >= 2)
321                                 return;
322                 }
323         }
324 }
325
326 static Descriptor*
327 heap_get_partial (MonoLockFreeAllocator *heap)
328 {
329         return list_get_partial (heap->sc);
330 }
331
332 static void
333 heap_put_partial (Descriptor *desc)
334 {
335         list_put_partial (desc);
336 }
337
338 static gboolean
339 set_anchor (Descriptor *desc, Anchor old_anchor, Anchor new_anchor)
340 {
341         if (old_anchor.data.state == STATE_EMPTY)
342                 g_assert (new_anchor.data.state == STATE_EMPTY);
343
344         return InterlockedCompareExchange (&desc->anchor.value, new_anchor.value, old_anchor.value) == old_anchor.value;
345 }
346
347 static gpointer
348 alloc_from_active_or_partial (MonoLockFreeAllocator *heap)
349 {
350         Descriptor *desc;
351         Anchor old_anchor, new_anchor;
352         gpointer addr;
353
354  retry:
355         desc = heap->active;
356         if (desc) {
357                 if (InterlockedCompareExchangePointer ((gpointer * volatile)&heap->active, NULL, desc) != desc)
358                         goto retry;
359         } else {
360                 desc = heap_get_partial (heap);
361                 if (!desc)
362                         return NULL;
363         }
364
365         /* Now we own the desc. */
366
367         do {
368                 unsigned int next;
369                 new_anchor = old_anchor = *(volatile Anchor*)&desc->anchor.value;
370                 if (old_anchor.data.state == STATE_EMPTY) {
371                         /* We must free it because we own it. */
372                         desc_retire (desc);
373                         goto retry;
374                 }
375                 g_assert (old_anchor.data.state == STATE_PARTIAL);
376                 g_assert (old_anchor.data.count > 0);
377
378                 addr = (char*)desc->sb + old_anchor.data.avail * desc->slot_size;
379
380                 mono_memory_read_barrier ();
381
382                 next = *(unsigned int*)addr;
383                 g_assert (next < LOCK_FREE_ALLOC_SB_USABLE_SIZE (desc->block_size) / desc->slot_size);
384
385                 new_anchor.data.avail = next;
386                 --new_anchor.data.count;
387
388                 if (new_anchor.data.count == 0)
389                         new_anchor.data.state = STATE_FULL;
390         } while (!set_anchor (desc, old_anchor, new_anchor));
391
392         /* If the desc is partial we have to give it back. */
393         if (new_anchor.data.state == STATE_PARTIAL) {
394                 if (InterlockedCompareExchangePointer ((gpointer * volatile)&heap->active, desc, NULL) != NULL)
395                         heap_put_partial (desc);
396         }
397
398         return addr;
399 }
400
401 static gpointer
402 alloc_from_new_sb (MonoLockFreeAllocator *heap)
403 {
404         unsigned int slot_size, block_size, count, i;
405         Descriptor *desc = desc_alloc ();
406
407         slot_size = desc->slot_size = heap->sc->slot_size;
408         block_size = desc->block_size = heap->sc->block_size;
409         count = LOCK_FREE_ALLOC_SB_USABLE_SIZE (block_size) / slot_size;
410
411         desc->heap = heap;
412         /*
413          * Setting avail to 1 because 0 is the block we're allocating
414          * right away.
415          */
416         desc->anchor.data.avail = 1;
417         desc->slot_size = heap->sc->slot_size;
418         desc->max_count = count;
419
420         desc->anchor.data.count = desc->max_count - 1;
421         desc->anchor.data.state = STATE_PARTIAL;
422
423         desc->sb = alloc_sb (desc);
424
425         /* Organize blocks into linked list. */
426         for (i = 1; i < count - 1; ++i)
427                 *(unsigned int*)((char*)desc->sb + i * slot_size) = i + 1;
428
429         mono_memory_write_barrier ();
430
431         /* Make it active or free it again. */
432         if (InterlockedCompareExchangePointer ((gpointer * volatile)&heap->active, desc, NULL) == NULL) {
433                 return desc->sb;
434         } else {
435                 desc->anchor.data.state = STATE_EMPTY;
436                 desc_retire (desc);
437                 return NULL;
438         }
439 }
440
441 gpointer
442 mono_lock_free_alloc (MonoLockFreeAllocator *heap)
443 {
444         gpointer addr;
445
446         for (;;) {
447
448                 addr = alloc_from_active_or_partial (heap);
449                 if (addr)
450                         break;
451
452                 addr = alloc_from_new_sb (heap);
453                 if (addr)
454                         break;
455         }
456
457         return addr;
458 }
459
460 void
461 mono_lock_free_free (gpointer ptr, size_t block_size)
462 {
463         Anchor old_anchor, new_anchor;
464         Descriptor *desc;
465         gpointer sb;
466         MonoLockFreeAllocator *heap = NULL;
467
468         desc = *(Descriptor**) sb_header_for_addr (ptr, block_size);
469         g_assert (block_size == desc->block_size);
470
471         sb = desc->sb;
472
473         do {
474                 new_anchor = old_anchor = *(volatile Anchor*)&desc->anchor.value;
475                 *(unsigned int*)ptr = old_anchor.data.avail;
476                 new_anchor.data.avail = ((char*)ptr - (char*)sb) / desc->slot_size;
477                 g_assert (new_anchor.data.avail < LOCK_FREE_ALLOC_SB_USABLE_SIZE (block_size) / desc->slot_size);
478
479                 if (old_anchor.data.state == STATE_FULL)
480                         new_anchor.data.state = STATE_PARTIAL;
481
482                 if (++new_anchor.data.count == desc->max_count) {
483                         heap = desc->heap;
484                         new_anchor.data.state = STATE_EMPTY;
485                 }
486         } while (!set_anchor (desc, old_anchor, new_anchor));
487
488         if (new_anchor.data.state == STATE_EMPTY) {
489                 g_assert (old_anchor.data.state != STATE_EMPTY);
490
491                 if (InterlockedCompareExchangePointer ((gpointer * volatile)&heap->active, NULL, desc) == desc) {
492                         /* We own it, so we free it. */
493                         desc_retire (desc);
494                 } else {
495                         /*
496                          * Somebody else must free it, so we do some
497                          * freeing for others.
498                          */
499                         list_remove_empty_desc (heap->sc);
500                 }
501         } else if (old_anchor.data.state == STATE_FULL) {
502                 /*
503                  * Nobody owned it, now we do, so we need to give it
504                  * back.
505                  */
506
507                 g_assert (new_anchor.data.state == STATE_PARTIAL);
508
509                 if (InterlockedCompareExchangePointer ((gpointer * volatile)&desc->heap->active, desc, NULL) != NULL)
510                         heap_put_partial (desc);
511         }
512 }
513
514 #define g_assert_OR_PRINT(c, format, ...)       do {                            \
515                 if (!(c)) {                                             \
516                         if (print)                                      \
517                                 g_print ((format), ## __VA_ARGS__);     \
518                         else                                            \
519                                 g_assert (FALSE);                               \
520                 }                                                       \
521         } while (0)
522
523 static void
524 descriptor_check_consistency (Descriptor *desc, gboolean print)
525 {
526         int count = desc->anchor.data.count;
527         int max_count = LOCK_FREE_ALLOC_SB_USABLE_SIZE (desc->block_size) / desc->slot_size;
528 #if _MSC_VER
529         gboolean* linked = alloca(max_count*sizeof(gboolean));
530 #else
531         gboolean linked [max_count];
532 #endif
533         int i, last;
534         unsigned int index;
535
536 #ifndef DESC_AVAIL_DUMMY
537         Descriptor *avail;
538
539         for (avail = desc_avail; avail; avail = avail->next)
540                 g_assert_OR_PRINT (desc != avail, "descriptor is in the available list\n");
541 #endif
542
543         g_assert_OR_PRINT (desc->slot_size == desc->heap->sc->slot_size, "slot size doesn't match size class\n");
544
545         if (print)
546                 g_print ("descriptor %p is ", desc);
547
548         switch (desc->anchor.data.state) {
549         case STATE_FULL:
550                 if (print)
551                         g_print ("full\n");
552                 g_assert_OR_PRINT (count == 0, "count is not zero: %d\n", count);
553                 break;
554         case STATE_PARTIAL:
555                 if (print)
556                         g_print ("partial\n");
557                 g_assert_OR_PRINT (count < max_count, "count too high: is %d but must be below %d\n", count, max_count);
558                 break;
559         case STATE_EMPTY:
560                 if (print)
561                         g_print ("empty\n");
562                 g_assert_OR_PRINT (count == max_count, "count is wrong: is %d but should be %d\n", count, max_count);
563                 break;
564         default:
565                 g_assert_OR_PRINT (FALSE, "invalid state\n");
566         }
567
568         for (i = 0; i < max_count; ++i)
569                 linked [i] = FALSE;
570
571         index = desc->anchor.data.avail;
572         last = -1;
573         for (i = 0; i < count; ++i) {
574                 gpointer addr = (char*)desc->sb + index * desc->slot_size;
575                 g_assert_OR_PRINT (index >= 0 && index < max_count,
576                                 "index %d for %dth available slot, linked from %d, not in range [0 .. %d)\n",
577                                 index, i, last, max_count);
578                 g_assert_OR_PRINT (!linked [index], "%dth available slot %d linked twice\n", i, index);
579                 if (linked [index])
580                         break;
581                 linked [index] = TRUE;
582                 last = index;
583                 index = *(unsigned int*)addr;
584         }
585 }
586
587 gboolean
588 mono_lock_free_allocator_check_consistency (MonoLockFreeAllocator *heap)
589 {
590         Descriptor *active = heap->active;
591         Descriptor *desc;
592         if (active) {
593                 g_assert (active->anchor.data.state == STATE_PARTIAL);
594                 descriptor_check_consistency (active, FALSE);
595         }
596         while ((desc = (Descriptor*)mono_lock_free_queue_dequeue (&heap->sc->partial))) {
597                 g_assert (desc->anchor.data.state == STATE_PARTIAL || desc->anchor.data.state == STATE_EMPTY);
598                 descriptor_check_consistency (desc, FALSE);
599         }
600         return TRUE;
601 }
602
603 void
604 mono_lock_free_allocator_init_size_class (MonoLockFreeAllocSizeClass *sc, unsigned int slot_size, unsigned int block_size)
605 {
606         g_assert (block_size > 0);
607         g_assert ((block_size & (block_size - 1)) == 0); /* check if power of 2 */
608         g_assert (slot_size * 2 <= LOCK_FREE_ALLOC_SB_USABLE_SIZE (block_size));
609
610         mono_lock_free_queue_init (&sc->partial);
611         sc->slot_size = slot_size;
612         sc->block_size = block_size;
613 }
614
615 void
616 mono_lock_free_allocator_init_allocator (MonoLockFreeAllocator *heap, MonoLockFreeAllocSizeClass *sc)
617 {
618         heap->sc = sc;
619         heap->active = NULL;
620 }