Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
use #if instead if #ifdef for the things in the public config header
[simgrid.git] / src / simix / UContext.cpp
1 /* Copyright (c) 2009-2015. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 /* \file UContext.cpp Context switching with ucontexts from System V         */
8
9 #include <stdarg.h>
10
11 #include <functional>
12 #include <ucontext.h>           /* context relative declarations */
13
14 #include "xbt/parmap.h"
15 #include "src/simix/smx_private.h"
16 #include "src/simix/smx_private.hpp"
17 #include "src/internal_config.h"
18 #include "mc/mc.h"
19
20 /** Many integers are needed to store a pointer
21  *
22  * This is a bit paranoid about sizeof(smx_ctx_sysv_t) not being a multiple
23  * of sizeof(int), but it doesn't harm. */
24 #define CTX_ADDR_LEN                            \
25   (sizeof(void*) / sizeof(int) +       \
26    !!(sizeof(void*) % sizeof(int)))
27
28 /** A better makecontext
29  *
30  * Makecontext expects integer arguments, we the context
31  * variable is decomposed into a serie of integers and
32  * each integer is passed as argument to makecontext. */
33 static void simgrid_makecontext(ucontext_t* ucp, void (*func)(int first, ...), void* arg)
34 {
35   int ctx_addr[CTX_ADDR_LEN];
36   memcpy(ctx_addr, &arg, sizeof(void*));
37   switch (CTX_ADDR_LEN) {
38   case 1:
39     makecontext(ucp, (void (*)())func, 1, ctx_addr[0]);
40     break;
41   case 2:
42     makecontext(ucp, (void (*)()) func, 2, ctx_addr[0], ctx_addr[1]);
43     break;
44   default:
45     xbt_die("Ucontexts are not supported on this arch yet (addr len = %zu/%zu = %zu)", sizeof(void*), sizeof(int), CTX_ADDR_LEN);
46   }
47 }
48
49 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
50
51 namespace simgrid {
52 namespace simix {
53   class UContext;
54   class SerialUContext;
55   class ParallelUContext;
56   class UContextFactory;
57 }
58 }
59
60 #ifdef HAVE_THREAD_CONTEXTS
61 static xbt_parmap_t sysv_parmap;
62 static simgrid::simix::ParallelUContext** sysv_workers_context;   /* space to save the worker's context in each thread */
63 static uintptr_t sysv_threads_working;     /* number of threads that have started their work */
64 static xbt_os_thread_key_t sysv_worker_id_key; /* thread-specific storage for the thread id */
65 #endif
66 static unsigned long sysv_process_index = 0;   /* index of the next process to run in the
67                                                 * list of runnable processes */
68 static simgrid::simix::UContext* sysv_maestro_context;
69 static bool sysv_parallel;
70
71 // The name of this function is currently hardcoded in the code (as string).
72 // Do not change it without fixing those references as well.
73 static void smx_ctx_sysv_wrapper(int first, ...);
74
75 namespace simgrid {
76 namespace simix {
77
78 class UContext : public Context {
79 protected:
80   ucontext_t uc_;         /* the ucontext that executes the code */
81   char *stack_ = nullptr; /* the thread stack */
82 public:
83   friend UContextFactory;
84   UContext(std::function<void()>  code,
85     void_pfn_smxprocess_t cleanup_func, smx_process_t process);
86   ~UContext();
87 };
88
89 class SerialUContext : public UContext {
90 public:
91   SerialUContext(std::function<void()>  code,
92       void_pfn_smxprocess_t cleanup_func, smx_process_t process)
93     : UContext(std::move(code), cleanup_func, process)
94   {}
95   void stop() override;
96   void suspend() override;
97   void resume();
98 };
99
100 class ParallelUContext : public UContext {
101 public:
102   ParallelUContext(std::function<void()>  code,
103       void_pfn_smxprocess_t cleanup_func, smx_process_t process)
104     : UContext(std::move(code), cleanup_func, process)
105   {}
106   void stop() override;
107   void suspend() override;
108   void resume();
109 };
110
111 class UContextFactory : public ContextFactory {
112 public:
113   friend UContext;
114   friend SerialUContext;
115   friend ParallelUContext;
116
117   UContextFactory();
118   virtual ~UContextFactory();
119   virtual Context* create_context(std::function<void()> code,
120     void_pfn_smxprocess_t, smx_process_t process) override;
121   void run_all() override;
122 };
123
124 XBT_PRIVATE ContextFactory* sysv_factory()
125 {
126   XBT_VERB("Activating SYSV context factory");
127   return new UContextFactory();
128 }
129
130 UContextFactory::UContextFactory() : ContextFactory("UContextFactory")
131 {
132   if (SIMIX_context_is_parallel()) {
133     sysv_parallel = true;
134 #ifdef HAVE_THREAD_CONTEXTS  /* To use parallel ucontexts a thread pool is needed */
135     int nthreads = SIMIX_context_get_nthreads();
136     sysv_parmap = nullptr;
137     sysv_workers_context = xbt_new(ParallelUContext*, nthreads);
138     sysv_maestro_context = nullptr;
139     xbt_os_thread_key_create(&sysv_worker_id_key);
140 #else
141     THROWF(arg_error, 0, "No thread support for parallel context execution");
142 #endif
143   } else {
144     sysv_parallel = false;
145   }
146 }
147
148 UContextFactory::~UContextFactory()
149 {
150 #ifdef HAVE_THREAD_CONTEXTS
151   if (sysv_parmap)
152     xbt_parmap_destroy(sysv_parmap);
153   xbt_free(sysv_workers_context);
154 #endif
155 }
156
157 /* This function is called by maestro at the beginning of a scheduling round to get all working threads executing some stuff
158  * It is much easier to understand what happens if you see the working threads as bodies that swap their soul for the
159  *    ones of the simulated processes that must run.
160  */
161 void UContextFactory::run_all()
162 {
163   if (sysv_parallel) {
164     #ifdef HAVE_THREAD_CONTEXTS
165       sysv_threads_working = 0;
166       // Parmap_apply ensures that every working thread get an index in the
167       // process_to_run array (through an atomic fetch_and_add),
168       //  and runs the smx_ctx_sysv_resume_parallel function on that index
169
170       // We lazily create the parmap because the parmap creates context
171       // with simix_global->context_factory (which might not be initialized
172       // when bootstrapping):
173       if (sysv_parmap == nullptr)
174         sysv_parmap = xbt_parmap_new(
175           SIMIX_context_get_nthreads(), SIMIX_context_get_parallel_mode());
176
177       xbt_parmap_apply(sysv_parmap,
178         [](void* arg) {
179           smx_process_t process = (smx_process_t) arg;
180           ParallelUContext* context = static_cast<ParallelUContext*>(process->context);
181           context->resume();
182         },
183         simix_global->process_to_run);
184     #else
185       xbt_die("You asked for a parallel execution, but you don't have any threads.");
186     #endif
187   } else {
188     // Serial:
189       smx_process_t first_process =
190           xbt_dynar_get_as(simix_global->process_to_run, 0, smx_process_t);
191       sysv_process_index = 1;
192       SerialUContext* context =
193         static_cast<SerialUContext*>(first_process->context);
194       context->resume();
195   }
196 }
197
198 Context* UContextFactory::create_context(std::function<void()> code,
199   void_pfn_smxprocess_t cleanup, smx_process_t process)
200 {
201   if (sysv_parallel)
202     return new_context<ParallelUContext>(std::move(code), cleanup, process);
203   else
204     return new_context<SerialUContext>(std::move(code), cleanup, process);
205 }
206
207 UContext::UContext(std::function<void()> code,
208     void_pfn_smxprocess_t cleanup_func, smx_process_t process)
209   : Context(std::move(code), cleanup_func, process)
210 {
211   /* if the user provided a function for the process then use it, otherwise it is the context for maestro */
212   if (has_code()) {
213     this->stack_ = (char*) SIMIX_context_stack_new();
214     getcontext(&this->uc_);
215     this->uc_.uc_link = nullptr;
216     this->uc_.uc_stack.ss_sp   = sg_makecontext_stack_addr(this->stack_);
217     this->uc_.uc_stack.ss_size = sg_makecontext_stack_size(smx_context_usable_stack_size);
218     simgrid_makecontext(&this->uc_, smx_ctx_sysv_wrapper, this);
219   } else {
220     if (process != NULL && sysv_maestro_context == NULL)
221       sysv_maestro_context = this;
222   }
223
224 #if HAVE_MC
225   if (MC_is_active() && has_code()) {
226     MC_register_stack_area(this->stack_, process,
227                       &(this->uc_), smx_context_usable_stack_size);
228   }
229 #endif
230 }
231
232 UContext::~UContext()
233 {
234   SIMIX_context_stack_delete(this->stack_);
235 }
236
237 }
238 }
239
240 static void smx_ctx_sysv_wrapper(int first, ...)
241 {
242   // Rebuild the Context* pointer from the integers:
243   int ctx_addr[CTX_ADDR_LEN];
244   simgrid::simix::UContext* context;
245   ctx_addr[0] = first;
246   if (CTX_ADDR_LEN > 1) {
247     va_list ap;
248     va_start(ap, first);
249     for (unsigned i = 1; i < CTX_ADDR_LEN; i++)
250       ctx_addr[i] = va_arg(ap, int);
251     va_end(ap);
252   }
253   memcpy(&context, ctx_addr, sizeof(simgrid::simix::UContext*));
254
255   (*context)();
256   context->stop();
257 }
258
259 namespace simgrid {
260 namespace simix {
261
262 void SerialUContext::stop()
263 {
264   Context::stop();
265   this->suspend();
266 }
267
268 void SerialUContext::suspend()
269 {
270   /* determine the next context */
271   SerialUContext* next_context = nullptr;
272   unsigned long int i = sysv_process_index++;
273
274   if (i < xbt_dynar_length(simix_global->process_to_run)) {
275     /* execute the next process */
276     XBT_DEBUG("Run next process");
277     next_context = (SerialUContext*) xbt_dynar_get_as(
278         simix_global->process_to_run,i, smx_process_t)->context;
279   }
280   else {
281     /* all processes were run, return to maestro */
282     XBT_DEBUG("No more process to run");
283     next_context = (SerialUContext*) sysv_maestro_context;
284   }
285   SIMIX_context_set_current(next_context);
286   swapcontext(&this->uc_, &next_context->uc_);
287 }
288
289 // UContextSerial
290
291 void SerialUContext::resume()
292 {
293   SIMIX_context_set_current(this);
294   swapcontext(&((SerialUContext*)sysv_maestro_context)->uc_, &this->uc_);
295 }
296
297 void ParallelUContext::stop()
298 {
299   UContext::stop();
300   this->suspend();
301 }
302
303 /** Run one particular simulated process on the current thread. */
304 void ParallelUContext::resume()
305 {
306 #ifdef HAVE_THREAD_CONTEXTS
307   // What is my containing body?
308   uintptr_t worker_id = __sync_fetch_and_add(&sysv_threads_working, 1);
309   // Store the number of my containing body in os-thread-specific area :
310   xbt_os_thread_set_specific(sysv_worker_id_key, (void*) worker_id);
311   // Get my current soul:
312   ParallelUContext* worker_context = (ParallelUContext*) SIMIX_context_self();
313   // Write down that this soul is hosted in that body (for now)
314   sysv_workers_context[worker_id] = worker_context;
315   // Retrieve the system-level info that fuels this soul:
316   ucontext_t* worker_stack = &((ParallelUContext*) worker_context)->uc_;
317   // Write in simix that I switched my soul
318   SIMIX_context_set_current(this);
319    // Actually do that using the relevant library call:
320   swapcontext(worker_stack, &this->uc_);
321   // No body runs that soul anymore at this point.
322   // Instead the current body took the soul of simulated process
323   // The simulated process wakes back after the call to
324   // "SIMIX_context_suspend(self->context);" within
325   // smx_process.c::SIMIX_process_yield()
326
327   // From now on, the simulated processes will change their
328   // soul with the next soul to execute (in suspend_parallel, below).
329   // When nobody is to be executed in this scheduling round,
330   // the last simulated process will take back the initial
331   // soul of the current working thread
332 #endif
333 }
334
335 /** Yield
336  *
337  * This function is called when a simulated process wants to yield back
338  * to the maestro in a blocking simcall. This naturally occurs within
339  * SIMIX_context_suspend(self->context), called from SIMIX_process_yield()
340  * Actually, it does not really yield back to maestro, but into the next
341  * process that must be executed. If no one is to be executed, then it
342  * yields to the initial soul that was in this working thread (that was
343  * saved in resume_parallel).
344  */
345 void ParallelUContext::suspend()
346 {
347 #ifdef HAVE_THREAD_CONTEXTS
348   /* determine the next context */
349   // Get the next soul to embody now:
350   smx_process_t next_work = (smx_process_t) xbt_parmap_next(sysv_parmap);
351   ParallelUContext* next_context = nullptr;
352   // Will contain the next soul to run, either simulated or initial minion's one
353   ucontext_t* next_stack;
354
355   if (next_work != NULL) {
356     // There is a next soul to embody (ie, a next process to resume)
357     XBT_DEBUG("Run next process");
358     next_context = (ParallelUContext*) next_work->context;
359   }
360   else {
361     // All processes were run, go to the barrier
362     XBT_DEBUG("No more processes to run");
363     // Get back the identity of my body that was stored when starting
364     // the scheduling round
365     uintptr_t worker_id =
366         (uintptr_t) xbt_os_thread_get_specific(sysv_worker_id_key);
367     // Deduce the initial soul of that body
368     next_context = (ParallelUContext*) sysv_workers_context[worker_id];
369     // When given that soul, the body will wait for the next scheduling round
370   }
371
372   next_stack = &next_context->uc_;
373
374   SIMIX_context_set_current(next_context);
375   // Get that next soul:
376   swapcontext(&this->uc_, next_stack);
377 #endif
378 }
379
380 }
381 }
382