Logo AND Algorithmique Numérique Distribuée

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