Logo AND Algorithmique Numérique Distribuée

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