Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
context: rewrite some comments, and useless cosmetics
[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 #include "src/simix/smx_private.hpp"
15
16 #include "ContextUnix.hpp"
17
18 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
19
20 /** Many integers are needed to store a pointer
21  *
22  * Support up to two ints. */
23 constexpr int CTX_ADDR_LEN = 2;
24
25 static_assert(sizeof(simgrid::kernel::context::UContext*) <= CTX_ADDR_LEN * sizeof(int),
26               "Ucontexts are not supported on this arch yet");
27
28 namespace simgrid {
29 namespace kernel {
30 namespace context {
31
32 // UContextFactory
33
34 UContextFactory::UContextFactory() : ContextFactory("UContextFactory"), parallel_(SIMIX_context_is_parallel())
35 {
36   UContext::set_maestro(nullptr);
37   if (parallel_)
38     SwappedContext::initialize();
39 }
40
41 UContextFactory::~UContextFactory()
42 {
43   if (parallel_)
44     SwappedContext::finalize();
45 }
46
47 Context* UContextFactory::create_context(std::function<void()> code, void_pfn_smxprocess_t cleanup, smx_actor_t process)
48 {
49   if (parallel_)
50     return new_context<ParallelUContext>(std::move(code), cleanup, process);
51   else
52     return new_context<UContext>(std::move(code), cleanup, process);
53 }
54
55 /* This function is called by maestro at the beginning of a scheduling round to get all working threads executing some
56  * stuff It is much easier to understand what happens if you see the working threads as bodies that swap their soul for
57  * the ones of the simulated processes that must run.
58  */
59 void UContextFactory::run_all()
60 {
61   if (parallel_)
62     ParallelUContext::run_all();
63   else
64     SwappedContext::run_all();
65 }
66
67 // UContext
68
69 UContext::UContext(std::function<void()> code, void_pfn_smxprocess_t cleanup_func, smx_actor_t process)
70     : SwappedContext(std::move(code), cleanup_func, process)
71 {
72   /* if the user provided a function for the process then use it, otherwise it is the context for maestro */
73   if (has_code()) {
74     getcontext(&this->uc_);
75     this->uc_.uc_link = nullptr;
76     this->uc_.uc_stack.ss_sp   = sg_makecontext_stack_addr(this->stack_);
77     this->uc_.uc_stack.ss_size = sg_makecontext_stack_size(smx_context_usable_stack_size);
78 #if PTH_STACKGROWTH == -1
79     ASAN_ONLY(this->asan_stack_ = static_cast<char*>(this->stack_) + smx_context_usable_stack_size);
80 #else
81     ASAN_ONLY(this->asan_stack_ = this->stack_);
82 #endif
83     UContext::make_ctx(&this->uc_, UContext::smx_ctx_sysv_wrapper, this);
84   } else {
85     if (process != nullptr && get_maestro() == nullptr)
86       set_maestro(this);
87   }
88
89 #if SIMGRID_HAVE_MC
90   if (MC_is_active() && has_code()) {
91     MC_register_stack_area(this->stack_, process, &(this->uc_), smx_context_usable_stack_size);
92   }
93 #endif
94 }
95
96 UContext::~UContext() = default;
97
98 // The name of this function is currently hardcoded in the code (as string).
99 // Do not change it without fixing those references as well.
100 void UContext::smx_ctx_sysv_wrapper(int i1, int i2)
101 {
102   // Rebuild the Context* pointer from the integers:
103   int ctx_addr[CTX_ADDR_LEN] = {i1, i2};
104   simgrid::kernel::context::UContext* context;
105   memcpy(&context, ctx_addr, sizeof context);
106
107   ASAN_FINISH_SWITCH(nullptr, &context->asan_ctx_->asan_stack_, &context->asan_ctx_->asan_stack_size_);
108   try {
109     (*context)();
110   } catch (simgrid::kernel::context::Context::StopRequest const&) {
111     XBT_DEBUG("Caught a StopRequest");
112   } catch (simgrid::Exception const& e) {
113     XBT_INFO("Actor killed by an uncatched exception %s", simgrid::xbt::demangle(typeid(e).name()).get());
114     throw;
115   }
116   context->Context::stop();
117   ASAN_ONLY(context->asan_stop_ = true);
118   context->suspend();
119 }
120
121 /** A better makecontext
122  *
123  * Makecontext expects integer arguments, we the context variable is decomposed into a serie of integers and each
124  * integer is passed as argument to makecontext.
125  */
126 void UContext::make_ctx(ucontext_t* ucp, void (*func)(int, int), UContext* arg)
127 {
128   int ctx_addr[CTX_ADDR_LEN]{};
129   memcpy(ctx_addr, &arg, sizeof arg);
130   makecontext(ucp, (void (*)())func, 2, ctx_addr[0], ctx_addr[1]);
131 }
132
133 void UContext::swap_into(SwappedContext* to_)
134 {
135   UContext* to = static_cast<UContext*>(to_);
136   ASAN_ONLY(void* fake_stack = nullptr);
137   ASAN_ONLY(to->asan_ctx_ = from);
138   ASAN_START_SWITCH(from->asan_stop_ ? nullptr : &fake_stack, to->asan_stack_, to->asan_stack_size_);
139   swapcontext(&this->uc_, &to->uc_);
140   ASAN_FINISH_SWITCH(fake_stack, &from->asan_ctx_->asan_stack_, &from->asan_ctx_->asan_stack_size_);
141 }
142
143 void UContext::stop()
144 {
145   Context::stop();
146   throw StopRequest();
147 }
148
149 // ParallelUContext
150
151 void ParallelUContext::run_all()
152 {
153   threads_working_ = 0;
154
155   // We lazily create the parmap so that all options are actually processed when doing so.
156   if (parmap_ == nullptr)
157     parmap_ = new simgrid::xbt::Parmap<smx_actor_t>(SIMIX_context_get_nthreads(), SIMIX_context_get_parallel_mode());
158
159   // Usually, Parmap::apply() executes the provided function on all elements of the array.
160   // Here, the executed function does not return the control to the parmap before all the array is processed:
161   //   - suspend() should switch back to the worker_context (either maestro or one of its minions) to return
162   //     the control to the parmap. Instead, it uses parmap_->next() to steal another work, and does it directly.
163   //     It only yields back to worker_context when the work array is exhausted.
164   //   - So, resume() is only launched from the parmap for the first job of each minion.
165   parmap_->apply(
166       [](smx_actor_t process) {
167         ParallelUContext* context = static_cast<ParallelUContext*>(process->context_);
168         context->resume();
169       },
170       simix_global->process_to_run);
171 }
172
173 /** Run one particular simulated process on the current thread.
174  *
175  * Only applied to the N first elements of the parmap array, where N is the amount of worker threads in the parmap.
176  * See ParallelUContext::run_all for details.
177  */
178 void ParallelUContext::resume()
179 {
180   // Save the thread number (my body) in an os-thread-specific area
181   worker_id_ = threads_working_.fetch_add(1, std::memory_order_relaxed);
182   // Save my current soul (either maestro, or one of the minions) in a permanent area
183   SwappedContext* worker_context = static_cast<SwappedContext*>(self());
184   workers_context_[worker_id_]   = worker_context;
185   // Switch my soul and the actor's one
186   Context::set_current(this);
187   worker_context->swap_into(this);
188   // No body runs that soul anymore at this point, but it is stored in a safe place.
189   // When the executed actor will do a blocking action, SIMIX_process_yield() will call suspend(), below.
190 }
191
192 /** Yield
193  *
194  * This function is called when a simulated process wants to yield back to the maestro in a blocking simcall,
195  * ie in SIMIX_process_yield().
196  *
197  * Actually, it does not really yield back to maestro, but directly into the next executable actor.
198  *
199  * This makes the parmap::apply awkward (see ParallelUContext::run_all()) because it only apply regularly
200  * on the few first elements of the array, but it saves a lot of context switches back to maestro,
201  * and directly forth to the next executable actor.
202  */
203 void ParallelUContext::suspend()
204 {
205   // Get some more work to directly swap into the next executable actor instead of yielding back to the parmap
206   boost::optional<smx_actor_t> next_work = parmap_->next();
207   SwappedContext* next_context;
208   if (next_work) {
209     // There is a next soul to embody (ie, another executable actor)
210     XBT_DEBUG("Run next process");
211     next_context = static_cast<ParallelUContext*>(next_work.get()->context_);
212   } else {
213     // All actors were run, go back to the parmap context
214     XBT_DEBUG("No more processes to run");
215     // worker_id_ is the identity of my body, stored in thread_local when starting the scheduling round
216     next_context = workers_context_[worker_id_];
217     // When given that soul, the body will wait for the next scheduling round
218   }
219
220   // Get the next soul to run, either from another actor or the initial minion's one
221   Context::set_current(next_context);
222   this->swap_into(next_context);
223 }
224
225 XBT_PRIVATE ContextFactory* sysv_factory()
226 {
227   XBT_VERB("Activating SYSV context factory");
228   return new UContextFactory();
229 }
230 }}} // namespace simgrid::kernel::context