Logo AND Algorithmique Numérique Distribuée

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