Logo AND Algorithmique Numérique Distribuée

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