Logo AND Algorithmique Numérique Distribuée

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