1 /* Copyright (c) 2009-2018. The SimGrid Team. All rights reserved. */
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. */
6 /* \file UContext.cpp Context switching with ucontexts from System V */
8 #include "context_private.hpp"
11 #include "simgrid/Exception.hpp"
12 #include "src/mc/mc_ignore.hpp"
13 #include "src/simix/ActorImpl.hpp"
15 #include "ContextUnix.hpp"
17 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
19 /** Many integers are needed to store a pointer
21 * Support up to two ints. */
22 constexpr int CTX_ADDR_LEN = 2;
24 static_assert(sizeof(simgrid::kernel::context::UContext*) <= CTX_ADDR_LEN * sizeof(int),
25 "Ucontexts are not supported on this arch yet");
33 UContextFactory::UContextFactory() : ContextFactory("UContextFactory"), parallel_(SIMIX_context_is_parallel())
35 UContext::set_maestro(nullptr);
37 ParallelUContext::initialize();
40 UContextFactory::~UContextFactory()
43 ParallelUContext::finalize();
46 Context* UContextFactory::create_context(std::function<void()> code, void_pfn_smxprocess_t cleanup, smx_actor_t process)
49 return new_context<ParallelUContext>(std::move(code), cleanup, process);
51 return new_context<SerialUContext>(std::move(code), cleanup, process);
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.
58 void UContextFactory::run_all()
61 ParallelUContext::run_all();
63 SerialUContext::run_all();
68 UContext* UContext::maestro_context_ = nullptr;
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)
73 /* if the user provided a function for the process then use it, otherwise it is the context for maestro */
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);
83 ASAN_ONLY(this->asan_stack_ = this->stack_);
85 UContext::make_ctx(&this->uc_, UContext::smx_ctx_sysv_wrapper, this);
87 if (process != nullptr && maestro_context_ == nullptr)
88 maestro_context_ = this;
92 if (MC_is_active() && has_code()) {
93 MC_register_stack_area(this->stack_, process, &(this->uc_), smx_context_usable_stack_size);
100 SIMIX_context_stack_delete(this->stack_);
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)
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);
112 ASAN_FINISH_SWITCH(nullptr, &context->asan_ctx_->asan_stack_, &context->asan_ctx_->asan_stack_size_);
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());
121 context->Context::stop();
122 ASAN_ONLY(context->asan_stop_ = true);
126 /** A better makecontext
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.
131 void UContext::make_ctx(ucontext_t* ucp, void (*func)(int, int), UContext* arg)
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]);
138 inline void UContext::swap(UContext* from, UContext* to)
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_);
147 void UContext::stop()
155 unsigned long SerialUContext::process_index_; /* index of the next process to run in the list of runnable processes */
157 void SerialUContext::suspend()
159 /* determine the next context */
160 SerialUContext* next_context;
161 unsigned long int i = process_index_;
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_);
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());
173 Context::set_current(next_context);
174 UContext::swap(this, next_context);
177 void SerialUContext::resume()
179 Context::set_current(this);
180 UContext::swap(UContext::get_maestro(), this);
183 void SerialUContext::run_all()
185 if (simix_global->process_to_run.empty())
187 smx_actor_t first_process = simix_global->process_to_run.front();
189 static_cast<SerialUContext*>(first_process->context_)->resume();
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
200 void ParallelUContext::initialize()
203 workers_context_.clear();
204 workers_context_.resize(SIMIX_context_get_nthreads(), nullptr);
207 void ParallelUContext::finalize()
211 workers_context_.clear();
214 void ParallelUContext::run_all()
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
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());
225 [](smx_actor_t process) {
226 ParallelUContext* context = static_cast<ParallelUContext*>(process->context_);
229 simix_global->process_to_run);
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).
239 void ParallelUContext::suspend()
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;
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_);
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
258 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);
263 /** Run one particular simulated process on the current thread. */
264 void ParallelUContext::resume()
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*>(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 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()
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
285 XBT_PRIVATE ContextFactory* sysv_factory()
287 XBT_VERB("Activating SYSV context factory");
288 return new UContextFactory();
290 }}} // namespace simgrid::kernel::context