Logo AND Algorithmique Numérique Distribuée

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