Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
8d7e071a63388186166ca594f222d474d31ef7bf
[simgrid.git] / src / kernel / context / ContextSwapped.cpp
1 /* Copyright (c) 2009-2020. 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 #include "simgrid/Exception.hpp"
7 #include "simgrid/modelchecker.h"
8 #include "src/internal_config.h"
9 #include "src/kernel/actor/ActorImpl.hpp"
10 #include "src/kernel/context/context_private.hpp"
11 #include "src/simix/smx_private.hpp"
12 #include "xbt/parmap.hpp"
13
14 #include "src/kernel/context/ContextSwapped.hpp"
15
16 #ifdef _WIN32
17 #include <malloc.h>
18 #include <windows.h>
19 #else
20 #include <sys/mman.h>
21 #endif
22
23 #ifdef __MINGW32__
24 #define _aligned_malloc __mingw_aligned_malloc
25 #define _aligned_free __mingw_aligned_free
26 #endif /*MINGW*/
27
28 #if HAVE_VALGRIND_H
29 #include <valgrind/valgrind.h>
30 #endif
31
32 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(simix_context);
33
34 // The name of this function is currently hardcoded in MC (as string).
35 // Do not change it without fixing those references as well.
36 void smx_ctx_wrapper(simgrid::kernel::context::SwappedContext* context)
37 {
38 #if HAVE_SANITIZER_ADDRESS_FIBER_SUPPORT
39   __sanitizer_finish_switch_fiber(nullptr, &context->asan_ctx_->asan_stack_, &context->asan_ctx_->asan_stack_size_);
40 #endif
41   try {
42     (*context)();
43     context->Context::stop();
44   } catch (simgrid::ForcefulKillException const&) {
45     XBT_DEBUG("Caught a ForcefulKillException");
46   } catch (simgrid::Exception const& e) {
47     XBT_INFO("Actor killed by an uncaught exception %s", simgrid::xbt::demangle(typeid(e).name()).get());
48     throw;
49   }
50 #if HAVE_SANITIZER_ADDRESS_FIBER_SUPPORT
51   context->asan_stop_ = true;
52 #endif
53   context->suspend();
54   THROW_IMPOSSIBLE;
55 }
56
57 namespace simgrid {
58 namespace kernel {
59 namespace context {
60
61 /* thread-specific storage for the worker's context */
62 thread_local SwappedContext* SwappedContext::worker_context_ = nullptr;
63
64 SwappedContext::SwappedContext(std::function<void()>&& code, smx_actor_t actor, SwappedContextFactory* factory)
65     : Context(std::move(code), actor), factory_(*factory)
66 {
67   // Save maestro (=context created first) in preparation for run_all
68   if (not SIMIX_context_is_parallel() && factory_.maestro_context_ == nullptr)
69     factory_.maestro_context_ = this;
70
71   if (has_code()) {
72     xbt_assert((smx_context_stack_size & 0xf) == 0, "smx_context_stack_size should be multiple of 16");
73     if (smx_context_guard_size > 0 && not MC_is_active()) {
74 #if PTH_STACKGROWTH != -1
75       xbt_die(
76           "Stack overflow protection is known to be broken on your system: you stacks grow upwards (or detection is "
77           "broken). "
78           "Please disable stack guards with --cfg=contexts:guard-size:0");
79       /* Current code for stack overflow protection assumes that stacks are growing downward (PTH_STACKGROWTH == -1).
80        * Protected pages need to be put after the stack when PTH_STACKGROWTH == 1. */
81 #endif
82
83       size_t size = smx_context_stack_size + smx_context_guard_size;
84 #if SIMGRID_HAVE_MC
85       /* Cannot use posix_memalign when SIMGRID_HAVE_MC. Align stack by hand, and save the
86        * pointer returned by xbt_malloc0. */
87       unsigned char* alloc = static_cast<unsigned char*>(xbt_malloc0(size + xbt_pagesize));
88       stack_               = alloc - (reinterpret_cast<uintptr_t>(alloc) & (xbt_pagesize - 1)) + xbt_pagesize;
89       reinterpret_cast<unsigned char**>(stack_)[-1] = alloc;
90 #elif !defined(_WIN32)
91       void* alloc;
92       if (posix_memalign(&alloc, xbt_pagesize, size) != 0)
93         xbt_die("Failed to allocate stack.");
94       this->stack_ = static_cast<unsigned char*>(alloc);
95 #else
96       this->stack_ = static_cast<unsigned char*>(_aligned_malloc(size, xbt_pagesize));
97 #endif
98
99 #ifndef _WIN32
100       if (mprotect(this->stack_, smx_context_guard_size, PROT_NONE) == -1) {
101         xbt_die(
102             "Failed to protect stack: %s.\n"
103             "If you are running a lot of actors, you may be exceeding the amount of mappings allowed per process.\n"
104             "On Linux systems, change this value with sudo sysctl -w vm.max_map_count=newvalue (default value: 65536)\n"
105             "Please see "
106             "https://simgrid.org/doc/latest/Configuring_SimGrid.html#configuring-the-user-code-virtualization for more "
107             "information.",
108             strerror(errno));
109         /* This is fatal. We are going to fail at some point when we try reusing this. */
110       }
111 #endif
112       this->stack_ = this->stack_ + smx_context_guard_size;
113     } else {
114       this->stack_ = static_cast<unsigned char*>(xbt_malloc0(smx_context_stack_size));
115     }
116
117 #if HAVE_VALGRIND_H
118     if (RUNNING_ON_VALGRIND)
119       this->valgrind_stack_id_ = VALGRIND_STACK_REGISTER(this->stack_, this->stack_ + smx_context_stack_size);
120 #endif
121 #if HAVE_SANITIZER_ADDRESS_FIBER_SUPPORT
122     this->asan_stack_ = get_stack_bottom();
123 #endif
124   }
125 }
126
127 SwappedContext::~SwappedContext()
128 {
129   if (stack_ == nullptr) // maestro has no extra stack
130     return;
131
132 #if HAVE_VALGRIND_H
133   if (RUNNING_ON_VALGRIND)
134     VALGRIND_STACK_DEREGISTER(valgrind_stack_id_);
135 #endif
136
137 #ifndef _WIN32
138   if (smx_context_guard_size > 0 && not MC_is_active()) {
139     stack_ = stack_ - smx_context_guard_size;
140     if (mprotect(stack_, smx_context_guard_size, PROT_READ | PROT_WRITE) == -1) {
141       XBT_WARN("Failed to remove page protection: %s", strerror(errno));
142       /* try to pursue anyway */
143     }
144 #if SIMGRID_HAVE_MC
145     /* Retrieve the saved pointer.  See SIMIX_context_stack_new above. */
146     stack_ = reinterpret_cast<unsigned char**>(stack_)[-1];
147 #endif
148   }
149 #endif /* not windows */
150
151   xbt_free(stack_);
152 }
153
154 void SwappedContext::stop()
155 {
156   Context::stop();
157   /* We must cut the actor execution using an exception to properly free the C++ RAII variables */
158   throw ForcefulKillException();
159 }
160
161 /** Maestro wants to run all ready actors */
162 void SwappedContextFactory::run_all()
163 {
164   /* This function is called by maestro at the beginning of a scheduling round to get all working threads executing some
165    * stuff It is much easier to understand what happens if you see the working threads as bodies that swap their soul
166    * for the ones of the simulated processes that must run.
167    */
168   if (SIMIX_context_is_parallel()) {
169     // We lazily create the parmap so that all options are actually processed when doing so.
170     if (parmap_ == nullptr)
171       parmap_.reset(
172           new simgrid::xbt::Parmap<smx_actor_t>(SIMIX_context_get_nthreads(), SIMIX_context_get_parallel_mode()));
173
174     // Usually, Parmap::apply() executes the provided function on all elements of the array.
175     // Here, the executed function does not return the control to the parmap before all the array is processed:
176     //   - suspend() should switch back to the worker_context (either maestro or one of its minions) to return
177     //     the control to the parmap. Instead, it uses parmap_->next() to steal another work, and does it directly.
178     //     It only yields back to worker_context when the work array is exhausted.
179     //   - So, resume() is only launched from the parmap for the first job of each minion.
180     parmap_->apply(
181         [](const actor::ActorImpl* process) {
182           SwappedContext* context = static_cast<SwappedContext*>(process->context_.get());
183           context->resume();
184         },
185         simix_global->actors_to_run);
186   } else { // sequential execution
187     if (simix_global->actors_to_run.empty())
188       return;
189
190     /* maestro is already saved in the first slot of workers_context_ */
191     const actor::ActorImpl* first_actor = simix_global->actors_to_run.front();
192     process_index_          = 1;
193     /* execute the first actor; it will chain to the others when using suspend() */
194     static_cast<SwappedContext*>(first_actor->context_.get())->resume();
195   }
196 }
197
198 /** Maestro wants to yield back to a given actor, so awake it on the current thread
199  *
200  * In parallel, it is only applied to the N first elements of the parmap array,
201  * where N is the amount of worker threads in the parmap.
202  * See SwappedContextFactory::run_all for details.
203  */
204 void SwappedContext::resume()
205 {
206   SwappedContext* old = static_cast<SwappedContext*>(self());
207   if (SIMIX_context_is_parallel()) {
208     // Save my current soul (either maestro, or one of the minions) in a thread-specific area
209     worker_context_ = old;
210   }
211   // Switch my soul and the actor's one
212   Context::set_current(this);
213   old->swap_into(this);
214   // No body runs that soul anymore at this point, but it is stored in a safe place.
215   // When the executed actor will do a blocking action, ActorImpl::yield() will call suspend(), below.
216 }
217
218 /** The actor wants to yield back to maestro, because it is blocked in a simcall (i.e., in ActorImpl::yield())
219  *
220  * Actually, it does not really yield back to maestro, but directly into the next executable actor.
221  *
222  * This makes the parmap::apply awkward (see SwappedContextFactory::run_all()) because it only apply regularly
223  * on the few first elements of the array, but it saves a lot of context switches back to maestro,
224  * and directly forth to the next executable actor.
225  */
226 void SwappedContext::suspend()
227 {
228   SwappedContext* next_context;
229   if (SIMIX_context_is_parallel()) {
230     // Get some more work to directly swap into the next executable actor instead of yielding back to the parmap
231     boost::optional<smx_actor_t> next_work = factory_.parmap_->next();
232     if (next_work) {
233       // There is a next soul to embody (ie, another executable actor)
234       XBT_DEBUG("Run next process");
235       next_context = static_cast<SwappedContext*>(next_work.get()->context_.get());
236     } else {
237       // All actors were run, go back to the parmap context
238       XBT_DEBUG("No more actors to run");
239       // worker_context_ is my own soul, stored in thread_local when starting the scheduling round
240       next_context = worker_context_;
241       // When given that soul, the body will wait for the next scheduling round
242     }
243   } else { // sequential execution
244     /* determine the next context */
245     unsigned long int i = factory_.process_index_;
246     factory_.process_index_++;
247
248     if (i < simix_global->actors_to_run.size()) {
249       /* Actually swap into the next actor directly without transiting to maestro */
250       XBT_DEBUG("Run next actor");
251       next_context = static_cast<SwappedContext*>(simix_global->actors_to_run[i]->context_.get());
252     } else {
253       /* all processes were run, actually return to maestro */
254       XBT_DEBUG("No more actors to run");
255       next_context = factory_.maestro_context_;
256     }
257   }
258   Context::set_current(next_context);
259   this->swap_into(next_context);
260 }
261
262 } // namespace context
263 } // namespace kernel
264 } // namespace simgrid