Improve a safety check when writing data into StatBuffer
[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 volatile gboolean forced_stop;
35 static WorkerData *workers_data;
36
37 static SgenSectionGrayQueue workers_distribute_gray_queue;
38 static gboolean workers_distribute_gray_queue_inited;
39
40 /*
41  * Allowed transitions:
42  *
43  * | from \ to          | NOT WORKING | WORKING | WORK ENQUEUED |
44  * |--------------------+-------------+---------+---------------+
45  * | NOT WORKING        | -           | -       | main          |
46  * | WORKING            | worker      | -       | main          |
47  * | WORK ENQUEUED      | -           | worker  | -             |
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 };
61
62 typedef gint32 State;
63
64 static volatile State workers_state;
65
66 static SgenObjectOperations * volatile idle_func_object_ops;
67
68 static guint64 stat_workers_num_finished;
69
70 static gboolean
71 set_state (State old_state, State new_state)
72 {
73         SGEN_ASSERT (0, old_state != new_state, "Why are we transitioning to the same state?");
74         if (new_state == STATE_NOT_WORKING)
75                 SGEN_ASSERT (0, old_state == STATE_WORKING, "We can only transition to NOT WORKING from WORKING");
76         else if (new_state == STATE_WORKING)
77                 SGEN_ASSERT (0, old_state == STATE_WORK_ENQUEUED, "We can only transition to WORKING from WORK ENQUEUED");
78         if (new_state == STATE_NOT_WORKING || new_state == STATE_WORKING)
79                 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");
80
81         return InterlockedCompareExchange (&workers_state, new_state, old_state) == old_state;
82 }
83
84 static gboolean
85 state_is_working_or_enqueued (State state)
86 {
87         return state == STATE_WORKING || state == STATE_WORK_ENQUEUED;
88 }
89
90 void
91 sgen_workers_ensure_awake (void)
92 {
93         State old_state;
94         gboolean did_set_state;
95
96         do {
97                 old_state = workers_state;
98
99                 if (old_state == STATE_WORK_ENQUEUED)
100                         break;
101
102                 did_set_state = set_state (old_state, STATE_WORK_ENQUEUED);
103         } while (!did_set_state);
104
105         if (!state_is_working_or_enqueued (old_state))
106                 sgen_thread_pool_idle_signal ();
107 }
108
109 static void
110 worker_try_finish (void)
111 {
112         State old_state;
113
114         ++stat_workers_num_finished;
115
116         do {
117                 old_state = workers_state;
118
119                 SGEN_ASSERT (0, old_state != STATE_NOT_WORKING, "How did we get from doing idle work to NOT WORKING without setting it ourselves?");
120                 if (old_state == STATE_WORK_ENQUEUED)
121                         return;
122                 SGEN_ASSERT (0, old_state == STATE_WORKING, "What other possibility is there?");
123
124                 /* We are the last thread to go to sleep. */
125         } while (!set_state (old_state, STATE_NOT_WORKING));
126
127         binary_protocol_worker_finish (sgen_timestamp (), forced_stop);
128 }
129
130 void
131 sgen_workers_enqueue_job (SgenThreadPoolJob *job, gboolean enqueue)
132 {
133         if (!enqueue) {
134                 job->func (NULL, job);
135                 sgen_thread_pool_job_free (job);
136                 return;
137         }
138
139         sgen_thread_pool_job_enqueue (job);
140 }
141
142 void
143 sgen_workers_wait_for_jobs_finished (void)
144 {
145         sgen_thread_pool_wait_for_all_jobs ();
146         /*
147          * If the idle task was never triggered or it finished before the last job did and
148          * then didn't get triggered again, we might end up in the situation of having
149          * something in the gray queue yet the idle task not working.  The easiest way to
150          * make sure this doesn't stay that way is to just trigger it again after all jobs
151          * have finished.
152          */
153         sgen_workers_ensure_awake ();
154 }
155
156 static gboolean
157 workers_get_work (WorkerData *data)
158 {
159         SgenMajorCollector *major;
160
161         g_assert (sgen_gray_object_queue_is_empty (&data->private_gray_queue));
162
163         /* If we're concurrent, steal from the workers distribute gray queue. */
164         major = sgen_get_major_collector ();
165         if (major->is_concurrent) {
166                 GrayQueueSection *section = sgen_section_gray_queue_dequeue (&workers_distribute_gray_queue);
167                 if (section) {
168                         sgen_gray_object_enqueue_section (&data->private_gray_queue, section);
169                         return TRUE;
170                 }
171         }
172
173         /* Nobody to steal from */
174         g_assert (sgen_gray_object_queue_is_empty (&data->private_gray_queue));
175         return FALSE;
176 }
177
178 static void
179 concurrent_enqueue_check (GCObject *obj)
180 {
181         g_assert (sgen_concurrent_collection_in_progress ());
182         g_assert (!sgen_ptr_in_nursery (obj));
183         g_assert (SGEN_LOAD_VTABLE (obj));
184 }
185
186 static void
187 init_private_gray_queue (WorkerData *data)
188 {
189         sgen_gray_object_queue_init (&data->private_gray_queue,
190                         sgen_get_major_collector ()->is_concurrent ? concurrent_enqueue_check : NULL);
191 }
192
193 static void
194 thread_pool_init_func (void *data_untyped)
195 {
196         WorkerData *data = (WorkerData *)data_untyped;
197         SgenMajorCollector *major = sgen_get_major_collector ();
198
199         sgen_client_thread_register_worker ();
200
201         if (!major->is_concurrent)
202                 return;
203
204         init_private_gray_queue (data);
205 }
206
207 static gboolean
208 continue_idle_func (void)
209 {
210         return state_is_working_or_enqueued (workers_state);
211 }
212
213 static void
214 marker_idle_func (void *data_untyped)
215 {
216         WorkerData *data = (WorkerData *)data_untyped;
217
218         SGEN_ASSERT (0, continue_idle_func (), "Why are we called when we're not supposed to work?");
219         SGEN_ASSERT (0, sgen_concurrent_collection_in_progress (), "The worker should only mark in concurrent collections.");
220
221         if (workers_state == STATE_WORK_ENQUEUED) {
222                 set_state (STATE_WORK_ENQUEUED, STATE_WORKING);
223                 SGEN_ASSERT (0, workers_state != STATE_NOT_WORKING, "How did we get from WORK ENQUEUED to NOT WORKING?");
224         }
225
226         if (!forced_stop && (!sgen_gray_object_queue_is_empty (&data->private_gray_queue) || workers_get_work (data))) {
227                 ScanCopyContext ctx = CONTEXT_FROM_OBJECT_OPERATIONS (idle_func_object_ops, &data->private_gray_queue);
228
229                 SGEN_ASSERT (0, !sgen_gray_object_queue_is_empty (&data->private_gray_queue), "How is our gray queue empty if we just got work?");
230
231                 sgen_drain_gray_stack (ctx);
232         } else {
233                 worker_try_finish ();
234         }
235 }
236
237 static void
238 init_distribute_gray_queue (void)
239 {
240         if (workers_distribute_gray_queue_inited) {
241                 g_assert (sgen_section_gray_queue_is_empty (&workers_distribute_gray_queue));
242                 g_assert (workers_distribute_gray_queue.locked);
243                 return;
244         }
245
246         sgen_section_gray_queue_init (&workers_distribute_gray_queue, TRUE,
247                         sgen_get_major_collector ()->is_concurrent ? concurrent_enqueue_check : NULL);
248         workers_distribute_gray_queue_inited = TRUE;
249 }
250
251 void
252 sgen_workers_init_distribute_gray_queue (void)
253 {
254         SGEN_ASSERT (0, sgen_get_major_collector ()->is_concurrent,
255                         "Why should we init the distribute gray queue if we don't need it?");
256         init_distribute_gray_queue ();
257 }
258
259 void
260 sgen_workers_init (int num_workers)
261 {
262         int i;
263         void **workers_data_ptrs = (void **)alloca(num_workers * sizeof(void *));
264
265         if (!sgen_get_major_collector ()->is_concurrent) {
266                 sgen_thread_pool_init (num_workers, thread_pool_init_func, NULL, NULL, NULL);
267                 return;
268         }
269
270         //g_print ("initing %d workers\n", num_workers);
271
272         workers_num = num_workers;
273
274         workers_data = (WorkerData *)sgen_alloc_internal_dynamic (sizeof (WorkerData) * num_workers, INTERNAL_MEM_WORKER_DATA, TRUE);
275         memset (workers_data, 0, sizeof (WorkerData) * num_workers);
276
277         init_distribute_gray_queue ();
278
279         for (i = 0; i < workers_num; ++i)
280                 workers_data_ptrs [i] = (void *) &workers_data [i];
281
282         sgen_thread_pool_init (num_workers, thread_pool_init_func, marker_idle_func, continue_idle_func, workers_data_ptrs);
283
284         mono_counters_register ("# workers finished", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_workers_num_finished);
285 }
286
287 void
288 sgen_workers_stop_all_workers (void)
289 {
290         forced_stop = TRUE;
291
292         sgen_thread_pool_wait_for_all_jobs ();
293         sgen_thread_pool_idle_wait ();
294         SGEN_ASSERT (0, workers_state == STATE_NOT_WORKING, "Can only signal enqueue work when in no work state");
295 }
296
297 void
298 sgen_workers_start_all_workers (SgenObjectOperations *object_ops)
299 {
300         forced_stop = FALSE;
301         idle_func_object_ops = object_ops;
302         mono_memory_write_barrier ();
303
304         sgen_workers_ensure_awake ();
305 }
306
307 void
308 sgen_workers_join (void)
309 {
310         int i;
311
312         sgen_thread_pool_wait_for_all_jobs ();
313         sgen_thread_pool_idle_wait ();
314         SGEN_ASSERT (0, workers_state == STATE_NOT_WORKING, "Can only signal enqueue work when in no work state");
315
316         /* At this point all the workers have stopped. */
317
318         SGEN_ASSERT (0, sgen_section_gray_queue_is_empty (&workers_distribute_gray_queue), "Why is there still work left to do?");
319         for (i = 0; i < workers_num; ++i)
320                 SGEN_ASSERT (0, sgen_gray_object_queue_is_empty (&workers_data [i].private_gray_queue), "Why is there still work left to do?");
321 }
322
323 /*
324  * Can only be called if the workers are stopped.
325  * If we're stopped, there are also no pending jobs.
326  */
327 gboolean
328 sgen_workers_have_idle_work (void)
329 {
330         int i;
331
332         SGEN_ASSERT (0, forced_stop && sgen_workers_all_done (), "Checking for idle work should only happen if the workers are stopped.");
333
334         if (!sgen_section_gray_queue_is_empty (&workers_distribute_gray_queue))
335                 return TRUE;
336
337         for (i = 0; i < workers_num; ++i) {
338                 if (!sgen_gray_object_queue_is_empty (&workers_data [i].private_gray_queue))
339                         return TRUE;
340         }
341
342         return FALSE;
343 }
344
345 gboolean
346 sgen_workers_all_done (void)
347 {
348         return workers_state == STATE_NOT_WORKING;
349 }
350
351 /* Must only be used for debugging */
352 gboolean
353 sgen_workers_are_working (void)
354 {
355         return state_is_working_or_enqueued (workers_state);
356 }
357
358 SgenSectionGrayQueue*
359 sgen_workers_get_distribute_section_gray_queue (void)
360 {
361         return &workers_distribute_gray_queue;
362 }
363
364 #endif