Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Declare local variables inside the if statement.
[simgrid.git] / src / plugins / host_dvfs.cpp
1 /* Copyright (c) 2010-2022. 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/plugins/dvfs.h>
7 #include <simgrid/plugins/load.h>
8 #include <simgrid/s4u/Actor.hpp>
9 #include <simgrid/s4u/Host.hpp>
10 #include <simgrid/s4u/VirtualMachine.hpp>
11 #include <xbt/asserts.h>
12 #include <xbt/config.hpp>
13
14 #include "src/internal_config.h" // HAVE_SMPI
15 #include "src/kernel/activity/CommImpl.hpp"
16 #include "src/kernel/resource/NetworkModel.hpp"
17 #if HAVE_SMPI
18 #include "src/smpi/include/smpi_request.hpp"
19 #include "src/smpi/plugins/ampi/ampi.hpp"
20 #endif
21
22 #include <boost/algorithm/string.hpp>
23
24 SIMGRID_REGISTER_PLUGIN(host_dvfs, "Dvfs support", &sg_host_dvfs_plugin_init)
25
26 static simgrid::config::Flag<double>
27     cfg_sampling_rate("plugin/dvfs/sampling-rate",
28                       "How often should the dvfs plugin check whether the frequency needs to be changed?", 0.1,
29                       [](double val) {
30                         if (val != 0.1)
31                           sg_host_dvfs_plugin_init();
32                       });
33
34 static simgrid::config::Flag<std::string> cfg_governor("plugin/dvfs/governor",
35                                                        "Which Governor should be used that adapts the CPU frequency?",
36                                                        "performance",
37
38                                                        std::map<std::string, std::string, std::less<>>({
39 #if HAVE_SMPI
40                                                          {"adagio", "TODO: Doc"},
41 #endif
42                                                              {"conservative", "TODO: Doc"}, {"ondemand", "TODO: Doc"},
43                                                              {"performance", "TODO: Doc"}, {"powersave", "TODO: Doc"},
44                                                        }),
45
46                                                        [](const std::string& val) {
47                                                          if (val != "performance")
48                                                            sg_host_dvfs_plugin_init();
49                                                        });
50
51 static simgrid::config::Flag<int>
52     cfg_min_pstate("plugin/dvfs/min-pstate",
53                    "Which pstate is the minimum (and hence fastest) pstate for this governor?", 0);
54
55 static constexpr int MAX_PSTATE_NOT_LIMITED = -1;
56 static simgrid::config::Flag<int>
57     cfg_max_pstate("plugin/dvfs/max-pstate",
58                    "Which pstate is the maximum (and hence slowest) pstate for this governor?", MAX_PSTATE_NOT_LIMITED);
59
60 /** @addtogroup SURF_plugin_load
61
62   This plugin makes it very simple for users to obtain the current load for each host.
63
64 */
65
66 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(host_dvfs, kernel, "Logging specific to the HostDvfs plugin");
67
68 namespace simgrid {
69 namespace plugin {
70
71 namespace dvfs {
72
73 /**
74  *  Add this to your host tag:
75  *    - \<prop id="plugin/dvfs/governor" value="performance" /\>
76  *
77  *  Valid values as of now are: performance, powersave, ondemand, conservative
78  *  It doesn't matter if you use uppercase or lowercase.
79  *
80  *  For the sampling rate, use this:
81  *
82  *    - \<prop id="plugin/dvfs/sampling-rate" value="2" /\>
83  *
84  *  This will run the update() method of the specified governor every 2 seconds
85  *  on that host.
86  *
87  *  These properties can also be used within the \<config\> tag to configure
88  *  these values globally. Using them within the \<host\> will overwrite this
89  *  global configuration
90  */
91 class Governor {
92   simgrid::s4u::Host* const host_;
93   double sampling_rate_;
94   unsigned long min_pstate = cfg_min_pstate; //< Never use a pstate less than this one
95   unsigned long max_pstate = cfg_max_pstate; //< Never use a pstate larger than this one
96
97 public:
98   explicit Governor(simgrid::s4u::Host* ptr)
99       : host_(ptr)
100   {
101     if (cfg_max_pstate == MAX_PSTATE_NOT_LIMITED)
102       max_pstate = host_->get_pstate_count() - 1;
103     init();
104   }
105   virtual ~Governor() = default;
106   virtual std::string get_name() const = 0;
107   simgrid::s4u::Host* get_host() const { return host_; }
108   unsigned long get_min_pstate() const { return min_pstate; }
109   unsigned long get_max_pstate() const { return max_pstate; }
110
111   void init()
112   {
113     if (const char* local_sampling_rate_config = host_->get_property(cfg_sampling_rate.get_name())) {
114       sampling_rate_ = std::stod(local_sampling_rate_config);
115     } else {
116       sampling_rate_ = cfg_sampling_rate;
117     }
118     if (const char* local_min_pstate_config = host_->get_property(cfg_min_pstate.get_name())) {
119       min_pstate = std::stoul(local_min_pstate_config);
120     }
121
122     if (const char* local_max_pstate_config = host_->get_property(cfg_max_pstate.get_name())) {
123       max_pstate = std::stoul(local_max_pstate_config);
124     }
125     xbt_assert(max_pstate <= host_->get_pstate_count() - 1, "Value for max_pstate too large!");
126     xbt_assert(min_pstate <= max_pstate, "min_pstate is larger than max_pstate!");
127   }
128
129   virtual void update()         = 0;
130   double get_sampling_rate() const { return sampling_rate_; }
131 };
132
133 /**
134  * The linux kernel doc describes this governor as follows:
135  * https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt
136  *
137  * > The CPUfreq governor "performance" sets the CPU statically to the
138  * > highest frequency within the borders of scaling_min_freq and
139  * > scaling_max_freq.
140  *
141  * We do not support scaling_min_freq/scaling_max_freq -- we just pick the lowest frequency.
142  */
143 class Performance : public Governor {
144 public:
145   using Governor::Governor;
146   std::string get_name() const override { return "Performance"; }
147
148   void update() override { get_host()->set_pstate(get_min_pstate()); }
149 };
150
151 /**
152  * The linux kernel doc describes this governor as follows:
153  * https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt
154  *
155  * > The CPUfreq governor "powersave" sets the CPU statically to the
156  * > lowest frequency within the borders of scaling_min_freq and
157  * > scaling_max_freq.
158  *
159  * We do not support scaling_min_freq/scaling_max_freq -- we just pick the lowest frequency.
160  */
161 class Powersave : public Governor {
162 public:
163   using Governor::Governor;
164   std::string get_name() const override { return "Powersave"; }
165
166   void update() override { get_host()->set_pstate(get_max_pstate()); }
167 };
168
169 /**
170  * The linux kernel doc describes this governor as follows:
171  * https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt
172  *
173  * > The CPUfreq governor "ondemand" sets the CPU frequency depending on the
174  * > current system load. [...] when triggered, cpufreq checks
175  * > the CPU-usage statistics over the last period and the governor sets the
176  * > CPU accordingly.
177  */
178 class OnDemand : public Governor {
179   /**
180    * See https://elixir.bootlin.com/linux/v4.15.4/source/drivers/cpufreq/cpufreq_ondemand.c
181    * DEF_FREQUENCY_UP_THRESHOLD and od_update()
182    */
183   double freq_up_threshold_ = 0.80;
184
185 public:
186   using Governor::Governor;
187   std::string get_name() const override { return "OnDemand"; }
188
189   void update() override
190   {
191     double load = get_host()->get_core_count() * sg_host_get_avg_load(get_host());
192     sg_host_load_reset(get_host()); // Only consider the period between two calls to this method!
193
194     if (load > freq_up_threshold_) {
195       get_host()->set_pstate(get_min_pstate()); /* Run at max. performance! */
196       XBT_INFO("Load: %f > threshold: %f --> changed to pstate %lu", load, freq_up_threshold_, get_min_pstate());
197     } else {
198       /* The actual implementation uses a formula here: (See Kernel file cpufreq_ondemand.c:158)
199        *
200        *    freq_next = min_f + load * (max_f - min_f) / 100
201        *
202        * So they assume that frequency increases by 100 MHz. We will just use
203        * lowest_pstate - load*pstatesCount()
204        */
205       // Load is now < freq_up_threshold; exclude pstate 0 (the fastest)
206       // because pstate 0 can only be selected if load > freq_up_threshold_
207       auto new_pstate = get_max_pstate() - static_cast<unsigned long>(load) * (get_max_pstate() + 1);
208       if (new_pstate < get_min_pstate())
209         new_pstate = get_min_pstate();
210       get_host()->set_pstate(new_pstate);
211
212       XBT_DEBUG("Load: %f < threshold: %f --> changed to pstate %lu", load, freq_up_threshold_, new_pstate);
213     }
214   }
215 };
216
217 /**
218  * This is the conservative governor, which is very similar to the
219  * OnDemand governor. The Linux Kernel Documentation describes it
220  * very well, see https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt:
221  *
222  * > The CPUfreq governor "conservative", much like the "ondemand"
223  * > governor, sets the CPU frequency depending on the current usage.  It
224  * > differs in behavior in that it gracefully increases and decreases the
225  * > CPU speed rather than jumping to max speed the moment there is any load
226  * > on the CPU. This behavior is more suitable in a battery powered
227  * > environment.
228  */
229 class Conservative : public Governor {
230   double freq_up_threshold_   = .8;
231   double freq_down_threshold_ = .2;
232
233 public:
234   using Governor::Governor;
235   std::string get_name() const override { return "Conservative"; }
236
237   void update() override
238   {
239     double load = get_host()->get_core_count() * sg_host_get_avg_load(get_host());
240     unsigned long pstate = get_host()->get_pstate();
241     sg_host_load_reset(get_host()); // Only consider the period between two calls to this method!
242
243     if (load > freq_up_threshold_) {
244       if (pstate != get_min_pstate()) {
245         get_host()->set_pstate(pstate - 1);
246         XBT_INFO("Load: %f > threshold: %f -> increasing performance to pstate %lu", load, freq_up_threshold_,
247                  pstate - 1);
248       } else {
249         XBT_DEBUG("Load: %f > threshold: %f -> but cannot speed up even more, already in highest pstate %lu", load,
250                   freq_up_threshold_, pstate);
251       }
252     } else if (load < freq_down_threshold_) {
253       if (pstate != get_max_pstate()) { // Are we in the slowest pstate already?
254         get_host()->set_pstate(pstate + 1);
255         XBT_INFO("Load: %f < threshold: %f -> slowing down to pstate %lu", load, freq_down_threshold_, pstate + 1);
256       } else {
257         XBT_DEBUG("Load: %f < threshold: %f -> cannot slow down even more, already in slowest pstate %lu", load,
258                   freq_down_threshold_, pstate);
259       }
260     }
261   }
262 };
263
264 #if HAVE_SMPI
265 class Adagio : public Governor {
266   unsigned long best_pstate = 0;
267   double start_time         = 0;
268   double comp_counter       = 0;
269   double comp_timer         = 0;
270
271   std::vector<std::vector<double>> rates; // Each host + all frequencies of that host
272
273   unsigned int task_id   = 0;
274   bool iteration_running = false; /*< Are we currently between iteration_in and iteration_out calls? */
275
276 public:
277   explicit Adagio(simgrid::s4u::Host* ptr)
278       : Governor(ptr), rates(100, std::vector<double>(ptr->get_pstate_count(), 0.0))
279   {
280     simgrid::smpi::plugin::ampi::on_iteration_in.connect([this](simgrid::s4u::Actor const& actor) {
281       // Every instance of this class subscribes to this event, so one per host
282       // This means that for any actor, all 'hosts' are normally notified of these
283       // changes, even those who don't currently run the actor 'proc_id'.
284       // -> Let's check if this signal call is for us!
285       if (get_host() == actor.get_host()) {
286         iteration_running = true;
287       }
288     });
289     simgrid::smpi::plugin::ampi::on_iteration_out.connect([this](simgrid::s4u::Actor const& actor) {
290       if (get_host() == actor.get_host()) {
291         iteration_running = false;
292         task_id           = 0;
293       }
294     });
295     simgrid::s4u::Exec::on_start_cb([this](simgrid::s4u::Exec const& activity) {
296       if (activity.get_host() == get_host())
297         pre_task();
298     });
299     simgrid::s4u::Activity::on_completion_cb([this](simgrid::s4u::Activity const& activity) {
300       const auto* exec = dynamic_cast<simgrid::s4u::Exec const*>(&activity);
301       if (exec == nullptr) // Only Execs are concerned here
302         return;
303       // For more than one host (not yet supported), we can access the host via
304       // simcalls_.front()->issuer->get_iface()->get_host()
305       if (exec->get_host() == get_host() && iteration_running) {
306         comp_timer += exec->get_finish_time() - exec->get_start_time();
307       }
308     });
309     // FIXME I think that this fires at the same time for all hosts, so when the src sends something,
310     // the dst will be notified even though it didn't even arrive at the recv yet
311     kernel::activity::CommImpl::on_start.connect([this](const kernel::activity::CommImpl& comm) {
312       const auto* act = static_cast<kernel::resource::NetworkAction*>(comm.surf_action_);
313       if ((get_host() == &act->get_src() || get_host() == &act->get_dst()) && iteration_running) {
314         post_task();
315       }
316     });
317   }
318
319   std::string get_name() const override { return "Adagio"; }
320
321   void pre_task()
322   {
323     sg_host_load_reset(get_host());
324     comp_counter = sg_host_get_computed_flops(get_host()); // Should be 0 because of the reset
325     comp_timer   = 0;
326     start_time   = simgrid::s4u::Engine::get_clock();
327     if (rates.size() <= task_id)
328       rates.resize(task_id + 5, std::vector<double>(get_host()->get_pstate_count(), 0.0));
329     if (rates[task_id][best_pstate] == 0)
330       best_pstate = 0;
331     get_host()->set_pstate(best_pstate); // Load our schedule
332     XBT_DEBUG("Set pstate to %lu", best_pstate);
333   }
334
335   void post_task()
336   {
337     double computed_flops = sg_host_get_computed_flops(get_host()) - comp_counter;
338     double target_time    = (simgrid::s4u::Engine::get_clock() - start_time);
339     target_time           = target_time * 99.0 / 100.0; // FIXME We account for t_copy arbitrarily with 1%
340                                                         // -- this needs to be fixed
341
342     bool is_initialized         = rates[task_id][best_pstate] != 0;
343     rates[task_id][best_pstate] = computed_flops / comp_timer;
344     if (not is_initialized) {
345       for (unsigned long i = 1; i < get_host()->get_pstate_count(); i++) {
346         rates[task_id][i] = rates[task_id][0] * (get_host()->get_pstate_speed(i) / get_host()->get_speed());
347       }
348     }
349
350     for (unsigned long pstate = get_host()->get_pstate_count() - 1; pstate != 0; pstate--) {
351       if (computed_flops / rates[task_id][pstate] <= target_time) {
352         // We just found the pstate we want to use!
353         best_pstate = pstate;
354         break;
355       }
356     }
357     task_id++;
358   }
359
360   void update() override {}
361 };
362 #endif
363 } // namespace dvfs
364 } // namespace plugin
365 } // namespace simgrid
366
367 /* **************************** events  callback *************************** */
368 static void on_host_added(simgrid::s4u::Host& host)
369 {
370   if (dynamic_cast<simgrid::s4u::VirtualMachine*>(&host)) // Ignore virtual machines
371     return;
372
373   std::string name              = std::string("dvfs-daemon-") + host.get_cname();
374   simgrid::s4u::ActorPtr daemon = simgrid::s4u::Actor::create(name.c_str(), &host, []() {
375     /**
376      * This lambda function is the function the actor (daemon) will execute
377      * all the time - in the case of the dvfs plugin, this controls when to
378      * lower/raise the frequency.
379      */
380     simgrid::s4u::ActorPtr daemon_proc = simgrid::s4u::Actor::self();
381
382     XBT_DEBUG("DVFS process on %s is a daemon: %d", daemon_proc->get_host()->get_cname(), daemon_proc->is_daemon());
383
384     std::string dvfs_governor;
385     if (const char* host_conf = daemon_proc->get_host()->get_property("plugin/dvfs/governor")) {
386       dvfs_governor = std::string(host_conf);
387       boost::algorithm::to_lower(dvfs_governor);
388     } else {
389       dvfs_governor = cfg_governor;
390       boost::algorithm::to_lower(dvfs_governor);
391     }
392
393     auto governor = [&dvfs_governor, &daemon_proc]() -> std::unique_ptr<simgrid::plugin::dvfs::Governor> {
394       if (dvfs_governor == "conservative")
395         return std::make_unique<simgrid::plugin::dvfs::Conservative>(daemon_proc->get_host());
396       if (dvfs_governor == "ondemand")
397         return std::make_unique<simgrid::plugin::dvfs::OnDemand>(daemon_proc->get_host());
398 #if HAVE_SMPI
399       if (dvfs_governor == "adagio")
400         return std::make_unique<simgrid::plugin::dvfs::Adagio>(daemon_proc->get_host());
401 #endif
402       if (dvfs_governor == "powersave")
403         return std::make_unique<simgrid::plugin::dvfs::Powersave>(daemon_proc->get_host());
404       if (dvfs_governor != "performance")
405         XBT_CRITICAL("No governor specified for host %s, falling back to Performance",
406                      daemon_proc->get_host()->get_cname());
407       return std::make_unique<simgrid::plugin::dvfs::Performance>(daemon_proc->get_host());
408     }();
409
410     while (true) {
411       // Sleep *before* updating; important for startup (i.e., t = 0).
412       // In the beginning, we want to go with the pstates specified in the platform file
413       // (so we sleep first)
414       simgrid::s4u::this_actor::sleep_for(governor->get_sampling_rate());
415       governor->update();
416       XBT_DEBUG("Governor (%s) just updated!", governor->get_name().c_str());
417     }
418
419     XBT_WARN("I should have never reached this point: daemons should be killed when all regular processes are done");
420     return 0;
421   });
422
423   // This call must be placed in this function. Otherwise, the daemonize() call comes too late and
424   // SMPI will take this process as an MPI process!
425   daemon->daemonize();
426 }
427
428 /* **************************** Public interface *************************** */
429
430 /**
431  * @brief Initializes the HostDvfs plugin
432  * @details The HostDvfs plugin provides an API to get the current load of each host.
433  */
434 void sg_host_dvfs_plugin_init()
435 {
436   static bool inited = false;
437   if (inited)
438     return;
439   inited = true;
440
441   sg_host_load_plugin_init();
442
443   simgrid::s4u::Host::on_creation_cb(&on_host_added);
444 }