Logo AND Algorithmique Numérique Distribuée

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