Logo AND Algorithmique Numérique Distribuée

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