Logo AND Algorithmique Numérique Distribuée

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