Logo AND Algorithmique Numérique Distribuée

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