Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge s4u wait_any
[simgrid.git] / src / simix / smx_context.cpp
1 /* a fast and simple context switching library                              */
2
3 /* Copyright (c) 2009-2015. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 #include <cerrno>
10 #include <cstring>
11
12 #include <utility>
13 #include <string>
14
15 #include <xbt/config.hpp>
16 #include <xbt/log.h>
17 #include <xbt/range.hpp>
18 #include <xbt/sysdep.h>
19
20 #include "src/internal_config.h"
21 #include "xbt/log.h"
22 #include "xbt/swag.h"
23 #include "xbt/xbt_os_thread.h"
24 #include "smx_private.h"
25 #include "simgrid/sg_config.h"
26 #include "src/internal_config.h"
27 #include "simgrid/modelchecker.h"
28
29
30 #ifdef _WIN32
31 #include <windows.h>
32 #include <malloc.h>
33 #else
34 #include <sys/mman.h>
35 #endif
36
37 #ifdef __MINGW32__ 
38 #define _aligned_malloc __mingw_aligned_malloc 
39 #define _aligned_free  __mingw_aligned_free 
40 #endif //MINGW
41
42 #if HAVE_VALGRIND_H
43 # include <valgrind/valgrind.h>
44 #endif
45
46 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_context, simix, "Context switching mechanism");
47
48 static std::pair<const char*, simgrid::simix::ContextFactoryInitializer> context_factories[] = {
49 #if HAVE_RAW_CONTEXTS
50   { "raw", &simgrid::simix::raw_factory },
51 #endif
52 #if HAVE_UCONTEXT_CONTEXTS
53   { "ucontext", &simgrid::simix::sysv_factory },
54 #endif
55 #if HAVE_BOOST_CONTEXTS
56   { "boost", &simgrid::simix::boost_factory },
57 #endif
58 #if HAVE_THREAD_CONTEXTS
59   { "thread", &simgrid::simix::thread_factory },
60 #endif
61 };
62
63 static_assert(sizeof(context_factories) != 0,
64   "No context factories are enabled for this build");
65
66 // Create the list of possible contexts:
67 static inline
68 std::string contexts_list()
69 {
70   std::string res;
71   const std::size_t n = sizeof(context_factories) / sizeof(context_factories[0]);
72   for (std::size_t i = 1; i != n; ++i) {
73     res += ", ";
74     res += context_factories[i].first;
75   }
76   return res;
77 }
78
79 static simgrid::config::Flag<std::string> context_factory_name(
80   "contexts/factory",
81   (std::string("Possible values: ")+contexts_list()).c_str(),
82   context_factories[0].first);
83
84 int smx_context_stack_size;
85 int smx_context_stack_size_was_set = 0;
86 int smx_context_guard_size;
87 int smx_context_guard_size_was_set = 0;
88 #if HAVE_THREAD_LOCAL_STORAGE
89 static XBT_THREAD_LOCAL smx_context_t smx_current_context_parallel;
90 #else
91 static xbt_os_thread_key_t smx_current_context_key = 0;
92 #endif
93 static smx_context_t smx_current_context_serial;
94 static int smx_parallel_contexts = 1;
95 static int smx_parallel_threshold = 2;
96 static e_xbt_parmap_mode_t smx_parallel_synchronization_mode = XBT_PARMAP_DEFAULT;
97
98 static inline
99 void invalid_context_factory()
100 {
101   XBT_ERROR("Invalid context factory specified. Valid factories on this machine:");
102 #if HAVE_RAW_CONTEXTS
103   XBT_ERROR("  raw: high performance context factory implemented specifically for SimGrid");
104 #else
105   XBT_ERROR("  (raw contexts were disabled at compilation time on this machine -- check configure logs for details)");
106 #endif
107 #if HAVE_UCONTEXT_CONTEXTS
108   XBT_ERROR("  ucontext: classical system V contexts (implemented with makecontext, swapcontext and friends)");
109 #else
110   XBT_ERROR("  (ucontext was disabled at compilation time on this machine -- check configure logs for details)");
111 #endif
112 #if HAVE_BOOST_CONTEXTS
113   XBT_ERROR("  boost: this uses the boost libraries context implementation");
114 #else
115   XBT_ERROR("  (boost was disabled at compilation time on this machine -- check configure logs for details. Did you install the libboost-context-dev package?)");
116 #endif
117   XBT_ERROR("  thread: slow portability layer using pthreads as provided by gcc");
118   xbt_die("Please use a valid factory.");
119 }
120
121 /**
122  * This function is called by SIMIX_global_init() to initialize the context module.
123  */
124 void SIMIX_context_mod_init(void)
125 {
126 #if HAVE_THREAD_CONTEXTS && !HAVE_THREAD_LOCAL_STORAGE
127   /* the __thread storage class is not available on this platform:
128    * use getspecific/setspecific instead to store the current context in each thread */
129   xbt_os_thread_key_create(&smx_current_context_key);
130 #endif
131   if (simix_global->context_factory)
132     return;
133   /* select the context factory to use to create the contexts */
134   if (simgrid::simix::factory_initializer) { // Give Java a chance to hijack the factory mechanism
135     simix_global->context_factory = simgrid::simix::factory_initializer();
136     return;
137   }
138   /* use the factory specified by --cfg=contexts/factory:value */
139   for (auto const& factory : context_factories)
140     if (context_factory_name == factory.first) {
141       simix_global->context_factory = factory.second();
142       break;
143     }
144   if (simix_global->context_factory == nullptr)
145     invalid_context_factory();
146 }
147
148 /**
149  * This function is called by SIMIX_clean() to finalize the context module.
150  */
151 void SIMIX_context_mod_exit(void)
152 {
153   delete simix_global->context_factory;
154   simix_global->context_factory = nullptr;
155 }
156
157 void *SIMIX_context_stack_new(void)
158 {
159   void *stack;
160
161   /* FIXME: current code for stack overflow protection assumes that stacks are
162    * growing downward (PTH_STACKGROWTH == -1).  Protected pages need to be put
163    * after the stack when PTH_STACKGROWTH == 1. */
164
165   if (smx_context_guard_size > 0 && !MC_is_active()) {
166
167 #if !defined(PTH_STACKGROWTH) || (PTH_STACKGROWTH != -1)
168     static int warned_once = 0;
169     if (!warned_once) {
170       XBT_WARN("Stack overflow protection is known to be broken on your system.  Either stack grows upwards, or it was not even tested properly.");
171       warned_once = 1;
172     }
173 #endif
174
175     size_t size = smx_context_stack_size + smx_context_guard_size;
176 #if HAVE_MC
177     /* Cannot use posix_memalign when HAVE_MC. Align stack by hand, and save the
178      * pointer returned by xbt_malloc0. */
179     char *alloc = (char*)xbt_malloc0(size + xbt_pagesize);
180     stack = alloc - ((uintptr_t)alloc & (xbt_pagesize - 1)) + xbt_pagesize;
181     *((void **)stack - 1) = alloc;
182 #elif !defined(_WIN32)
183     if (posix_memalign(&stack, xbt_pagesize, size) != 0)
184       xbt_die("Failed to allocate stack.");
185 #else
186     stack = _aligned_malloc(size, xbt_pagesize);
187 #endif
188
189 #ifndef _WIN32
190     if (mprotect(stack, smx_context_guard_size, PROT_NONE) == -1) {
191       xbt_die("Failed to protect stack: %s", strerror(errno));
192       /* This is fatal. We are going to fail at some point when
193          we tryi reusing this. */
194     }
195 #endif
196     stack = (char *)stack + smx_context_guard_size;
197   } else {
198     stack = xbt_malloc0(smx_context_stack_size);
199   }
200
201 #if HAVE_VALGRIND_H
202   unsigned int valgrind_stack_id = VALGRIND_STACK_REGISTER(stack, (char *)stack + smx_context_stack_size);
203   memcpy((char *)stack + smx_context_usable_stack_size, &valgrind_stack_id, sizeof valgrind_stack_id);
204 #endif
205
206   return stack;
207 }
208
209 void SIMIX_context_stack_delete(void *stack)
210 {
211   if (!stack)
212     return;
213
214 #if HAVE_VALGRIND_H
215   unsigned int valgrind_stack_id;
216   memcpy(&valgrind_stack_id, (char *)stack + smx_context_usable_stack_size, sizeof valgrind_stack_id);
217   VALGRIND_STACK_DEREGISTER(valgrind_stack_id);
218 #endif
219
220 #ifndef _WIN32
221   if (smx_context_guard_size > 0 && !MC_is_active()) {
222     stack = (char *)stack - smx_context_guard_size;
223     if (mprotect(stack, smx_context_guard_size, PROT_READ | PROT_WRITE) == -1) {
224       XBT_WARN("Failed to remove page protection: %s", strerror(errno));
225       /* try to pursue anyway */
226     }
227 #if HAVE_MC
228     /* Retrieve the saved pointer.  See SIMIX_context_stack_new above. */
229     stack = *((void **)stack - 1);
230 #endif
231   }
232 #endif /* not windows */
233
234   xbt_free(stack);
235 }
236
237 /** @brief Returns whether some parallel threads are used for the user contexts. */
238 int SIMIX_context_is_parallel(void) {
239   return smx_parallel_contexts > 1;
240 }
241
242 /**
243  * @brief Returns the number of parallel threads used for the user contexts.
244  * \return the number of threads (1 means no parallelism)
245  */
246 int SIMIX_context_get_nthreads(void) {
247   return smx_parallel_contexts;
248 }
249
250 /**
251  * \brief Sets the number of parallel threads to use
252  * for the user contexts.
253  *
254  * This function should be called before initializing SIMIX.
255  * A value of 1 means no parallelism (1 thread only).
256  * If the value is greater than 1, the thread support must be enabled.
257  *
258  * \param nb_threads the number of threads to use
259  */
260 void SIMIX_context_set_nthreads(int nb_threads) {
261   if (nb_threads<=0) {  
262      nb_threads = xbt_os_get_numcores();
263      XBT_INFO("Auto-setting contexts/nthreads to %d",nb_threads);
264   }   
265 #if !HAVE_THREAD_CONTEXTS
266   xbt_assert(nb_threads == 1, "Parallel runs are impossible when the pthreads are missing.");
267 #endif
268   smx_parallel_contexts = nb_threads;
269 }
270
271 /**
272  * \brief Returns the threshold above which user processes are run in parallel.
273  *
274  * If the number of threads is set to 1, there is no parallelism and this
275  * threshold has no effect.
276  *
277  * \return when the number of user processes ready to run is above
278  * this threshold, they are run in parallel
279  */
280 int SIMIX_context_get_parallel_threshold(void) {
281   return smx_parallel_threshold;
282 }
283
284 /**
285  * \brief Sets the threshold above which user processes are run in parallel.
286  *
287  * If the number of threads is set to 1, there is no parallelism and this
288  * threshold has no effect.
289  *
290  * \param threshold when the number of user processes ready to run is above
291  * this threshold, they are run in parallel
292  */
293 void SIMIX_context_set_parallel_threshold(int threshold) {
294   smx_parallel_threshold = threshold;
295 }
296
297 /**
298  * \brief Returns the synchronization mode used when processes are run in
299  * parallel.
300  * \return how threads are synchronized if processes are run in parallel
301  */
302 e_xbt_parmap_mode_t SIMIX_context_get_parallel_mode(void) {
303   return smx_parallel_synchronization_mode;
304 }
305
306 /**
307  * \brief Sets the synchronization mode to use when processes are run in
308  * parallel.
309  * \param mode how to synchronize threads if processes are run in parallel
310  */
311 void SIMIX_context_set_parallel_mode(e_xbt_parmap_mode_t mode) {
312   smx_parallel_synchronization_mode = mode;
313 }
314
315 /**
316  * \brief Returns the current context of this thread.
317  * \return the current context of this thread
318  */
319 smx_context_t SIMIX_context_get_current(void)
320 {
321   if (SIMIX_context_is_parallel()) {
322 #if HAVE_THREAD_LOCAL_STORAGE
323     return smx_current_context_parallel;
324 #else
325     return xbt_os_thread_get_specific(smx_current_context_key);
326 #endif
327   }
328   else {
329     return smx_current_context_serial;
330   }
331 }
332
333 /**
334  * \brief Sets the current context of this thread.
335  * \param context the context to set
336  */
337 void SIMIX_context_set_current(smx_context_t context)
338 {
339   if (SIMIX_context_is_parallel()) {
340 #if HAVE_THREAD_LOCAL_STORAGE
341     smx_current_context_parallel = context;
342 #else
343     xbt_os_thread_set_specific(smx_current_context_key, context);
344 #endif
345   }
346   else {
347     smx_current_context_serial = context;
348   }
349 }