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 "ContextUnix.hpp"
11 #include "src/mc/mc_ignore.hpp"
12 #include "src/simix/ActorImpl.hpp"
14 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
16 /** Many integers are needed to store a pointer
18 * Support up to two ints. */
19 constexpr int CTX_ADDR_LEN = 2;
21 static_assert(sizeof(simgrid::kernel::context::UContext*) <= CTX_ADDR_LEN * sizeof(int),
22 "Ucontexts are not supported on this arch yet");
24 // The name of this function is currently hardcoded in the code (as string).
25 // Do not change it without fixing those references as well.
26 static void smx_ctx_sysv_wrapper(int i1, int i2)
28 // Rebuild the Context* pointer from the integers:
29 int ctx_addr[CTX_ADDR_LEN] = {i1, i2};
30 simgrid::kernel::context::UContext* context;
31 memcpy(&context, ctx_addr, sizeof context);
35 context->Context::stop();
36 } catch (simgrid::kernel::context::Context::StopRequest const&) {
37 XBT_DEBUG("Caught a StopRequest");
48 UContextFactory::UContextFactory() : ContextFactory("UContextFactory"), parallel_(SIMIX_context_is_parallel())
50 UContext::setMaestro(nullptr);
52 #if HAVE_THREAD_CONTEXTS
53 ParallelUContext::initialize();
55 xbt_die("No thread support for parallel context execution");
60 UContextFactory::~UContextFactory()
62 #if HAVE_THREAD_CONTEXTS
64 ParallelUContext::finalize();
68 Context* UContextFactory::create_context(std::function<void()> code, void_pfn_smxprocess_t cleanup, smx_actor_t process)
70 #if HAVE_THREAD_CONTEXTS
72 return new_context<ParallelUContext>(std::move(code), cleanup, process);
75 return new_context<SerialUContext>(std::move(code), cleanup, process);
78 /* This function is called by maestro at the beginning of a scheduling round to get all working threads executing some
79 * stuff It is much easier to understand what happens if you see the working threads as bodies that swap their soul for
80 * the ones of the simulated processes that must run.
82 void UContextFactory::run_all()
84 #if HAVE_THREAD_CONTEXTS
86 ParallelUContext::run_all();
89 SerialUContext::run_all();
94 UContext* UContext::maestro_context_ = nullptr;
96 UContext::UContext(std::function<void()> code, void_pfn_smxprocess_t cleanup_func, smx_actor_t process)
97 : Context(std::move(code), cleanup_func, process)
99 /* if the user provided a function for the process then use it, otherwise it is the context for maestro */
101 this->stack_ = SIMIX_context_stack_new();
102 getcontext(&this->uc_);
103 this->uc_.uc_link = nullptr;
104 this->uc_.uc_stack.ss_sp = sg_makecontext_stack_addr(this->stack_);
105 this->uc_.uc_stack.ss_size = sg_makecontext_stack_size(smx_context_usable_stack_size);
106 UContext::make_ctx(&this->uc_, UContext::wrapper, this);
108 if (process != nullptr && maestro_context_ == nullptr)
109 maestro_context_ = this;
113 if (MC_is_active() && has_code()) {
114 MC_register_stack_area(this->stack_, process, &(this->uc_), smx_context_usable_stack_size);
119 UContext::~UContext()
121 SIMIX_context_stack_delete(this->stack_);
124 void UContext::wrapper(int i1, int i2)
126 smx_ctx_sysv_wrapper(i1, i2);
129 /** A better makecontext
131 * Makecontext expects integer arguments, we the context variable is decomposed into a serie of integers and each
132 * integer is passed as argument to makecontext.
134 void UContext::make_ctx(ucontext_t* ucp, void (*func)(int, int), UContext* arg)
136 int ctx_addr[CTX_ADDR_LEN]{};
137 memcpy(ctx_addr, &arg, sizeof arg);
138 makecontext(ucp, (void (*)())func, 2, ctx_addr[0], ctx_addr[1]);
141 void UContext::stop()
149 unsigned long SerialUContext::process_index_; /* index of the next process to run in the list of runnable processes */
151 void SerialUContext::suspend()
153 /* determine the next context */
154 SerialUContext* next_context;
155 unsigned long int i = process_index_;
158 if (i < simix_global->process_to_run.size()) {
159 /* execute the next process */
160 XBT_DEBUG("Run next process");
161 next_context = static_cast<SerialUContext*>(simix_global->process_to_run[i]->context);
163 /* all processes were run, return to maestro */
164 XBT_DEBUG("No more process to run");
165 next_context = static_cast<SerialUContext*>(UContext::getMaestro());
167 SIMIX_context_set_current(next_context);
168 UContext::swap(this, next_context);
171 void SerialUContext::resume()
173 SIMIX_context_set_current(this);
174 UContext::swap(UContext::getMaestro(), this);
177 void SerialUContext::run_all()
179 if (simix_global->process_to_run.empty())
181 smx_actor_t first_process = simix_global->process_to_run.front();
183 static_cast<SerialUContext*>(first_process->context)->resume();
188 #if HAVE_THREAD_CONTEXTS
190 simgrid::xbt::Parmap<smx_actor_t>* ParallelUContext::parmap_;
191 std::atomic<uintptr_t> ParallelUContext::threads_working_; /* number of threads that have started their work */
192 xbt_os_thread_key_t ParallelUContext::worker_id_key_; /* thread-specific storage for the thread id */
193 std::vector<ParallelUContext*> ParallelUContext::workers_context_; /* space to save the worker's context
196 void ParallelUContext::initialize()
199 workers_context_.clear();
200 workers_context_.resize(SIMIX_context_get_nthreads(), nullptr);
201 xbt_os_thread_key_create(&worker_id_key_);
204 void ParallelUContext::finalize()
208 workers_context_.clear();
209 xbt_os_thread_key_destroy(worker_id_key_);
212 void ParallelUContext::run_all()
214 threads_working_ = 0;
215 // Parmap_apply ensures that every working thread get an index in the process_to_run array (through an atomic
216 // fetch_and_add), and runs the ParallelUContext::resume function on that index
218 // We lazily create the parmap because the parmap creates context with simix_global->context_factory (which might not
219 // be initialized when bootstrapping):
220 if (parmap_ == nullptr)
221 parmap_ = new simgrid::xbt::Parmap<smx_actor_t>(SIMIX_context_get_nthreads(), SIMIX_context_get_parallel_mode());
223 [](smx_actor_t process) {
224 ParallelUContext* context = static_cast<ParallelUContext*>(process->context);
227 simix_global->process_to_run);
232 * This function is called when a simulated process wants to yield back to the maestro in a blocking simcall. This
233 * naturally occurs within SIMIX_context_suspend(self->context), called from SIMIX_process_yield() Actually, it does not
234 * really yield back to maestro, but into the next process that must be executed. If no one is to be executed, then it
235 * yields to the initial soul that was in this working thread (that was saved in resume_parallel).
237 void ParallelUContext::suspend()
239 /* determine the next context */
240 // Get the next soul to embody now:
241 boost::optional<smx_actor_t> next_work = parmap_->next();
242 ParallelUContext* next_context;
244 // There is a next soul to embody (ie, a next process to resume)
245 XBT_DEBUG("Run next process");
246 next_context = static_cast<ParallelUContext*>(next_work.get()->context);
248 // All processes were run, go to the barrier
249 XBT_DEBUG("No more processes to run");
250 // Get back the identity of my body that was stored when starting the scheduling round
251 uintptr_t worker_id = reinterpret_cast<uintptr_t>(xbt_os_thread_get_specific(worker_id_key_));
252 // Deduce the initial soul of that body
253 next_context = workers_context_[worker_id];
254 // When given that soul, the body will wait for the next scheduling round
257 SIMIX_context_set_current(next_context);
258 // Get the next soul to run, either simulated or initial minion's one:
259 UContext::swap(this, next_context);
262 /** Run one particular simulated process on the current thread. */
263 void ParallelUContext::resume()
265 // What is my containing body?
266 uintptr_t worker_id = threads_working_.fetch_add(1, std::memory_order_relaxed);
267 // Store the number of my containing body in os-thread-specific area :
268 xbt_os_thread_set_specific(worker_id_key_, reinterpret_cast<void*>(worker_id));
269 // Get my current soul:
270 ParallelUContext* worker_context = static_cast<ParallelUContext*>(SIMIX_context_self());
271 // Write down that this soul is hosted in that body (for now)
272 workers_context_[worker_id] = worker_context;
273 // Write in simix that I switched my soul
274 SIMIX_context_set_current(this);
275 // Actually do that using the relevant library call:
276 UContext::swap(worker_context, this);
277 // No body runs that soul anymore at this point. Instead the current body took the soul of simulated process The
278 // simulated process wakes back after the call to "SIMIX_context_suspend(self->context);" within
279 // smx_process.c::SIMIX_process_yield()
281 // From now on, the simulated processes will change their soul with the next soul to execute (in suspend_parallel,
282 // below). When nobody is to be executed in this scheduling round, the last simulated process will take back the
283 // initial soul of the current working thread
288 XBT_PRIVATE ContextFactory* sysv_factory()
290 XBT_VERB("Activating SYSV context factory");
291 return new UContextFactory();
293 }}} // namespace simgrid::kernel::context