Logo AND Algorithmique Numérique Distribuée

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