Logo AND Algorithmique Numérique Distribuée

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