b26234298473a093bf81712b97b50e6fa6515506
[mono.git] / mono / sgen / sgen-workers.c
1 /*
2  * sgen-workers.c: Worker threads for parallel and concurrent GC.
3  *
4  * Copyright 2001-2003 Ximian, Inc
5  * Copyright 2003-2010 Novell, Inc.
6  * Copyright (C) 2012 Xamarin Inc
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License 2.0 as published by the Free Software Foundation;
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License 2.0 along with this library; if not, write to the Free
19  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  */
21
22 #include "config.h"
23 #ifdef HAVE_SGEN_GC
24
25 #include <string.h>
26
27 #include "mono/sgen/sgen-gc.h"
28 #include "mono/sgen/sgen-workers.h"
29 #include "mono/sgen/sgen-thread-pool.h"
30 #include "mono/utils/mono-membar.h"
31 #include "mono/sgen/sgen-client.h"
32
33 static int workers_num;
34 static WorkerData *workers_data;
35
36 static SgenSectionGrayQueue workers_distribute_gray_queue;
37 static gboolean workers_distribute_gray_queue_inited;
38
39 /*
40  * Allowed transitions:
41  *
42  * | from \ to          | NOT WORKING | WORKING | WORK ENQUEUED | NURSERY COLLECTION |
43  * |--------------------+-------------+---------+---------------+--------------------|
44  * | NOT WORKING        | -           | -       | main          | main               |
45  * | WORKING            | worker      | -       | main          | main               |
46  * | WORK ENQUEUED      | -           | worker  | -             | main               |
47  * | NURSERY COLLECTION | -           | -       | main          | -                  |
48  *
49  * The WORK ENQUEUED state guarantees that the worker thread will inspect the queue again at
50  * least once.  Only after looking at the queue will it go back to WORKING, and then,
51  * eventually, to NOT WORKING.  After enqueuing work the main thread transitions the state
52  * to WORK ENQUEUED.  Signalling the worker thread to wake up is only necessary if the old
53  * state was NOT WORKING.
54  */
55
56 enum {
57         STATE_NOT_WORKING,
58         STATE_WORKING,
59         STATE_WORK_ENQUEUED,
60         STATE_NURSERY_COLLECTION
61 };
62
63 typedef gint32 State;
64
65 static volatile State workers_state;
66
67 static SgenObjectOperations * volatile idle_func_object_ops;
68
69 static guint64 stat_workers_num_finished;
70
71 static gboolean
72 set_state (State old_state, State new_state)
73 {
74         SGEN_ASSERT (0, old_state != new_state, "Why are we transitioning to the same state?");
75         if (new_state == STATE_NOT_WORKING)
76                 SGEN_ASSERT (0, old_state == STATE_WORKING, "We can only transition to NOT WORKING from WORKING");
77         else if (new_state == STATE_WORKING)
78                 SGEN_ASSERT (0, old_state == STATE_WORK_ENQUEUED, "We can only transition to WORKING from WORK ENQUEUED");
79         if (new_state == STATE_NOT_WORKING || new_state == STATE_WORKING)
80                 SGEN_ASSERT (6, sgen_thread_pool_is_thread_pool_thread (mono_native_thread_id_get ()), "Only the worker thread is allowed to transition to NOT_WORKING or WORKING");
81
82         return InterlockedCompareExchange (&workers_state, new_state, old_state) == old_state;
83 }
84
85 static void
86 assert_nursery_collection (State state)
87 {
88         SGEN_ASSERT (0, state == STATE_NURSERY_COLLECTION, "Must be in the nursery collection state");
89 }
90
91 static gboolean
92 state_is_working_or_enqueued (State state)
93 {
94         return state == STATE_WORKING || state == STATE_WORK_ENQUEUED;
95 }
96
97 static void
98 workers_signal_enqueue_work (gboolean from_nursery_collection)
99 {
100         State old_state;
101         gboolean did_set_state;
102
103         do {
104                 old_state = workers_state;
105
106                 if (from_nursery_collection)
107                         assert_nursery_collection (old_state);
108                 else
109                         SGEN_ASSERT (0, old_state != STATE_NURSERY_COLLECTION, "If we're not in a nursery collection, how come the state is NURSERY COLLECTION?");
110
111                 if (old_state == STATE_WORK_ENQUEUED)
112                         break;
113
114                 did_set_state = set_state (old_state, STATE_WORK_ENQUEUED);
115                 if (from_nursery_collection)
116                         SGEN_ASSERT (0, did_set_state, "Nobody else should be mutating the state");
117         } while (!did_set_state);
118
119         if (!state_is_working_or_enqueued (old_state))
120                 sgen_thread_pool_idle_signal ();
121 }
122
123 void
124 sgen_workers_ensure_awake (void)
125 {
126         SGEN_ASSERT (0, workers_state != STATE_NURSERY_COLLECTION, "Can't wake workers during nursery collection");
127         workers_signal_enqueue_work (FALSE);
128 }
129
130 static void
131 worker_try_finish (void)
132 {
133         State old_state;
134
135         ++stat_workers_num_finished;
136
137         do {
138                 old_state = workers_state;
139
140                 SGEN_ASSERT (0, old_state != STATE_NOT_WORKING, "How did we get from doing idle work to NOT WORKING without setting it ourselves?");
141                 if (old_state == STATE_NURSERY_COLLECTION)
142                         return;
143                 if (old_state == STATE_WORK_ENQUEUED)
144                         return;
145                 SGEN_ASSERT (0, old_state == STATE_WORKING, "What other possibility is there?");
146
147                 /* We are the last thread to go to sleep. */
148         } while (!set_state (old_state, STATE_NOT_WORKING));
149 }
150
151 static gboolean
152 collection_needs_workers (void)
153 {
154         return sgen_collection_is_concurrent ();
155 }
156
157 void
158 sgen_workers_enqueue_job (SgenThreadPoolJob *job)
159 {
160         if (!collection_needs_workers ()) {
161                 job->func (NULL, job);
162                 sgen_thread_pool_job_free (job);
163                 return;
164         }
165
166         sgen_thread_pool_job_enqueue (job);
167 }
168
169 void
170 sgen_workers_wait_for_jobs_finished (void)
171 {
172         sgen_thread_pool_wait_for_all_jobs ();
173         /*
174          * If the idle task was never triggered or it finished before the last job did and
175          * then didn't get triggered again, we might end up in the situation of having
176          * something in the gray queue yet the idle task not working.  The easiest way to
177          * make sure this doesn't stay that way is to just trigger it again after all jobs
178          * have finished.
179          */
180         sgen_workers_ensure_awake ();
181 }
182
183 void
184 sgen_workers_signal_start_nursery_collection_and_wait (void)
185 {
186         State old_state;
187
188         do {
189                 old_state = workers_state;
190
191                 if (old_state != STATE_NOT_WORKING)
192                         SGEN_ASSERT (0, old_state != STATE_NURSERY_COLLECTION, "Why are we transitioning to NURSERY COLLECTION when we're already there?");
193         } while (!set_state (old_state, STATE_NURSERY_COLLECTION));
194
195         sgen_thread_pool_idle_wait ();
196
197         assert_nursery_collection (workers_state);
198 }
199
200 void
201 sgen_workers_signal_finish_nursery_collection (void)
202 {
203         assert_nursery_collection (workers_state);
204         workers_signal_enqueue_work (TRUE);
205 }
206
207 static gboolean
208 workers_get_work (WorkerData *data)
209 {
210         SgenMajorCollector *major;
211
212         g_assert (sgen_gray_object_queue_is_empty (&data->private_gray_queue));
213
214         /* If we're concurrent, steal from the workers distribute gray queue. */
215         major = sgen_get_major_collector ();
216         if (major->is_concurrent) {
217                 GrayQueueSection *section = sgen_section_gray_queue_dequeue (&workers_distribute_gray_queue);
218                 if (section) {
219                         sgen_gray_object_enqueue_section (&data->private_gray_queue, section);
220                         return TRUE;
221                 }
222         }
223
224         /* Nobody to steal from */
225         g_assert (sgen_gray_object_queue_is_empty (&data->private_gray_queue));
226         return FALSE;
227 }
228
229 static void
230 concurrent_enqueue_check (GCObject *obj)
231 {
232         g_assert (sgen_concurrent_collection_in_progress ());
233         g_assert (!sgen_ptr_in_nursery (obj));
234         g_assert (SGEN_LOAD_VTABLE (obj));
235 }
236
237 static void
238 init_private_gray_queue (WorkerData *data)
239 {
240         sgen_gray_object_queue_init (&data->private_gray_queue,
241                         sgen_get_major_collector ()->is_concurrent ? concurrent_enqueue_check : NULL);
242 }
243
244 static void
245 thread_pool_init_func (void *data_untyped)
246 {
247         WorkerData *data = data_untyped;
248         SgenMajorCollector *major = sgen_get_major_collector ();
249
250         sgen_client_thread_register_worker ();
251
252         if (!major->is_concurrent)
253                 return;
254
255         init_private_gray_queue (data);
256 }
257
258 static gboolean
259 continue_idle_func (void)
260 {
261         return state_is_working_or_enqueued (workers_state);
262 }
263
264 static void
265 marker_idle_func (void *data_untyped)
266 {
267         WorkerData *data = data_untyped;
268
269         if (!continue_idle_func ())
270                 return;
271
272         SGEN_ASSERT (0, sgen_concurrent_collection_in_progress (), "The worker should only mark in concurrent collections.");
273         SGEN_ASSERT (0, sgen_get_current_collection_generation () != GENERATION_NURSERY, "Why are we doing work while there's a nursery collection happening?");
274
275         if (workers_state == STATE_WORK_ENQUEUED) {
276                 set_state (STATE_WORK_ENQUEUED, STATE_WORKING);
277                 SGEN_ASSERT (0, workers_state != STATE_NOT_WORKING, "How did we get from WORK ENQUEUED to NOT WORKING?");
278         }
279
280         if (!sgen_gray_object_queue_is_empty (&data->private_gray_queue) || workers_get_work (data)) {
281                 ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (idle_func_object_ops, &data->private_gray_queue);
282
283                 SGEN_ASSERT (0, !sgen_gray_object_queue_is_empty (&data->private_gray_queue), "How is our gray queue empty if we just got work?");
284
285                 sgen_drain_gray_stack (32, ctx);
286         } else {
287                 worker_try_finish ();
288         }
289 }
290
291 static void
292 init_distribute_gray_queue (void)
293 {
294         if (workers_distribute_gray_queue_inited) {
295                 g_assert (sgen_section_gray_queue_is_empty (&workers_distribute_gray_queue));
296                 g_assert (workers_distribute_gray_queue.locked);
297                 return;
298         }
299
300         sgen_section_gray_queue_init (&workers_distribute_gray_queue, TRUE,
301                         sgen_get_major_collector ()->is_concurrent ? concurrent_enqueue_check : NULL);
302         workers_distribute_gray_queue_inited = TRUE;
303 }
304
305 void
306 sgen_workers_init_distribute_gray_queue (void)
307 {
308         SGEN_ASSERT (0, sgen_get_major_collector ()->is_concurrent && collection_needs_workers (),
309                         "Why should we init the distribute gray queue if we don't need it?");
310         init_distribute_gray_queue ();
311 }
312
313 void
314 sgen_workers_init (int num_workers)
315 {
316         int i;
317         void **workers_data_ptrs = alloca(num_workers * sizeof(void *));
318
319         if (!sgen_get_major_collector ()->is_concurrent) {
320                 sgen_thread_pool_init (num_workers, thread_pool_init_func, NULL, NULL, NULL);
321                 return;
322         }
323
324         //g_print ("initing %d workers\n", num_workers);
325
326         workers_num = num_workers;
327
328         workers_data = sgen_alloc_internal_dynamic (sizeof (WorkerData) * num_workers, INTERNAL_MEM_WORKER_DATA, TRUE);
329         memset (workers_data, 0, sizeof (WorkerData) * num_workers);
330
331         init_distribute_gray_queue ();
332
333         for (i = 0; i < workers_num; ++i)
334                 workers_data_ptrs [i] = (void *) &workers_data [i];
335
336         sgen_thread_pool_init (num_workers, thread_pool_init_func, marker_idle_func, continue_idle_func, workers_data_ptrs);
337
338         mono_counters_register ("# workers finished", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_workers_num_finished);
339 }
340
341 void
342 sgen_workers_start_all_workers (SgenObjectOperations *object_ops)
343 {
344         if (!collection_needs_workers ())
345                 return;
346
347         idle_func_object_ops = object_ops;
348         mono_memory_write_barrier ();
349
350         workers_signal_enqueue_work (FALSE);
351 }
352
353 void
354 sgen_workers_join (void)
355 {
356         int i;
357
358         SGEN_ASSERT (0, workers_state != STATE_NURSERY_COLLECTION, "Can't be in nursery collection when joining");
359
360         if (!collection_needs_workers ())
361                 return;
362
363         sgen_thread_pool_wait_for_all_jobs ();
364         sgen_thread_pool_idle_wait ();
365         SGEN_ASSERT (0, workers_state == STATE_NOT_WORKING, "Can only signal enqueue work when in no work state");
366
367         /* At this point all the workers have stopped. */
368
369         SGEN_ASSERT (0, sgen_section_gray_queue_is_empty (&workers_distribute_gray_queue), "Why is there still work left to do?");
370         for (i = 0; i < workers_num; ++i)
371                 SGEN_ASSERT (0, sgen_gray_object_queue_is_empty (&workers_data [i].private_gray_queue), "Why is there still work left to do?");
372 }
373
374 gboolean
375 sgen_workers_all_done (void)
376 {
377         return workers_state == STATE_NOT_WORKING;
378 }
379
380 /* Must only be used for debugging */
381 gboolean
382 sgen_workers_are_working (void)
383 {
384         return state_is_working_or_enqueued (workers_state);
385 }
386
387 void
388 sgen_workers_wait (void)
389 {
390         sgen_thread_pool_idle_wait ();
391         SGEN_ASSERT (0, sgen_workers_all_done (), "Why are the workers not done after we wait for them?");
392 }
393
394 SgenSectionGrayQueue*
395 sgen_workers_get_distribute_section_gray_queue (void)
396 {
397         return &workers_distribute_gray_queue;
398 }
399
400 #endif