Logo AND Algorithmique Numérique Distribuée

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