Logo AND Algorithmique Numérique Distribuée

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