Logo AND Algorithmique Numérique Distribuée

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