Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Remove unused typedefs.
[simgrid.git] / src / kernel / context / ContextUnix.cpp
1 /* Copyright (c) 2009-2017. 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
10 #include "mc/mc.h"
11 #include "src/mc/mc_ignore.h"
12 #include "src/simix/ActorImpl.hpp"
13
14 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
15
16 /** Many integers are needed to store a pointer
17  *
18  * Support up to two ints. */
19 constexpr int CTX_ADDR_LEN = 2;
20
21 static_assert(sizeof(simgrid::kernel::context::UContext*) <= CTX_ADDR_LEN * sizeof(int),
22               "Ucontexts are not supported on this arch yet");
23
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)
27 {
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);
32
33   try {
34     (*context)();
35     context->Context::stop();
36   } catch (simgrid::kernel::context::Context::StopRequest const&) {
37     XBT_DEBUG("Caught a StopRequest");
38   }
39   context->suspend();
40 }
41
42 namespace simgrid {
43 namespace kernel {
44 namespace context {
45
46 // UContextFactory
47
48 UContextFactory::UContextFactory() : ContextFactory("UContextFactory"), parallel_(SIMIX_context_is_parallel())
49 {
50   UContext::setMaestro(nullptr);
51   if (parallel_) {
52 #if HAVE_THREAD_CONTEXTS
53     ParallelUContext::initialize();
54 #else
55     xbt_die("No thread support for parallel context execution");
56 #endif
57   }
58 }
59
60 UContextFactory::~UContextFactory()
61 {
62 #if HAVE_THREAD_CONTEXTS
63   if (parallel_)
64     ParallelUContext::finalize();
65 #endif
66 }
67
68 Context* UContextFactory::create_context(std::function<void()> code, void_pfn_smxprocess_t cleanup, smx_actor_t process)
69 {
70 #if HAVE_THREAD_CONTEXTS
71   if (parallel_)
72     return new_context<ParallelUContext>(std::move(code), cleanup, process);
73   else
74 #endif
75     return new_context<SerialUContext>(std::move(code), cleanup, process);
76 }
77
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.
81  */
82 void UContextFactory::run_all()
83 {
84 #if HAVE_THREAD_CONTEXTS
85   if (parallel_)
86     ParallelUContext::run_all();
87   else
88 #endif
89     SerialUContext::run_all();
90 }
91
92 // UContext
93
94 UContext* UContext::maestro_context_ = nullptr;
95
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)
98 {
99   /* if the user provided a function for the process then use it, otherwise it is the context for maestro */
100   if (has_code()) {
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);
107   } else {
108     if (process != nullptr && maestro_context_ == nullptr)
109       maestro_context_ = this;
110   }
111
112 #if SIMGRID_HAVE_MC
113   if (MC_is_active() && has_code()) {
114     MC_register_stack_area(this->stack_, process, &(this->uc_), smx_context_usable_stack_size);
115   }
116 #endif
117 }
118
119 UContext::~UContext()
120 {
121   SIMIX_context_stack_delete(this->stack_);
122 }
123
124 void UContext::wrapper(int i1, int i2)
125 {
126   smx_ctx_sysv_wrapper(i1, i2);
127 }
128
129 /** A better makecontext
130  *
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.
133  */
134 void UContext::make_ctx(ucontext_t* ucp, void (*func)(int, int), UContext* arg)
135 {
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]);
139 }
140
141 void UContext::stop()
142 {
143   Context::stop();
144   throw StopRequest();
145 }
146
147 // SerialUContext
148
149 unsigned long SerialUContext::process_index_; /* index of the next process to run in the list of runnable processes */
150
151 void SerialUContext::suspend()
152 {
153   /* determine the next context */
154   SerialUContext* next_context;
155   unsigned long int i = process_index_;
156   process_index_++;
157
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);
162   } else {
163     /* all processes were run, return to maestro */
164     XBT_DEBUG("No more process to run");
165     next_context = static_cast<SerialUContext*>(UContext::getMaestro());
166   }
167   SIMIX_context_set_current(next_context);
168   UContext::swap(this, next_context);
169 }
170
171 void SerialUContext::resume()
172 {
173   SIMIX_context_set_current(this);
174   UContext::swap(UContext::getMaestro(), this);
175 }
176
177 void SerialUContext::run_all()
178 {
179   if (simix_global->process_to_run.empty())
180     return;
181   smx_actor_t first_process = simix_global->process_to_run.front();
182   process_index_            = 1;
183   static_cast<SerialUContext*>(first_process->context)->resume();
184 }
185
186 // ParallelUContext
187
188 #if HAVE_THREAD_CONTEXTS
189
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
194                                                                     * in each thread */
195
196 void ParallelUContext::initialize()
197 {
198   parmap_ = nullptr;
199   workers_context_.clear();
200   workers_context_.resize(SIMIX_context_get_nthreads(), nullptr);
201   xbt_os_thread_key_create(&worker_id_key_);
202 }
203
204 void ParallelUContext::finalize()
205 {
206   delete parmap_;
207   parmap_ = nullptr;
208   workers_context_.clear();
209   xbt_os_thread_key_destroy(worker_id_key_);
210 }
211
212 void ParallelUContext::run_all()
213 {
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
217
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());
222   parmap_->apply(
223       [](smx_actor_t process) {
224         ParallelUContext* context = static_cast<ParallelUContext*>(process->context);
225         context->resume();
226       },
227       simix_global->process_to_run);
228 }
229
230 /** Yield
231  *
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).
236  */
237 void ParallelUContext::suspend()
238 {
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;
243   if (next_work) {
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);
247   } else {
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
255   }
256
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);
260 }
261
262 /** Run one particular simulated process on the current thread. */
263 void ParallelUContext::resume()
264 {
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()
280
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
284 }
285
286 #endif
287
288 XBT_PRIVATE ContextFactory* sysv_factory()
289 {
290   XBT_VERB("Activating SYSV context factory");
291   return new UContextFactory();
292 }
293 }}} // namespace simgrid::kernel::context